import { createFileRoute, useRouter } from "@tanstack/react-router";
import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { toast } from "sonner";
import { Store, Loader2 } from "lucide-react";
import { useT } from "@/lib/i18n";

export const Route = createFileRoute("/auth")({
  ssr: false,
  head: () => ({ meta: [{ title: "Helpgate Inventory — লগ ইন" }] }),
  component: AuthPage,
});

function AuthPage() {
  const router = useRouter();
  const { t, lang, setLang } = useT();
  const [mode, setMode] = useState<"signin" | "signup">("signin");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [shopName, setShopName] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    supabase.auth.getUser().then(({ data }) => {
      if (data.user) router.navigate({ to: "/" });
    });
  }, [router]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      if (mode === "signup") {
        const { error } = await supabase.auth.signUp({
          email, password,
          options: {
            emailRedirectTo: `${window.location.origin}/`,
            data: { shop_name: shopName || (lang === "bn" ? "আমার দোকান" : "My Shop") },
          },
        });
        if (error) throw error;
        toast.success(lang === "bn" ? "অ্যাকাউন্ট তৈরি হয়েছে" : "Account created");
      } else {
        const { error } = await supabase.auth.signInWithPassword({ email, password });
        if (error) throw error;
        toast.success(lang === "bn" ? "স্বাগতম!" : "Welcome!");
      }
      router.navigate({ to: "/" });
    } catch (err: any) {
      toast.error(err?.message ?? "Error");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen grid lg:grid-cols-2 bg-background">
      {/* Left: branding */}
      <div className="hidden lg:flex relative gradient-primary text-white p-12 flex-col justify-between overflow-hidden">
        <div className="absolute inset-0 opacity-20" style={{
          backgroundImage: "radial-gradient(circle at 20% 30%, white 1px, transparent 1px), radial-gradient(circle at 80% 70%, white 1px, transparent 1px)",
          backgroundSize: "40px 40px, 60px 60px"
        }} />
        <div className="relative z-10">
          <div className="flex items-center gap-3">
            <div className="size-12 rounded-2xl bg-white/20 backdrop-blur grid place-items-center">
              <Store className="size-6" />
            </div>
            <div>
              <div className="text-2xl font-extrabold">Helpgate Inventory</div>
              <div className="text-sm text-white/70">Developed by Md Waliduzzaman Sarder</div>
            </div>
          </div>
        </div>
        <div className="relative z-10 space-y-6">
          <h1 className="text-4xl xl:text-5xl font-extrabold leading-tight">
            বাংলাদেশের <br /> ব্যবসার জন্য <br /> <span className="text-white/90">সম্পূর্ণ সমাধান</span>
          </h1>
          <p className="text-white/80 text-lg max-w-md">
            POS, ইনভেন্টরি, ইনভয়েস, কাস্টমার ও সাপ্লায়ার বকেয়া, রিপোর্ট — সব এক জায়গায়।
          </p>
          <div className="grid grid-cols-2 gap-3 max-w-md">
            {["📱 মোবাইল শপ", "💻 ইলেকট্রনিক্স", "👕 ফ্যাশন", "🛒 গ্রোসারি", "💊 ফার্মেসি", "🔧 হার্ডওয়্যার"].map((x) => (
              <div key={x} className="bg-white/10 backdrop-blur rounded-lg px-3 py-2 text-sm font-medium">{x}</div>
            ))}
          </div>
        </div>
        <div className="relative z-10 text-xs text-white/60">
          📞 Hotline: 01722427373
        </div>
      </div>

      {/* Right: form */}
      <div className="flex items-center justify-center p-6 lg:p-12">
        <div className="w-full max-w-md space-y-6">
          <div className="flex justify-between items-center">
            <div className="lg:hidden flex items-center gap-2">
              <div className="size-10 rounded-xl gradient-primary grid place-items-center text-white"><Store className="size-5" /></div>
              <span className="font-extrabold">Helpgate Inventory</span>
            </div>
            <button onClick={() => setLang(lang === "bn" ? "en" : "bn")} className="text-xs font-bold text-muted-foreground hover:text-foreground ml-auto">
              {lang === "bn" ? "English" : "বাংলা"}
            </button>
          </div>
          <div>
            <h2 className="text-3xl font-extrabold">{mode === "signin" ? t("sign_in") : t("sign_up")}</h2>
            <p className="text-muted-foreground mt-1 text-sm">
              {mode === "signin" ? (lang === "bn" ? "আপনার অ্যাকাউন্টে প্রবেশ করুন" : "Sign in to your account") : (lang === "bn" ? "নতুন অ্যাকাউন্ট তৈরি করুন" : "Create a new account")}
            </p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-4">
            {mode === "signup" && (
              <Field label={t("shop_name")}>
                <Input value={shopName} onChange={(e) => setShopName(e.target.value)} placeholder={lang === "bn" ? "রহিম স্টোর" : "My Store"} />
              </Field>
            )}
            <Field label={t("email")}>
              <Input type="email" required value={email} onChange={(e) => setEmail(e.target.value)} />
            </Field>
            <Field label={t("password")}>
              <Input type="password" required minLength={6} value={password} onChange={(e) => setPassword(e.target.value)} />
            </Field>
            <Button type="submit" className="w-full h-11 gradient-primary text-white font-bold shadow-elegant hover:opacity-95" disabled={loading}>
              {loading ? <Loader2 className="size-4 animate-spin" /> : mode === "signin" ? t("sign_in") : t("sign_up")}
            </Button>
          </form>

          <div className="text-center text-sm text-muted-foreground">
            {mode === "signin" ? t("no_account") : t("have_account")}{" "}
            <button type="button" onClick={() => setMode(mode === "signin" ? "signup" : "signin")} className="text-primary font-bold hover:underline">
              {mode === "signin" ? t("sign_up") : t("sign_in")}
            </button>
          </div>

          <div className="text-center text-xs text-muted-foreground pt-4 border-t">
            Developed by <span className="text-primary font-semibold">Md Waliduzzaman Sarder</span> · 📞 01722427373
          </div>
        </div>
      </div>
    </div>
  );
}

function Field({ label, children }: any) {
  return <div className="space-y-1.5"><Label className="text-sm font-semibold">{label}</Label>{children}</div>;
}
