import { createFileRoute, useNavigate, Link } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { useAuth } from "@/contexts/AuthContext";
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 { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { FaceCapture } from "@/components/FaceCapture";
import { RANKS } from "@/lib/constants";
import { toast } from "sonner";
import logo from "@/assets/tirs-logo.png";
import type { FaceDescriptor } from "@/lib/face";

export const Route = createFileRoute("/register")({
  component: RegisterPage,
  head: () => ({ meta: [{ title: "Register — TIRS" }] }),
});

interface Province { id: string; name: string; code: string; }
interface Station { id: string; name: string; province_id: string; }

function RegisterPage() {
  const navigate = useNavigate();
  const { user } = useAuth();
  const [busy, setBusy] = useState(false);
  const [provinces, setProvinces] = useState<Province[]>([]);
  const [stations, setStations] = useState<Station[]>([]);

  const [form, setForm] = useState({
    fullName: "", idNumber: "", persalNumber: "", email: "", phone: "",
    password: "", confirmPassword: "", rank: "", provinceId: "", stationId: "",
  });
  const [face, setFace] = useState<FaceDescriptor | null>(null);

  useEffect(() => {
    supabase.from("provinces").select("*").order("name").then(({ data }) => setProvinces(data ?? []));
  }, []);

  useEffect(() => {
    if (!form.provinceId) { setStations([]); return; }
    supabase.from("police_stations").select("*").eq("province_id", form.provinceId).order("name")
      .then(({ data }) => setStations(data ?? []));
  }, [form.provinceId]);

  const update = (k: keyof typeof form) => (v: string) => setForm((f) => ({ ...f, [k]: v }));

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (form.password !== form.confirmPassword) return toast.error("Passwords do not match");
    if (form.password.length < 8) return toast.error("Password must be at least 8 characters");
    if (!form.stationId) return toast.error("Select your police station");
    if (!face) return toast.error("Please capture your face for biometric enrollment");
    if (!/^\d{13}$/.test(form.idNumber)) return toast.error("ID number must be 13 digits");

    setBusy(true);
    const redirectUrl = `${window.location.origin}/dashboard`;
    const { data, error } = await supabase.auth.signUp({
      email: form.email,
      password: form.password,
      options: {
        emailRedirectTo: redirectUrl,
        data: { full_name: form.fullName },
      },
    });

    if (error || !data.user) {
      setBusy(false);
      return toast.error(error?.message ?? "Registration failed");
    }

    const { error: profileError } = await supabase.from("profiles").insert([{
      id: data.user.id,
      full_name: form.fullName,
      id_number: form.idNumber,
      persal_number: form.persalNumber,
      rank: form.rank,
      email: form.email,
      phone: form.phone || null,
      station_id: form.stationId,
      status: "pending" as const,
      face_descriptor: face as never,
    }]);

    // Default role: officer
    await supabase.from("user_roles").insert({ user_id: data.user.id, role: "officer" });

    setBusy(false);
    if (profileError) return toast.error(profileError.message);

    toast.success("Registration submitted. Awaiting admin approval.");
    navigate({ to: "/login" });
  };

  if (user) return <div className="min-h-screen flex items-center justify-center">Already signed in.</div>;

  return (
    <div className="min-h-screen bg-gradient-hero py-8 px-4">
      <div className="max-w-2xl mx-auto">
        <div className="flex flex-col items-center mb-6">
          <img src={logo} alt="TIRS" width={1024} height={1024} loading="lazy" className="h-20 w-20 object-contain" />
          <h1 className="text-xl font-bold text-primary-foreground mt-2">Officer Registration</h1>
        </div>

        <Card className="shadow-elevated">
          <CardHeader>
            <CardTitle>SAPS Member Enrollment</CardTitle>
            <CardDescription>
              All fields are required. Your account will be reviewed by an administrator before activation.
              Personal data is processed in accordance with POPIA.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={onSubmit} className="space-y-4">
              <div className="grid sm:grid-cols-2 gap-3">
                <div className="sm:col-span-2">
                  <Label>Full Name</Label>
                  <Input required value={form.fullName} onChange={(e) => update("fullName")(e.target.value)} />
                </div>
                <div>
                  <Label>South African ID Number</Label>
                  <Input required maxLength={13} value={form.idNumber} onChange={(e) => update("idNumber")(e.target.value.replace(/\D/g, ""))} />
                </div>
                <div>
                  <Label>PERSAL Number</Label>
                  <Input required value={form.persalNumber} onChange={(e) => update("persalNumber")(e.target.value)} />
                </div>
                <div>
                  <Label>Rank</Label>
                  <Select value={form.rank} onValueChange={update("rank")}>
                    <SelectTrigger><SelectValue placeholder="Select rank" /></SelectTrigger>
                    <SelectContent>{RANKS.map((r) => <SelectItem key={r} value={r}>{r}</SelectItem>)}</SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>Phone</Label>
                  <Input type="tel" value={form.phone} onChange={(e) => update("phone")(e.target.value)} />
                </div>
                <div>
                  <Label>Province</Label>
                  <Select value={form.provinceId} onValueChange={(v) => { update("provinceId")(v); update("stationId")(""); }}>
                    <SelectTrigger><SelectValue placeholder="Select province" /></SelectTrigger>
                    <SelectContent>{provinces.map((p) => <SelectItem key={p.id} value={p.id}>{p.name}</SelectItem>)}</SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>Police Station</Label>
                  <Select value={form.stationId} onValueChange={update("stationId")} disabled={!form.provinceId}>
                    <SelectTrigger><SelectValue placeholder={form.provinceId ? "Select station" : "Select province first"} /></SelectTrigger>
                    <SelectContent>{stations.map((s) => <SelectItem key={s.id} value={s.id}>{s.name}</SelectItem>)}</SelectContent>
                  </Select>
                </div>
                <div className="sm:col-span-2">
                  <Label>SAPS Email</Label>
                  <Input type="email" required value={form.email} onChange={(e) => update("email")(e.target.value)} />
                </div>
                <div>
                  <Label>Password (min 8 chars)</Label>
                  <Input type="password" required value={form.password} onChange={(e) => update("password")(e.target.value)} />
                </div>
                <div>
                  <Label>Confirm Password</Label>
                  <Input type="password" required value={form.confirmPassword} onChange={(e) => update("confirmPassword")(e.target.value)} />
                </div>
              </div>

              <div className="border-t pt-4">
                <Label className="mb-2 block">Facial Biometric Enrollment</Label>
                <p className="text-xs text-muted-foreground mb-3">
                  Capture a clear front-facing photo. This will be used for biometric login.
                </p>
                <FaceCapture onCapture={setFace} buttonLabel="Enroll Face" />
              </div>

              <Button type="submit" className="w-full" disabled={busy}>
                {busy ? "Submitting…" : "Submit Registration"}
              </Button>
              <p className="text-center text-sm">
                Already registered? <Link to="/login" className="text-primary hover:underline">Sign in</Link>
              </p>
            </form>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
