"use client"

import { useState } from "react"
import { signIn } from "next-auth/react"
import { useRouter } from "next/navigation"
import Link from "next/link"

export default function SignupPage() {
  const [step, setStep] = useState<"form" | "loading">("form")
  const [charityName, setCharityName] = useState("")
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const [error, setError] = useState("")
  const router = useRouter()

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!charityName.trim() || !email.trim() || !password) return
    setError("")
    setStep("loading")

    try {
      const res = await fetch("/api/auth/signup", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password, charityName, name: "" }),
      })
      const data = await res.json()

      if (!res.ok) {
        setError(data.error || "Something went wrong")
        setStep("form")
        return
      }

      // Auto sign in and go straight to dashboard
      const result = await signIn("credentials", { email, password, redirect: false })
      if (result?.error) {
        setError("Account created — please sign in")
        setStep("form")
      } else {
        router.push("/dashboard")
      }
    } catch {
      setError("Connection error. Try again.")
      setStep("form")
    }
  }

  if (step === "loading") {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-trust-blue/5 via-white to-warm-amber/5">
        <div className="text-center space-y-4">
          <div className="inline-flex h-14 w-14 rounded-2xl bg-gradient-to-br from-trust-blue to-blue-600 items-center justify-center shadow-lg shadow-trust-blue/20 animate-pulse">
            <span className="text-white text-2xl">🤲</span>
          </div>
          <p className="text-sm font-medium text-trust-blue animate-pulse">Setting up your charity...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-trust-blue/5 via-white to-warm-amber/5 p-4">
      <div className="w-full max-w-sm space-y-5">
        <div className="text-center">
          <div className="inline-flex h-12 w-12 rounded-2xl bg-gradient-to-br from-trust-blue to-blue-600 items-center justify-center shadow-lg shadow-trust-blue/20 mb-3">
            <span className="text-white text-xl">🤲</span>
          </div>
          <h1 className="text-2xl font-black text-gray-900">Start collecting pledges</h1>
          <p className="text-sm text-muted-foreground mt-1">Free. 30 seconds. No card.</p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-3">
          {error && (
            <div className="rounded-xl bg-danger-red/10 border border-danger-red/20 p-2.5 text-sm text-danger-red text-center">{error}</div>
          )}

          <input
            type="text"
            value={charityName}
            onChange={(e) => setCharityName(e.target.value)}
            className="w-full rounded-xl border border-gray-200 px-4 py-3 text-sm focus:border-trust-blue focus:ring-2 focus:ring-trust-blue/20 outline-none transition-all"
            placeholder="Your charity or mosque name"
            required
            autoFocus
          />

          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className="w-full rounded-xl border border-gray-200 px-4 py-3 text-sm focus:border-trust-blue focus:ring-2 focus:ring-trust-blue/20 outline-none transition-all"
            placeholder="Your email"
            required
          />

          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            className="w-full rounded-xl border border-gray-200 px-4 py-3 text-sm focus:border-trust-blue focus:ring-2 focus:ring-trust-blue/20 outline-none transition-all"
            placeholder="Pick a password (8+ chars)"
            required
            minLength={8}
          />

          <button
            type="submit"
            className="w-full rounded-xl bg-trust-blue px-4 py-3.5 text-sm font-bold text-white hover:bg-trust-blue/90 transition-all shadow-lg shadow-trust-blue/20"
          >
            Create Account →
          </button>
        </form>

        <p className="text-center text-xs text-muted-foreground">
          Already have an account? <Link href="/login" className="text-trust-blue font-semibold hover:underline">Sign in</Link>
        </p>
      </div>
    </div>
  )
}
