import { t } from "i18next";
import { useCallback, useEffect, useState } from "react";
import { useCopyToClipboard } from "react-use";

import WindowControlBar from "@/components/WindowControlBar";
import { APP_NAME, APP_VERSION, SDK_VERSION } from "@/config";
import { feedbackToast } from "@/utils/common";

import styles from "./index.module.scss";
import LoginForm from "./LoginForm";

export const Login = () => {
  const [_, copyToClipboard] = useCopyToClipboard();
  const [banner, setBanner] = useState<string | null>(null);
  const clearBanner = useCallback(() => setBanner(null), []);

  const handleCopy = () => {
    copyToClipboard(`${`${APP_NAME} ${APP_VERSION}`}/${SDK_VERSION}`);
    feedbackToast({ msg: t("toast.copySuccess") });
  };

  return (
    <div className="relative flex h-full flex-col">
      <div className="app-drag relative h-10 bg-[var(--primary)]">
        <WindowControlBar />
      </div>
      {banner ? <LoginToastBanner text={banner} onDone={clearBanner} /> : null}
      <div className="flex flex-1 items-center justify-center">
        <div
          className={`${styles.login} h-[450px] w-[350px] rounded-xl bg-white p-11`}
          style={{ boxShadow: "0 4px 16px rgba(0,0,0,0.08)" }}
        >
          <LoginForm onBanner={setBanner} />
        </div>
      </div>
      <div
        className="absolute bottom-3 right-3 flex cursor-pointer flex-col items-center text-xs"
        onClick={handleCopy}
      >
        <div className="text-[var(--sub-text)]">{`${APP_NAME} ${APP_VERSION}`}</div>
        <div className="text-[var(--sub-text)]">{SDK_VERSION}</div>
      </div>
    </div>
  );
};

const LoginToastBanner = ({ text, onDone }: { text: string; onDone: () => void }) => {
  const [phase, setPhase] = useState<"in" | "out">("in");

  useEffect(() => {
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const stay = window.setTimeout(() => setPhase("out"), reduce ? 2000 : 2150);
    const done = window.setTimeout(onDone, reduce ? 2000 : 2350);
    return () => {
      window.clearTimeout(stay);
      window.clearTimeout(done);
    };
  }, [onDone]);

  return (
    <div
      className={styles["login-toast"]}
      data-phase={phase}
      style={{ backgroundColor: "var(--warn-text)" }}
    >
      {text}
    </div>
  );
};
