import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { open } from "@tauri-apps/plugin-shell";
import {
  IconUserCircle,
  IconCopy,
  IconCheck,
  IconBrandTelegram,
} from "@tabler/icons-react";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useAuthStore } from "@/store/useAuthStore";
import { getBotUsername } from "@/lib/api";

// Кнопка входа по seed/Telegram на экране VPN. Панель — не полноэкранный
// Dialog (его затемнение перекрывает весь вьюпорт, включая хедер, и блокирует
// клик по бургеру), а собственный поповер с затемнением только ниже хедера —
// тот же приём, что и в BurgerMenu (см. `top-25`), чтобы боковое меню всегда
// оставалось доступным, даже пока эта панель открыта.
export function LoginButton() {
  const { t } = useTranslation();
  const [isOpen, setIsOpen] = useState(false);
  const [seedInput, setSeedInput] = useState("");
  const [codeInput, setCodeInput] = useState("");
  const [copied, setCopied] = useState(false);
  const [botUsername, setBotUsername] = useState<string | null>(null);

  const seed = useAuthStore((s) => s.seed);
  const seedLoading = useAuthStore((s) => s.seedLoading);
  const seedError = useAuthStore((s) => s.seedError);
  const loadSeed = useAuthStore((s) => s.loadSeed);
  const loginSeed = useAuthStore((s) => s.loginSeed);
  const telegramCodeLoading = useAuthStore((s) => s.telegramCodeLoading);
  const telegramCodeError = useAuthStore((s) => s.telegramCodeError);
  const loginTelegramCode = useAuthStore((s) => s.loginTelegramCode);

  useEffect(() => {
    if (isOpen) loadSeed();
  }, [isOpen, loadSeed]);

  useEffect(() => {
    getBotUsername().then(setBotUsername);
  }, []);

  const handleCopy = async () => {
    if (!seed) return;
    await navigator.clipboard.writeText(seed);
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };

  const handleSeedSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!seedInput.trim()) return;
    await loginSeed(seedInput.trim());
  };

  const handleTelegramSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!codeInput.trim()) return;
    await loginTelegramCode(codeInput.trim());
  };

  const handleOpenBot = () => {
    if (botUsername) open(`https://t.me/${botUsername}`).catch(() => {});
  };

  return (
    <>
      <button
        onClick={() => setIsOpen(true)}
        className="absolute top-3 end-3 z-10 flex items-center gap-1.5 rounded-full border border-white/10 bg-background/30 px-3 py-1.5 text-xs font-medium text-foreground/80 backdrop-blur-md transition-colors hover:border-white/20 hover:text-foreground"
      >
        <IconUserCircle className="size-4" />
        {t("login_button")}
      </button>

      {isOpen && (
        <>
          <div
            className="fixed inset-x-0 bottom-0 top-25 z-30 bg-black/20 backdrop-blur-sm"
            onClick={() => setIsOpen(false)}
          />
          <div className="fixed left-1/2 top-25 z-40 mt-4 w-[calc(100%-2rem)] max-w-sm -translate-x-1/2 rounded-2xl border border-white/10 bg-card p-5 shadow-xl animate-in slide-in-from-top-4">
            <h2 className="mb-4 text-base font-semibold">{t("login_title")}</h2>

            <Tabs defaultValue="seed">
              <TabsList className="w-full">
                <TabsTrigger value="seed">{t("login_tab_seed")}</TabsTrigger>
                <TabsTrigger value="telegram">{t("login_tab_telegram")}</TabsTrigger>
              </TabsList>

              <TabsContent value="seed" className="mt-4 flex flex-col gap-4">
                {seed ? (
                  <div>
                    <label className="text-xs font-bold uppercase tracking-widest text-muted-foreground">
                      {t("login_seed_current_label")}
                    </label>
                    <div className="mt-1 flex items-center gap-2">
                      <code className="flex-1 truncate rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-xs font-mono">
                        {seed}
                      </code>
                      <Button type="button" size="icon-sm" variant="outline" onClick={handleCopy}>
                        {copied ? <IconCheck className="size-4" /> : <IconCopy className="size-4" />}
                      </Button>
                    </div>
                  </div>
                ) : (
                  !seedLoading && (
                    <p className="text-sm text-muted-foreground">{t("login_seed_no_seed")}</p>
                  )
                )}

                <form onSubmit={handleSeedSubmit} className="flex flex-col gap-2">
                  <label className="text-xs font-bold uppercase tracking-widest text-muted-foreground">
                    {t("login_seed_input_label")}
                  </label>
                  <input
                    type="text"
                    value={seedInput}
                    onChange={(e) => setSeedInput(e.target.value)}
                    placeholder={t("login_seed_input_placeholder")}
                    className="w-full rounded-xl border border-white/10 bg-white/5 p-3 text-sm text-foreground outline-none transition-colors focus:border-primary"
                  />
                  {seedError && (
                    <p className="text-xs text-destructive">{t("login_seed_invalid")}</p>
                  )}
                  <Button type="submit" disabled={seedLoading}>
                    {t("login_seed_submit")}
                  </Button>
                </form>
              </TabsContent>

              <TabsContent value="telegram" className="mt-4 flex flex-col gap-3">
                <p className="text-sm text-muted-foreground">{t("login_telegram_desc")}</p>

                <Button
                  type="button"
                  variant="outline"
                  onClick={handleOpenBot}
                  disabled={!botUsername}
                  className="gap-2"
                >
                  <IconBrandTelegram className="size-4" />
                  {t("login_telegram_open_bot")}
                </Button>

                <form onSubmit={handleTelegramSubmit} className="flex flex-col gap-2">
                  <label className="text-xs font-bold uppercase tracking-widest text-muted-foreground">
                    {t("login_telegram_code_label")}
                  </label>
                  <input
                    type="text"
                    value={codeInput}
                    onChange={(e) => setCodeInput(e.target.value)}
                    placeholder={t("login_telegram_code_placeholder")}
                    className="w-full rounded-xl border border-white/10 bg-white/5 p-3 text-sm text-foreground outline-none transition-colors focus:border-primary"
                  />
                  {telegramCodeError && (
                    <p className="text-xs text-destructive">{t("login_telegram_error")}</p>
                  )}
                  <Button type="submit" disabled={telegramCodeLoading}>
                    {t("login_telegram_submit")}
                  </Button>
                </form>
              </TabsContent>
            </Tabs>
          </div>
        </>
      )}
    </>
  );
}
