import { createFileRoute, useNavigate, useSearch, redirect } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { z } from "zod";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";
import { Link } from "@tanstack/react-router";
import { trackEvent } from "@/lib/pixels";

const searchSchema = z.object({
  redirect: z.string().optional(),
  mode: z.enum(["login", "register"]).optional(),
});

export const Route = createFileRoute("/auth")({
  validateSearch: (s) => searchSchema.parse(s),
  beforeLoad: async ({ search }) => {
    const { data } = await supabase.auth.getUser();
    if (data.user) throw redirect({ to: (search.redirect as any) || "/dashboard" });
  },
  component: AuthPage,
});

function AuthPage() {
  const navigate = useNavigate();
  const search = useSearch({ from: "/auth" });
  const [mode, setMode] = useState<"login" | "register" | "forgot">(search.mode ?? "login");
  const [loading, setLoading] = useState(false);

  // form fields
  const [fullName, setFullName] = useState("");
  const [phone, setPhone] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  // Listen for auth state to redirect after login
  useEffect(() => {
    const { data: sub } = supabase.auth.onAuthStateChange((event, session) => {
      if (event === "SIGNED_IN" && session) {
        navigate({ to: (search.redirect as any) || "/dashboard", replace: true });
      }
    });
    return () => sub.subscription.unsubscribe();
  }, [navigate, search.redirect]);

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      if (mode === "login") {
        const { error } = await supabase.auth.signInWithPassword({ email, password });
        if (error) throw error;
        trackEvent("Login");
        toast.success("Welcome back!");
      } else if (mode === "register") {
        const { error } = await supabase.auth.signUp({
          email, password,
          options: {
            emailRedirectTo: `${window.location.origin}/dashboard`,
            data: { full_name: fullName, phone },
          },
        });
        if (error) throw error;
        trackEvent("CompleteRegistration");
        toast.success("Account created! Check your email to confirm, then sign in.");
        setMode("login");
      } else {
        const { error } = await supabase.auth.resetPasswordForEmail(email, {
          redirectTo: `${window.location.origin}/reset-password`,
        });
        if (error) throw error;
        toast.success("Password reset email sent.");
        setMode("login");
      }
    } catch (err: any) {
      toast.error(err.message ?? "Authentication failed");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-hero-radial">
      <div className="mx-auto flex min-h-screen max-w-md flex-col justify-center px-4 py-12">
        <Link to="/" className="mb-8 inline-flex items-center gap-2">
          <div className="grid h-9 w-9 place-items-center rounded-lg bg-gradient-primary"><span className="font-display font-bold text-primary-foreground">B</span></div>
          <span className="font-display font-semibold">BO Mastery</span>
        </Link>

        <div className="rounded-2xl border border-border bg-card p-7 shadow-card">
          <h1 className="font-display text-2xl font-bold">
            {mode === "login" && "Welcome back"}
            {mode === "register" && "Create your account"}
            {mode === "forgot" && "Reset password"}
          </h1>
          <p className="mt-1 text-sm text-muted-foreground">
            {mode === "login" && "Sign in to access your courses."}
            {mode === "register" && "Get started in less than a minute."}
            {mode === "forgot" && "We'll email you a reset link."}
          </p>

          <form onSubmit={submit} className="mt-6 space-y-4">
            {mode === "register" && (
              <>
                <Field label="Full name" value={fullName} onChange={setFullName} required />
                <Field label="Phone (bKash number)" value={phone} onChange={setPhone} required />
              </>
            )}
            <Field label="Email" type="email" value={email} onChange={setEmail} required />
            {mode !== "forgot" && <Field label="Password" type="password" value={password} onChange={setPassword} required minLength={6} />}
            <button disabled={loading} className="w-full rounded-lg bg-gradient-primary px-4 py-3 text-sm font-semibold text-primary-foreground shadow-glow disabled:opacity-60">
              {loading ? "Please wait…" : mode === "login" ? "Sign in" : mode === "register" ? "Create account" : "Send reset email"}
            </button>
          </form>

          <div className="mt-6 space-y-2 text-center text-xs text-muted-foreground">
            {mode === "login" && (
              <>
                <p>Don't have an account? <button onClick={() => setMode("register")} className="font-semibold text-primary hover:underline">Sign up</button></p>
                <p><button onClick={() => setMode("forgot")} className="hover:underline">Forgot password?</button></p>
              </>
            )}
            {mode === "register" && <p>Already have an account? <button onClick={() => setMode("login")} className="font-semibold text-primary hover:underline">Sign in</button></p>}
            {mode === "forgot" && <p><button onClick={() => setMode("login")} className="hover:underline">Back to sign in</button></p>}
          </div>
        </div>
      </div>
    </div>
  );
}

function Field({ label, type = "text", value, onChange, required, minLength }: { label: string; type?: string; value: string; onChange: (v: string) => void; required?: boolean; minLength?: number }) {
  return (
    <label className="block">
      <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">{label}</span>
      <input
        type={type} value={value} onChange={(e) => onChange(e.target.value)} required={required} minLength={minLength}
        className="mt-1.5 block w-full rounded-lg border border-border bg-input px-3 py-2.5 text-sm outline-none ring-primary/40 focus:ring-2"
      />
    </label>
  );
}
