import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Eye, EyeOff } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Mail, Lock, User, Loader2, ArrowLeft, Languages } from "lucide-react";
import niyamahLogo from "@/assets/niyamah-logo.png";
import { toast } from "sonner";
import { useLanguage } from "@/hooks/use-language";

export const Route = createFileRoute("/login")({
  component: LoginPage,
});

type View = "login" | "forgot";

function LoginPage() {
  const navigate = useNavigate();
  const { tr, lang, toggleLang } = useLanguage();
  const [view, setView] = useState<View>("login");
  const [loading, setLoading] = useState(false);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  
  const [showPassword, setShowPassword] = useState(false);

  const handleEmailAuth = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);

    try {
      const { data, error } = await supabase.auth.signInWithPassword({ email, password });
      if (error) throw error;

      // Log login backup event
      if (data.user) {
        const lastBackup = localStorage.getItem("last-login-backup");
        const now = Date.now();
        if (!lastBackup || now - Number(lastBackup) > 30 * 60 * 1000) {
          const d = new Date();
          const fileName = `backup_login_${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, "0")}${String(d.getDate()).padStart(2, "0")}_${String(d.getHours()).padStart(2, "0")}${String(d.getMinutes()).padStart(2, "0")}.zip`;
          const { error: backupError } = await supabase.from("backups").insert({
            type: "login",
            file_name: fileName,
            size_bytes: 0,
            status: "completed",
            tables_included: ["all"],
            created_by: data.user.id,
          });

          if (backupError) {
            console.warn("Login backup log skipped:", backupError.message);
          } else {
            localStorage.setItem("last-login-backup", String(now));
          }
        }
      }

      toast.success(tr("loginSuccess"));
      navigate({ to: "/" });
    } catch (error: unknown) {
      const message = error instanceof Error ? error.message : tr("somethingWrong");
      toast.error(message);
    } finally {
      setLoading(false);
    }
  };

  const handleForgotPassword = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      const { error } = await supabase.auth.resetPasswordForEmail(email, {
        redirectTo: `${window.location.origin}/reset-password`,
      });
      if (error) throw error;
      toast.success(tr("resetLinkSent"));
    } catch (error: unknown) {
      const message = error instanceof Error ? error.message : tr("somethingWrong");
      toast.error(message);
    } finally {
      setLoading(false);
    }
  };

  const title = view === "login" ? tr("loginTitle") : tr("forgotTitle");

  return (
    <div className="flex min-h-screen items-center justify-center bg-background p-4">
      {loading && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm">
          <div className="flex flex-col items-center gap-3">
            <Loader2 className="h-10 w-10 animate-spin text-primary" />
            <p className="text-sm font-medium text-muted-foreground">
              {view === "login" ? (lang === "bn" ? "লগইন হচ্ছে..." : "Signing in...") : (lang === "bn" ? "লিংক পাঠানো হচ্ছে..." : "Sending link...")}
            </p>
          </div>
        </div>
      )}
      <Card className="w-full max-w-md border-border shadow-xl">
        <CardHeader className="space-y-3 text-center">
          <div className="flex justify-end">
            <button
              onClick={toggleLang}
              className="flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground transition-colors"
            >
              <Languages className="h-3.5 w-3.5" />
              {lang === "bn" ? "English" : "বাংলা"}
            </button>
          </div>
          <div className="relative mx-auto" style={{ width: "min(140px, 35vw)", height: "min(140px, 35vw)" }}>
            <div className="absolute inset-0 rounded-full border-2 border-violet-400/30 animate-[logoRing1_3s_ease-in-out_infinite]" />
            <div className="absolute inset-[-8px] rounded-full border border-fuchsia-400/20 animate-[logoRing2_3s_ease-in-out_infinite_0.5s]" />
            <div className="absolute inset-[-16px] rounded-full border border-violet-300/10 animate-[logoRing3_3s_ease-in-out_infinite_1s]" />
            <div className="absolute inset-0 rounded-full bg-gradient-to-br from-violet-500/40 to-fuchsia-500/40 blur-xl animate-[logoPulse_2.5s_ease-in-out_infinite]" />
            <div className="relative z-10 w-full h-full rounded-full bg-white grid place-items-center shadow-2xl shadow-violet-500/50 ring-4 ring-violet-400/40 overflow-hidden animate-[logoFloat_4s_ease-in-out_infinite]">
              <img src={niyamahLogo} alt="Niyamah" className="h-full w-full object-cover scale-110" />
            </div>
          </div>
          <style>{`
            @keyframes logoPulse { 0%,100% { transform: scale(0.95); opacity: 0.6; } 50% { transform: scale(1.15); opacity: 1; } }
            @keyframes logoFloat { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-6px); } }
            @keyframes logoRing1 { 0%,100% { transform: scale(1); opacity: 0.3; } 50% { transform: scale(1.08); opacity: 0.6; } }
            @keyframes logoRing2 { 0%,100% { transform: scale(1); opacity: 0.2; } 50% { transform: scale(1.12); opacity: 0.4; } }
            @keyframes logoRing3 { 0%,100% { transform: scale(1); opacity: 0.1; } 50% { transform: scale(1.18); opacity: 0.25; } }
          `}</style>

          <CardTitle className="text-2xl font-bold">Niyamah ERP</CardTitle>
          <CardDescription>{title}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {view === "forgot" ? (
            <form onSubmit={handleForgotPassword} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="email" className="text-base">{tr("email")}</Label>
                <div className="relative">
                  <Mail className="absolute left-3.5 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground" />
                  <Input
                    id="email"
                    type="email"
                    inputMode="email"
                    autoComplete="email"
                    autoFocus
                    placeholder="you@example.com"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="pl-11 h-12 text-base"
                    required
                  />
                </div>
              </div>
              <Button type="submit" className="w-full h-12 text-base" disabled={loading}>
                {loading && <Loader2 className="mr-2 h-5 w-5 animate-spin" />}
                {tr("sendResetLink")}
              </Button>
              <button
                type="button"
                onClick={() => setView("login")}
                className="flex w-full items-center justify-center gap-1 text-sm text-muted-foreground hover:text-foreground"
              >
                <ArrowLeft className="h-3.5 w-3.5" />
                {tr("backToLogin")}
              </button>
            </form>
          ) : (
            <>
              <form onSubmit={handleEmailAuth} className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="email" className="text-base">{tr("email")}</Label>
                  <div className="relative">
                    <Mail className="absolute left-3.5 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground" />
                    <Input
                      id="email"
                      type="email"
                      inputMode="email"
                      autoComplete="email"
                      autoFocus
                      placeholder="you@example.com"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      className="pl-11 h-12 text-base"
                      required
                    />
                  </div>
                </div>
                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <Label htmlFor="password" className="text-base">{tr("password")}</Label>
                    <button
                      type="button"
                      onClick={() => setView("forgot")}
                      className="text-sm text-primary hover:underline"
                    >
                      {tr("forgotPassword")}
                    </button>
                  </div>
                  <div className="relative">
                    <Lock className="absolute left-3.5 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground" />
                    <Input
                      id="password"
                      type={showPassword ? "text" : "password"}
                      inputMode="text"
                      autoComplete="current-password"
                      placeholder="••••••••"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      className="pl-11 pr-11 h-12 text-base"
                      required
                      minLength={6}
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-3.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                      tabIndex={-1}
                    >
                      {showPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                    </button>
                  </div>
                </div>
                <Button type="submit" className="w-full h-12 text-base" disabled={loading}>
                  {loading && <Loader2 className="mr-2 h-5 w-5 animate-spin" />}
                  {tr("login")}
                </Button>
              </form>
            </>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
