import { createFileRoute, useNavigate, Link } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { supabase } from "@/integrations/supabase/client";
import { AuthLayout, Field, submitClass } from "@/components/auth/AuthLayout";
import { resolveAccountType } from "@/lib/portal";

export const Route = createFileRoute("/auth/customer")({
  validateSearch: (s: Record<string, unknown>) => ({
    next: typeof s.next === "string" && s.next.startsWith("/") && !s.next.startsWith("//") ? s.next : undefined,
  }),
  head: () => ({
    meta: [
      { title: "Customer login | Emma Mold Inspection Services" },
      { name: "description", content: "Sign in or register as a customer to book inspections and view mold reports." },
      { property: "og:title", content: "Customer login | Emma Mold" },
      { property: "og:description", content: "Access your bookings, quotes, AI scans and inspection reports." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
  }),
  component: CustomerAuth,
});

type Mode = "signin" | "signup" | "forgot";

function CustomerAuth() {
  const navigate = useNavigate();
  const { next } = Route.useSearch();
  const [mode, setMode] = useState<Mode>("signin");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [fullName, setFullName] = useState("");
  const [phone, setPhone] = useState("");
  const [busy, setBusy] = useState(false);

  function goHome() {
    if (next) {
      window.location.href = next;
      return;
    }
    navigate({ to: "/dashboard" });
  }

  useEffect(() => {
    supabase.auth.getSession().then(({ data }) => {
      if (!data.session) return;
      resolveAccountType(data.session.user.id).then((a) => {
        if (a.isAdmin || a.isProvider) return;
        if (next) window.location.href = next;
        else navigate({ to: "/dashboard" });
      });
    });
  }, [navigate, next]);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setBusy(true);
    try {
      if (mode === "forgot") {
        const { error } = await supabase.auth.resetPasswordForEmail(email, {
          redirectTo: `${window.location.origin}/reset-password`,
        });
        if (error) throw error;
        toast.success("Password reset link sent. Check your inbox.");
        setMode("signin");
        return;
      }
      if (mode === "signup") {
        const { error } = await supabase.auth.signUp({
          email,
          password,
          options: {
            emailRedirectTo: next ? `${window.location.origin}${next}` : window.location.origin,
            data: { full_name: fullName, phone },
          },
        });
        if (error) throw error;
        toast.success("Account created. Check your email to confirm, then sign in.");
        setMode("signin");
        return;
      }
      const { data, error } = await supabase.auth.signInWithPassword({ email, password });
      if (error) throw error;
      const account = await resolveAccountType(data.user!.id);
      if (account.isAdmin) {
        await supabase.auth.signOut();
        toast.error("This is an admin account. Please use the Admin login.");
        return;
      }
      if (account.isProvider) {
        await supabase.auth.signOut();
        toast.error("This is a service provider account. Please use the Service Provider login.");
        return;
      }
      goHome();
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Something went wrong.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <AuthLayout
      title={mode === "signup" ? "Create your customer account" : mode === "forgot" ? "Reset password" : "Customer login"}
      subtitle="Emma Mold Inspection Services"
      footer={
        mode === "signin" ? (
          <>
            <button className="font-semibold text-primary" onClick={() => setMode("forgot")}>
              Forgot password?
            </button>
            <p>
              New here?{" "}
              <button className="font-semibold text-primary" onClick={() => setMode("signup")}>
                Create an account
              </button>
            </p>
          </>
        ) : (
          <button className="font-semibold text-primary" onClick={() => setMode("signin")}>
            Back to sign in
          </button>
        )
      }
    >
      <form className="mt-6 space-y-3" onSubmit={submit}>
        {mode === "signup" ? (
          <>
            <Field label="Full name" value={fullName} onChange={setFullName} required />
            <Field label="Phone number" value={phone} onChange={setPhone} type="tel" required />
          </>
        ) : null}
        <Field label="Email" value={email} onChange={setEmail} type="email" required />
        {mode !== "forgot" ? <Field label="Password" value={password} onChange={setPassword} type="password" required /> : null}
        <button type="submit" disabled={busy} className={submitClass}>
          {busy ? "Please wait…" : mode === "signup" ? "Create account" : mode === "forgot" ? "Send reset link" : "Sign in"}
        </button>
      </form>
      <p className="mt-3 text-center text-[11px] text-muted-foreground">
        Running a mold company?{" "}
        <Link to="/auth/provider" className="font-semibold text-primary">
          Apply as a service provider
        </Link>
      </p>
    </AuthLayout>
  );
}
