import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { open } from "@tauri-apps/plugin-shell";
import { 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";

// Экран-шлюз перед подключением к VPN: пока юзер явно не вошёл (анонимно,
// по seed или через Telegram), сюда рендерится этот экран вместо Home
// (см. App.tsx) — без этого экрана нет доступа к экрану включения VPN.
export function Login() {
  const { t } = useTranslation();
  const [seedInput, setSeedInput] = useState("");
  const [codeInput, setCodeInput] = useState("");
  const [botUsername, setBotUsername] = useState<string | null>(null);

  const seedLoading = useAuthStore((s) => s.seedLoading);
  const seedError = useAuthStore((s) => s.seedError);
  const continueAnonymously = useAuthStore((s) => s.continueAnonymously);
  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(() => {
    getBotUsername().then(setBotUsername);
  }, []);

  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 (
    <div className="w-full max-w-sm mx-auto flex flex-col items-center gap-8 px-6 py-12">
      <div className="text-center space-y-2">
        <h1 className="text-2xl font-extrabold tracking-tight text-foreground">
          {t("login_screen_title")}
        </h1>
        <p className="text-sm text-muted-foreground">{t("login_screen_subtitle")}</p>
      </div>

      <Button
        type="button"
        size="lg"
        className="w-full"
        disabled={seedLoading}
        onClick={continueAnonymously}
      >
        {t("login_screen_continue_anon")}
      </Button>
      {seedError === "anon_failed" && (
        <p className="-mt-6 text-xs text-destructive">{t("login_anon_error")}</p>
      )}

      <div className="flex items-center gap-3 w-full">
        <div className="h-px flex-1 bg-border/50" />
        <span className="text-xs uppercase tracking-widest text-muted-foreground">
          {t("login_screen_or")}
        </span>
        <div className="h-px flex-1 bg-border/50" />
      </div>

      <Tabs defaultValue="seed" className="w-full">
        <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">
          <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 === "invalid_seed" && (
              <p className="text-xs text-destructive">{t("login_seed_invalid")}</p>
            )}
            <Button type="submit" variant="outline" 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>
  );
}
