"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Eye, EyeOff, AlertCircle } from "lucide-react"

export default function ClientLoginPage() {
  const router = useRouter()
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const [showPassword, setShowPassword] = useState(false)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")
  const [checking, setChecking] = useState(true)
  const [debugInfo, setDebugInfo] = useState("")

  useEffect(() => {
    fetch("/api/auth/me", { credentials: "include" })
      .then((r) => r.json())
      .then((data) => {
        if (data.user?.role === "client") router.push("/client-portal/dashboard")
        else setChecking(false)
      })
      .catch(() => setChecking(false))
  }, [router])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setError("")
    setDebugInfo("")

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

      const data = await res.json()
      console.log("LOGIN RESPONSE:", res.status, data)

      if (!res.ok) {
        setError(data.error || "Login failed")
        setDebugInfo(`HTTP ${res.status}`)
        return
      }

      if (data.user?.role !== "client") {
        setError("This portal is for clients only")
        setDebugInfo(`User role: ${data.user?.role}`)
        return
      }

      setError("Login successful! Redirecting...")
      setDebugInfo("")
      setTimeout(() => { window.location.href = "/client-portal/dashboard" }, 300)
    } catch (err) {
      console.error("LOGIN FETCH ERROR:", err)
      setError("Connection error")
      setDebugInfo("Check network tab for details")
    } finally {
      setLoading(false)
    }
  }

  if (checking) {
    return (
      <div className="flex min-h-screen bg-[#0a0a0f] items-center justify-center">
        <div className="w-8 h-8 border-2 border-[#1BB0CE] border-t-transparent rounded-full animate-spin" />
      </div>
    )
  }

  return (
    <div className="flex min-h-screen bg-[#0a0a0f] items-center justify-center p-4">
      <div className="w-full max-w-sm">
        <div className="text-center mb-8">
          <div className="text-2xl font-bold mb-1">
            <span className="text-[#1BB0CE]">Client</span>
            <span className="text-white"> Portal</span>
          </div>
          <p className="text-sm text-[#6a6a75]">Sign in to view your projects and invoices</p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm text-[#8a8a95] mb-1.5">Email</label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="w-full bg-[#1a1a24] border border-[#2a2a35] rounded-lg px-3 py-2.5 text-sm text-white placeholder-[#6a6a75] outline-none focus:border-[#1BB0CE]/50"
              placeholder="your@email.com"
              required
            />
          </div>

          <div>
            <label className="block text-sm text-[#8a8a95] mb-1.5">Password</label>
            <div className="relative">
              <input
                type={showPassword ? "text" : "password"}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="w-full bg-[#1a1a24] border border-[#2a2a35] rounded-lg px-3 py-2.5 pr-10 text-sm text-white placeholder-[#6a6a75] outline-none focus:border-[#1BB0CE]/50"
                placeholder="Enter password"
                required
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-[#6a6a75] hover:text-white"
              >
                {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
          </div>

          {error && (
            <div className={"text-sm bg-opacity-10 border rounded-lg px-3 py-2 " + (error === "Login successful! Redirecting..."
              ? "text-[#1BB0CE] bg-[#1BB0CE]/5 border-[#1BB0CE]/20"
              : "text-red-400 bg-red-400/5 border-red-400/10")}>
              <div className="flex items-center gap-2">
                {error !== "Login successful! Redirecting..." && <AlertCircle className="h-4 w-4 shrink-0" />}
                <span className="font-medium">{error}</span>
              </div>
              {debugInfo && <div className="mt-1 text-xs opacity-60">{debugInfo}</div>}
            </div>
          )}

          <button
            type="submit"
            disabled={loading}
            className="w-full bg-[#1BB0CE] hover:bg-[#1BB0CE]/80 text-white rounded-lg px-4 py-2.5 text-sm font-medium transition-all disabled:opacity-40"
          >
            {loading ? "Signing in..." : "Sign In"}
          </button>
        </form>
      </div>
    </div>
  )
}
