"use client";

import { useState, useEffect, Suspense } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { createClient } from "@/lib/supabase/client";
import { Field, Input } from "@/components/ui/Input";
import Button from "@/components/ui/Button";
import Chips from "@/components/ui/Chips";
import Spinner from "@/components/ui/Spinner";
import { ShieldCheck, AlertCircle, CheckCircle2, User } from "lucide-react";

type Skill = { id: string; name: string };

function RegisterForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const supabase = createClient();

  const initialRole = searchParams.get("role") === "admin" ? "admin" : "student";
  const [role, setRole] = useState<"student" | "admin">(initialRole);

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

  const [availableSkills, setAvailableSkills] = useState<Skill[]>([]);
  const [selectedSkills, setSelectedSkills] = useState<string[]>([]); // holds skill_id strings

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

  // Fetch available skills for student registration
  useEffect(() => {
    (async () => {
      const { data } = await supabase.from("skills").select("id, name").order("name");
      if (data) {
        setAvailableSkills(data as Skill[]);
      }
    })();
  }, [supabase]);

  function toggleSkill(id: string) {
    setSelectedSkills((s) =>
      s.includes(id) ? s.filter((x) => x !== id) : [...s, id]
    );
  }

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

    if (!phone.trim()) {
      setError("Phone number is mandatory.");
      return;
    }

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

    setLoading(true);

    // 1) Sign up in auth
    const { data: signUpData, error: signUpError } = await supabase.auth.signUp({
      email,
      password,
      options: {
        data: {
          full_name: fullName,
        },
        emailRedirectTo: `${window.location.origin}/login`,
      },
    });

    if (signUpError) {
      setError(signUpError.message);
      setLoading(false);
      return;
    }

    // 2) If email confirmation is required, Supabase will NOT return a
    // session here. That's expected — show a "check your email" state
    // instead of trying to force a sign-in (which Supabase will reject
    // pre-confirmation anyway).
    if (!signUpData.session) {
      setConfirmationSent(true);
      setLoading(false);
      return;
    }

    const { data: userRes } = await supabase.auth.getUser();
    const userId = userRes.user?.id;

    if (!userId) {
      setError("Failed to retrieve user ID.");
      setLoading(false);
      return;
    }

    // 3) Complete profiles update and role-based tasks
    if (role === "admin") {
      // Run the promote RPC for admin
      const { data: promoted, error: rpcError } = await supabase.rpc("register_admin", {
        p_code: code,
        p_full_name: fullName,
        p_staff_id: staffId,
        p_phone: phone,
      });

      if (rpcError) {
        setError(rpcError.message);
        setLoading(false);
        return;
      }

      if (promoted !== true) {
        await supabase.auth.signOut();
        setError("Invalid admin registration code. Ask your supervisor for the correct code.");
        setLoading(false);
        return;
      }
    } else {
      // For student: update profile details (matric no, total_merit defaults to 0, role is already volunteer)
      const { error: profileError } = await supabase
        .from("profiles")
        .update({
          full_name: fullName,
          matric_no: matricNo || null,
          phone: phone || null,
          role: "volunteer",
        })
        .eq("id", userId);

      if (profileError) {
        setError(profileError.message);
        setLoading(false);
        return;
      }

      // Save student volunteer skills
      if (selectedSkills.length > 0) {
        const rows = selectedSkills.map((skillId) => ({
          volunteer_id: userId,
          skill_id: skillId,
        }));
        const { error: skillsError } = await supabase
          .from("volunteer_skills")
          .insert(rows);

        if (skillsError) {
          console.error("Failed to save skills:", skillsError.message);
          // Non-blocking for registration success
        }
      }
    }

    // Success — redirect to home page
    router.push("/");
    router.refresh();
  }

  if (confirmationSent) {
    return (
      <main className="flex min-h-screen items-center justify-center bg-sand px-4 py-10 text-ink">
        <div className="w-full max-w-md rounded-card border border-sand-dark/60 bg-white p-8 text-center shadow-card">
          <div className="mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-emerald-light/40 text-emerald">
            <CheckCircle2 size={28} />
          </div>
          <h1 className="text-xl font-extrabold text-ink">Confirm your email</h1>
          <p className="mt-2 text-sm text-muted">
            We&apos;ve sent a confirmation link to <strong>{email}</strong>.
            Please check your inbox (and spam folder) and click the link to
            activate your account before signing in.
          </p>
          <Link
            href="/login"
            className="mt-5 inline-block font-semibold text-emerald hover:underline"
          >
            Back to sign in
          </Link>
        </div>
      </main>
    );
  }

  return (
    <main
      className={`flex min-h-screen items-center justify-center px-4 py-10 transition-all duration-500 ${
        role === "admin"
          ? "bg-gradient-to-br from-[#07382B] via-[#0B5945] to-[#1A1A1A] text-white"
          : "bg-sand text-ink"
      }`}
    >
      <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 transition-colors duration-300 ${
              role === "admin" ? "bg-[#1D9E75] text-white" : "bg-emerald text-white"
            }`}
          >
            {role === "admin" ? <ShieldCheck size={28} /> : <User size={28} />}
          </div>
          <h1 className="text-2xl font-extrabold tracking-tight">
            {role === "admin" ? "Create Admin Account" : "Join as Student Volunteer"}
          </h1>
          <p className="mt-1 text-sm opacity-80">
            Smart Web-Based Volunteer Management System
          </p>
        </div>

        {/* Role Select tab */}
        <div className="mb-5 flex rounded-card bg-black/5 p-1 backdrop-blur-sm">
          <button
            onClick={() => {
              setRole("student");
              setError("");
            }}
            className={`flex flex-1 items-center justify-center gap-1.5 rounded-card py-2 text-xs font-bold transition-all ${
              role === "student"
                ? "bg-white text-emerald shadow-sm"
                : "text-white/60 hover:text-white"
            }`}
          >
            <User size={14} /> Student Registration
          </button>
          <button
            onClick={() => {
              setRole("admin");
              setError("");
            }}
            className={`flex flex-1 items-center justify-center gap-1.5 rounded-card py-2 text-xs font-bold transition-all ${
              role === "admin"
                ? "bg-[#0F6E56] text-white shadow-sm"
                : "text-ink/60 hover:text-ink"
            }`}
          >
            <ShieldCheck size={14} /> Admin Registration
          </button>
        </div>

        <form
          onSubmit={handleRegister}
          className={`space-y-4 rounded-card border p-6 shadow-card transition-colors duration-300 ${
            role === "admin"
              ? "border-white/10 bg-white/10 backdrop-blur-md"
              : "border-sand-dark/60 bg-white"
          }`}
        >
          <Field label="Full name">
            <Input
              required
              value={fullName}
              onChange={(e) => setFullName(e.target.value)}
              placeholder="e.g. Ahmad bin Abdullah"
              className={role === "admin" ? "border-white/20 bg-white/5 text-white placeholder:text-white/30 focus:border-[#1D9E75] focus:ring-[#1D9E75]/20" : ""}
            />
          </Field>

          {role === "student" ? (
            <Field label="Matric No.">
              <Input
                required
                value={matricNo}
                onChange={(e) => setMatricNo(e.target.value)}
                placeholder="e.g. D20231106439"
              />
            </Field>
          ) : (
            <Field label="Staff ID">
              <Input
                required
                value={staffId}
                onChange={(e) => setStaffId(e.target.value)}
                placeholder="e.g. UPSI-PI-0123"
                className="border-white/20 bg-white/5 text-white placeholder:text-white/30 focus:border-[#1D9E75] focus:ring-[#1D9E75]/20"
              />
            </Field>
          )}

          <Field label="Email">
            <Input
              type="email"
              autoComplete="email"
              required
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder={role === "admin" ? "admin@upsi.edu.my" : "student@student.upsi.edu.my"}
              className={role === "admin" ? "border-white/20 bg-white/5 text-white placeholder:text-white/30 focus:border-[#1D9E75] focus:ring-[#1D9E75]/20" : ""}
            />
          </Field>

          <Field label="Phone" hint="Mandatory">
            <Input
              required
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              placeholder="012-3456789"
              className={role === "admin" ? "border-white/20 bg-white/5 text-white placeholder:text-white/30 focus:border-[#1D9E75] focus:ring-[#1D9E75]/20" : ""}
            />
          </Field>

          <Field label="Password">
            <Input
              type="password"
              autoComplete="new-password"
              required
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="At least 6 characters"
              className={role === "admin" ? "border-white/20 bg-white/5 text-white placeholder:text-white/30 focus:border-[#1D9E75] focus:ring-[#1D9E75]/20" : ""}
            />
          </Field>

          <Field label="Confirm password">
            <Input
              type="password"
              autoComplete="new-password"
              required
              value={confirm}
              onChange={(e) => setConfirm(e.target.value)}
              placeholder="Re-enter password"
              className={role === "admin" ? "border-white/20 bg-white/5 text-white placeholder:text-white/30 focus:border-[#1D9E75] focus:ring-[#1D9E75]/20" : ""}
            />
          </Field>

          {role === "student" ? (
            <Field label="My Skills" hint="Select skills you can contribute to volunteer activities">
              {availableSkills.length > 0 ? (
                <Chips
                  options={availableSkills}
                  selected={selectedSkills}
                  onToggle={toggleSkill}
                />
              ) : (
                <p className="text-xs text-muted">Loading available skills...</p>
              )}
            </Field>
          ) : (
            <Field label="Admin registration code" hint="Provided by supervisor / Pusat Islam.">
              <Input
                required
                value={code}
                onChange={(e) => setCode(e.target.value)}
                placeholder="Enter secret admin code"
                className="border-white/20 bg-white/5 text-white placeholder:text-white/30 focus:border-[#1D9E75] focus:ring-[#1D9E75]/20"
              />
            </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>
          )}

          {role === "admin" && (
            <div className="flex items-start gap-2 rounded-card bg-emerald-light px-3 py-2 text-xs text-[#0F6E56]">
              <CheckCircle2 size={14} className="mt-0.5 shrink-0" />
              <span>
                Only people with the correct code become admins. Without it, dashboard access is denied.
              </span>
            </div>
          )}

          <Button
            type="submit"
            disabled={loading}
            className={`w-full ${role === "admin" ? "bg-[#1D9E75] hover:bg-[#15805D] text-white" : ""}`}
          >
            {loading ? "Creating account…" : role === "admin" ? "Create Admin Account" : "Register as Volunteer"}
          </Button>
        </form>

        <p className="mt-4 text-center text-sm">
          Already have an account?{" "}
          <Link
            href="/login"
            className={`font-semibold hover:underline ${
              role === "admin" ? "text-[#1D9E75]" : "text-emerald"
            }`}
          >
            Sign in
          </Link>
        </p>
      </div>
    </main>
  );
}

export default function RegisterPage() {
  return (
    <Suspense fallback={<Spinner label="Loading registration form..." />}>
      <RegisterForm />
    </Suspense>
  );
}