import { createFileRoute, useNavigate, Link, redirect } from "@tanstack/react-router";
import { useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useServerFn } from "@tanstack/react-start";
import { signUpUser, resolveLogin } from "@/lib/bkash.functions";
import { toast } from "sonner";
import { Smartphone, KeyRound, User, Loader2 } from "lucide-react";
import { useAppSettings } from "@/hooks/useAppSettings";

export const Route = createFileRoute("/auth")({
  ssr: false,
  head: () => ({
    meta: [{ title: "bKash — Login" }, { name: "description", content: "Sign in to your bKash account." }],
  }),
  validateSearch: (s: Record<string, unknown>) => ({
    next: typeof s.next === "string" && s.next.startsWith("/") && !s.next.startsWith("//") ? s.next : "",
  }),
  beforeLoad: async ({ search }) => {
    const { data } = await supabase.auth.getUser();
    if (data.user) {
      if (search.next) throw redirect({ href: search.next } as any);
      throw redirect({ to: "/" });
    }
  },
  component: AuthPage,
});

function AuthPage() {
  const [mode, setMode] = useState<"login" | "register">("login");
  const [phone, setPhone] = useState("");
  const [pin, setPin] = useState("");
  const [name, setName] = useState("");
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const { next } = Route.useSearch();
  const signUp = useServerFn(signUpUser);
  const resolve = useServerFn(resolveLogin);
  const { settings } = useAppSettings();

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    try {
      if (mode === "register") {
        await signUp({ data: { phone, fullName: name || `${settings.app_name} User`, pin } });
        toast.success("অ্যাকাউন্ট তৈরি হয়েছে! সাইন ইন করছি...");
      }
      const { email, password } = await resolve({ data: { phone, pin } });
      const { error } = await supabase.auth.signInWithPassword({ email, password });
      if (error) throw new Error(mode === "login" ? "ভুল ফোন নম্বর বা পিন" : error.message);
      toast.success("স্বাগতম!");
      if (next) window.location.href = next;
      else navigate({ to: "/" });
    } catch (err: any) {
      toast.error(err?.message ?? "কিছু ভুল হয়েছে");
    } finally {
      setLoading(false);
    }
  }

  const initials = settings.app_name.slice(0, 2);

  return (
    <div
      className="min-h-screen flex flex-col text-primary-foreground"
      style={{ background: "var(--gradient-balance)" }}
    >
      <div className="px-6 pt-12 pb-6 text-center">
        <div className="inline-flex items-center justify-center h-16 w-16 rounded-2xl bg-white/15 backdrop-blur mb-4 overflow-hidden">
          {settings.app_logo_url ? (
            <img src={settings.app_logo_url} alt={settings.app_name} className="h-full w-full object-cover" />
          ) : (
            <span className="text-3xl font-extrabold">{initials}</span>
          )}
        </div>
        <h1 className="text-2xl font-extrabold tracking-tight">{settings.app_name}</h1>
        <p className="text-sm opacity-80 mt-1">{settings.app_tagline || "মোবাইল ফাইন্যান্সিয়াল সার্ভিস"}</p>
      </div>


      <div className="flex-1 bg-background text-foreground rounded-t-3xl px-6 pt-7 pb-10">
        <div className="flex gap-2 p-1 bg-muted rounded-full mb-6">
          {(["login", "register"] as const).map((m) => (
            <button
              key={m}
              onClick={() => setMode(m)}
              className={`flex-1 py-2.5 text-sm font-semibold rounded-full transition ${
                mode === m ? "bg-card text-primary shadow-sm" : "text-muted-foreground"
              }`}
            >
              {m === "login" ? "লগ ইন" : "রেজিস্টার"}
            </button>
          ))}
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          {mode === "register" && (
            <Field icon={User} label="পূর্ণ নাম">
              <input
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="আপনার নাম"
                className="w-full bg-transparent outline-none text-base"
                required
              />
            </Field>
          )}
          <Field icon={Smartphone} label="ফোন নম্বর">
            <input
              value={phone}
              onChange={(e) => setPhone(e.target.value.replace(/\D/g, "").slice(0, 11))}
              placeholder="01XXXXXXXXX"
              inputMode="numeric"
              className="w-full bg-transparent outline-none text-base tracking-wider"
              required
            />
          </Field>
          <Field icon={KeyRound} label="৫ ডিজিটের পিন">
            <input
              value={pin}
              onChange={(e) => setPin(e.target.value.replace(/\D/g, "").slice(0, 5))}
              placeholder="• • • • •"
              inputMode="numeric"
              type="password"
              className="w-full bg-transparent outline-none text-base tracking-[0.4em]"
              required
            />
          </Field>

          <button
            disabled={loading || phone.length !== 11 || pin.length !== 5}
            className="w-full mt-2 h-12 rounded-full font-bold text-primary-foreground disabled:opacity-50 active:scale-[0.98] transition flex items-center justify-center gap-2"
            style={{ background: "var(--gradient-primary)" }}
          >
            {loading && <Loader2 className="h-4 w-4 animate-spin" />}
            {mode === "login" ? "লগ ইন করুন" : "অ্যাকাউন্ট তৈরি করুন"}
          </button>
        </form>

        <p className="text-center text-xs text-muted-foreground mt-6">
          {settings.welcome_bonus_text}
        </p>
        <p className="text-center text-xs mt-2">
          <Link to="/forgot-pin" className="text-primary font-semibold">পিন ভুলে গেছেন?</Link>
        </p>
        <p className="text-center text-xs text-muted-foreground mt-2">
          <Link to="/" className="text-primary font-semibold">হোম এ ফিরে যান</Link>
        </p>
      </div>
    </div>
  );
}

function Field({ icon: Icon, label, children }: { icon: any; label: string; children: React.ReactNode }) {
  return (
    <label className="block">
      <span className="text-xs font-semibold text-muted-foreground">{label}</span>
      <div className="mt-1 flex items-center gap-3 px-4 h-12 rounded-xl border border-input bg-card focus-within:border-primary focus-within:ring-2 focus-within:ring-primary/20 transition">
        <Icon className="h-4 w-4 text-muted-foreground shrink-0" />
        {children}
      </div>
    </label>
  );
}
