"use client";

import { Suspense, useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
import { signIn } from "next-auth/react";
import Link from "next/link";
import { ScanLine, Mail, User, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { PasswordFields } from "@/components/auth/password-fields";

export default function SignupPage() {
  return (
    <Suspense>
      <SignupForm />
    </Suspense>
  );
}

function SignupForm() {
  const searchParams = useSearchParams();
  const token = searchParams.get("token") || "";
  const callbackUrl = searchParams.get("callbackUrl") || "/";

  const [formData, setFormData] = useState({
    displayName: "",
    email: "",
    password: "",
    confirmPassword: "",
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [inviteInfo, setInviteInfo] = useState<{
    orgName: string;
    email: string;
    role: string;
  } | null>(null);

  useEffect(() => {
    if (!token) return;
    fetch(`/api/invitations/verify?token=${token}`)
      .then((r) => r.json())
      .then((data) => {
        if (data.valid) {
          setInviteInfo({ orgName: data.orgName, email: data.email, role: data.role });
          setFormData((prev) => ({ ...prev, email: data.email }));
        }
      })
      .catch(() => {});
  }, [token]);

  function update(field: string, value: string) {
    setFormData((prev) => ({ ...prev, [field]: value }));
  }

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

    if (formData.password !== formData.confirmPassword) {
      setError("Passwords do not match");
      return;
    }

    if (formData.password.length < 8) {
      setError("Password must be at least 8 characters");
      return;
    }

    setLoading(true);

    try {
      const res = await fetch("/api/auth/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          displayName: formData.displayName,
          email: formData.email,
          password: formData.password,
          inviteToken: token,
        }),
      });

      if (!res.ok) {
        const data = await res.json();
        setError(data.error || "Registration failed");
        setLoading(false);
        return;
      }

      await signIn("credentials", {
        email: formData.email,
        password: formData.password,
        callbackUrl,
      });
    } catch {
      setError("Something went wrong. Please try again.");
      setLoading(false);
    }
  }

  return (
    <div className="glass-card mx-auto w-full max-w-md rounded-2xl p-8">
      <div className="mb-8 flex flex-col items-center">
        <div className="mb-4 flex size-14 items-center justify-center rounded-2xl gradient-banner shadow-lg">
          <ScanLine className="size-7 text-white" />
        </div>
        <h1 className="text-2xl font-bold tracking-tight">Create account</h1>
        <p className="mt-1 text-sm text-muted-foreground">
          {inviteInfo
            ? <>Join <strong>{inviteInfo.orgName}</strong></>
            : token
              ? "Complete your account setup"
              : "Get started with Echo"}
        </p>
      </div>

      {error && (
        <div className="mb-4 rounded-lg bg-destructive/10 p-3 text-center text-sm text-destructive">
          {error}
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-4">
        <div className="space-y-2">
          <Label htmlFor="displayName">Full Name</Label>
          <div className="relative">
            <User className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              id="displayName"
              type="text"
              placeholder="John Smith"
              value={formData.displayName}
              onChange={(e) => update("displayName", e.target.value)}
              required
              className="pl-10"
            />
          </div>
        </div>

        <div className="space-y-2">
          <Label htmlFor="email">Email</Label>
          <div className="relative">
            <Mail className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              id="email"
              type="email"
              placeholder="you@church.org"
              value={formData.email}
              onChange={(e) => update("email", e.target.value)}
              required
              autoComplete="email"
              readOnly={!!inviteInfo}
              className={`pl-10 ${inviteInfo ? "bg-muted/50 cursor-not-allowed" : ""}`}
            />
          </div>
        </div>

        <PasswordFields
          password={formData.password}
          confirmPassword={formData.confirmPassword}
          onPasswordChange={(v) => update("password", v)}
          onConfirmChange={(v) => update("confirmPassword", v)}
        />

        <Button type="submit" className="w-full rounded-xl" disabled={loading}>
          {loading ? <Loader2 className="mr-2 size-4 animate-spin" /> : null}
          Create Account
        </Button>
      </form>

      <p className="mt-6 text-center text-xs text-muted-foreground">
        Already have an account?{" "}
        <Link href="/login" className="font-medium text-primary hover:underline">
          Sign in
        </Link>
      </p>
      <p className="mt-3 text-center text-[10px] text-muted-foreground/60">
        By creating an account, you agree to our{" "}
        <Link href="/terms" className="underline hover:text-muted-foreground">Terms</Link>
        {" "}and{" "}
        <Link href="/privacy" className="underline hover:text-muted-foreground">Privacy Policy</Link>.
      </p>
    </div>
  );
}
