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

export const Route = createFileRoute("/auth/provider")({
  head: () => ({
    meta: [
      { title: "Service provider login | Emma Mold Inspection Services" },
      {
        name: "description",
        content: "Approved mold service companies sign in here to manage jobs, staff, quotations and reports.",
      },
      { property: "og:title", content: "Service provider login | Emma Mold" },
      { property: "og:description", content: "Company portal access for approved Emma marketplace providers." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
  }),
  component: ProviderAuth,
});

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

function ProviderAuth() {
  const navigate = useNavigate();
  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);
  const [pending, setPending] = useState<string | null>(null);

  useEffect(() => {
    supabase.auth.getSession().then(({ data }) => {
      if (!data.session) return;
      resolveAccountType(data.session.user.id).then((a) => {
        if (!a.isAdmin && a.companyStatus !== "suspended") navigate({ to: "/provider" });
      });
    });
  }, [navigate]);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setBusy(true);
    setPending(null);
    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 === "apply") {
        const { error } = await supabase.auth.signUp({
          email,
          password,
          options: {
            emailRedirectTo: `${window.location.origin}/auth/provider`,
            data: { full_name: fullName, phone, account_type: "service_provider" },
          },
        });
        if (error) throw error;
        toast.success("Account created. Confirm your email, sign in, then submit your company application.");
        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 && account.companyStatus !== "approved") {
        if (account.companyStatus === "pending") {
          navigate({ to: "/provider" });
          return;
        }
        await supabase.auth.signOut();
        setPending("Your application was rejected or suspended by Emma Exclusive Teams. Contact support for details.");
        return;
      }
      navigate({ to: "/provider" });
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Something went wrong.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <AuthLayout
      title={mode === "apply" ? "Apply as a service provider" : mode === "forgot" ? "Reset password" : "Service provider login"}
      subtitle="Emma Marketplace • approved companies only"
      footer={
        mode === "signin" ? (
          <>
            <button className="font-semibold text-primary" onClick={() => setMode("forgot")}>
              Forgot password?
            </button>
            <p>
              New company?{" "}
              <button className="font-semibold text-primary" onClick={() => setMode("apply")}>
                Apply for registration
              </button>
            </p>
          </>
        ) : (
          <button className="font-semibold text-primary" onClick={() => setMode("signin")}>
            Back to sign in
          </button>
        )
      }
    >
      <div className="mt-4 flex items-start gap-2 rounded-2xl bg-muted p-3 text-[11px] text-muted-foreground">
        <Building2 className="mt-0.5 h-4 w-4 shrink-0 text-primary" aria-hidden />
        <p>
          Company registrations are reviewed by Emma Exclusive Teams. Until approval your status shows{" "}
          <strong>Pending Admin Approval</strong> and jobs are not assigned to you.
        </p>
      </div>

      {pending ? (
        <p className="mt-3 rounded-2xl border border-destructive/40 bg-destructive/10 p-3 text-xs text-destructive">{pending}</p>
      ) : null}

      <form className="mt-4 space-y-3" onSubmit={submit}>
        {mode === "apply" ? (
          <>
            <Field label="Contact person" value={fullName} onChange={setFullName} required />
            <Field label="Phone number" value={phone} onChange={setPhone} type="tel" required />
          </>
        ) : null}
        <Field label="Work 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 === "apply" ? "Create provider account" : mode === "forgot" ? "Send reset link" : "Sign in"}
        </button>
      </form>
    </AuthLayout>
  );
}
