"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 signUpWithGoogle = () => {
    setStep("loading")
    signIn("auth0", { callbackUrl: "/dashboard" })
  }

  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
      }

      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-paper">
        <div className="text-center space-y-4">
          <div className="h-10 w-10 bg-midnight flex items-center justify-center mx-auto">
            <span className="text-white text-sm font-black">P</span>
          </div>
          <p className="text-sm font-medium text-gray-500">Setting up your charity...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-paper p-4">
      <div className="w-full max-w-sm space-y-6">
        <div className="text-center space-y-3">
          <div className="h-10 w-10 bg-midnight flex items-center justify-center mx-auto">
            <span className="text-white text-sm font-black">P</span>
          </div>
          <div>
            <h1 className="text-2xl font-black text-midnight">Start collecting pledges</h1>
            <p className="text-sm text-gray-500 mt-1">Free. 30 seconds. No card.</p>
          </div>
        </div>

        <button
          onClick={signUpWithGoogle}
          className="w-full flex items-center justify-center gap-2 border border-gray-200 bg-white px-4 py-3 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
        >
          <svg className="h-4 w-4" viewBox="0 0 24 24"><path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 01-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z" fill="#4285F4"/><path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/><path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/><path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/></svg>
          Sign up with Google
        </button>

        <div className="relative">
          <div className="absolute inset-0 flex items-center"><div className="w-full border-t border-gray-200" /></div>
          <div className="relative flex justify-center text-xs"><span className="bg-paper px-3 text-gray-400">or use email</span></div>
        </div>

        <form onSubmit={handleSubmit} className="space-y-3">
          {error && (
            <div className="border border-alert-red/20 bg-alert-red/5 p-2.5 text-sm text-alert-red text-center">{error}</div>
          )}
          <input
            type="text"
            value={charityName}
            onChange={(e) => setCharityName(e.target.value)}
            className="w-full border border-gray-200 px-4 py-3 text-sm focus:border-promise-blue focus:ring-1 focus:ring-promise-blue/20 outline-none transition-colors"
            placeholder="Your charity or mosque name"
            required
            autoFocus
          />
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className="w-full border border-gray-200 px-4 py-3 text-sm focus:border-promise-blue focus:ring-1 focus:ring-promise-blue/20 outline-none transition-colors"
            placeholder="Your email"
            required
          />
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            className="w-full border border-gray-200 px-4 py-3 text-sm focus:border-promise-blue focus:ring-1 focus:ring-promise-blue/20 outline-none transition-colors"
            placeholder="Pick a password (8+ chars)"
            required
            minLength={8}
          />
          <button
            type="submit"
            className="w-full bg-midnight px-4 py-3.5 text-sm font-bold text-white hover:bg-gray-800 transition-colors"
          >
            Create Account →
          </button>
        </form>

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