"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { createClient } from "@/lib/supabase/client";
import { Field, Input } from "@/components/ui/Input";
import Button from "@/components/ui/Button";
import { HeartHandshake, AlertCircle } from "lucide-react";

export default function SignupPage() {
  const router = useRouter();
  const supabase = createClient();

  const [fullName, setFullName] = useState("");
  const [matricNo, setMatricNo] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [password, setPassword] = useState("");
  const [confirm, setConfirm] = useState("");

  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  async function handleSignup(e: React.FormEvent) {
    e.preventDefault();
    setError("");

    if (password.length < 6) return setError("Password must be at least 6 characters.");
    if (password !== confirm) return setError("Passwords do not match.");

    setLoading(true);

    // Creates the auth user; the database trigger creates a volunteer profile.
    const { data: signUpData, error: signUpError } = await supabase.auth.signUp({
      email,
      password,
      options: { data: { full_name: fullName } },
    });
    if (signUpError) {
      setError(signUpError.message);
      setLoading(false);
      return;
    }

    if (!signUpData.session) {
      const { error: signInError } = await supabase.auth.signInWithPassword({ email, password });
      if (signInError) {
        setError(
          "Account created, but email confirmation is on. Disable it in Supabase (Authentication → Providers → Email), or confirm your email then sign in."
        );
        setLoading(false);
        return;
      }
    }

    // Fill the extra profile details the trigger doesn't set.
    const { data: userRes } = await supabase.auth.getUser();
    if (userRes.user) {
      await supabase
        .from("profiles")
        .update({
          full_name: fullName.trim(),
          matric_no: matricNo.trim() || null,
          phone: phone.trim() || null,
        })
        .eq("id", userRes.user.id);
    }

    router.push("/portal");
    router.refresh();
  }

  return (
    <main className="flex min-h-screen items-center justify-center bg-sand px-4 py-10">
      <div className="w-full max-w-md">
        <div className="mb-6 flex flex-col items-center text-center">
          <div className="mb-3 flex h-14 w-14 items-center justify-center rounded-card bg-emerald text-white">
            <HeartHandshake size={26} />
          </div>
          <h1 className="text-2xl font-extrabold text-ink">Join as a volunteer</h1>
          <p className="mt-1 text-sm text-muted">
            Pusat Islam · Smart Volunteer Management System
          </p>
        </div>

        <form
          onSubmit={handleSignup}
          className="space-y-4 rounded-card border border-sand-dark/60 bg-white p-6 shadow-card"
        >
          <Field label="Full name">
            <Input
              required
              value={fullName}
              onChange={(e) => setFullName(e.target.value)}
              placeholder="Nurul Huda binti Ali"
            />
          </Field>
          <Field label="Matric no." hint="Optional">
            <Input
              value={matricNo}
              onChange={(e) => setMatricNo(e.target.value)}
              placeholder="D20231100000"
            />
          </Field>
          <Field label="Email">
            <Input
              type="email"
              autoComplete="email"
              required
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="you@student.upsi.edu.my"
            />
          </Field>
          <Field label="Phone" hint="Used for WhatsApp reminders.">
            <Input
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              placeholder="012-3456789"
            />
          </Field>
          <Field label="Password">
            <Input
              type="password"
              autoComplete="new-password"
              required
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="At least 6 characters"
            />
          </Field>
          <Field label="Confirm password">
            <Input
              type="password"
              autoComplete="new-password"
              required
              value={confirm}
              onChange={(e) => setConfirm(e.target.value)}
              placeholder="Re-enter password"
            />
          </Field>

          {error && (
            <div className="flex items-start gap-2 rounded-card bg-red-50 px-3 py-2.5 text-sm text-error">
              <AlertCircle size={16} className="mt-0.5 shrink-0" />
              <span>{error}</span>
            </div>
          )}

          <Button type="submit" disabled={loading} className="w-full">
            {loading ? "Creating account…" : "Create account"}
          </Button>
        </form>

        <p className="mt-4 text-center text-sm text-muted">
          Already have an account?{" "}
          <Link href="/login" className="font-semibold text-emerald hover:underline">
            Sign in
          </Link>
        </p>
      </div>
    </main>
  );
}
