"use client"

import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"

export default function LoginPage() {
  const router = useRouter()
  const [mode, setMode] = useState<"login" | "register">("login")
  const [name, setName] = useState("")
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const [rememberMe, setRememberMe] = useState(true)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [resetSent, setResetSent] = useState(false)
  const [showForgot, setShowForgot] = useState(false)

  useEffect(() => {
    let isMounted = true
    const check = async () => {
      try {
        const res = await fetch("/api/auth/session", { cache: "no-store" })
        if (res.ok && isMounted) {
          router.replace("/")
        }
      } catch {
        // ignore and stay on login
      }
    }
    check()
    return () => {
      isMounted = false
    }
  }, [router])

  const submit = async () => {
    setError(null)

    if (!email.trim() || !password) {
      setError("Email and password are required")
      return
    }

    if (mode === "register" && !name.trim()) {
      setError("Name is required")
      return
    }

    setIsSubmitting(true)
    try {
      const endpoint = mode === "login" ? "/api/auth/login" : "/api/auth/register"
      const res = await fetch(endpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, email, password, rememberMe }),
      })

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

      router.replace("/")
    } catch {
      setError("Authentication failed")
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100 flex items-center justify-center p-4">
      <div className="w-full max-w-md border border-slate-800 rounded-xl bg-slate-900/70 p-6">
        <h1 className="text-2xl font-semibold text-white mb-2">OpenClaw Task Hub</h1>
        <p className="text-sm text-slate-400 mb-6">Sign in to continue.</p>

        <div className="flex gap-2 mb-6 bg-slate-800 p-1 rounded-lg">
          <button
            type="button"
            onClick={() => setMode("login")}
            className={`flex-1 px-3 py-2 rounded text-sm ${mode === "login" ? "bg-slate-700 text-white" : "text-slate-400"}`}
          >
            Login
          </button>
          <button
            type="button"
            onClick={() => setMode("register")}
            className={`flex-1 px-3 py-2 rounded text-sm ${mode === "register" ? "bg-slate-700 text-white" : "text-slate-400"}`}
          >
            Register
          </button>
        </div>

        <div className="space-y-4">
          {mode === "register" && (
            <div>
              <label className="block text-sm text-slate-300 mb-1">Name</label>
              <input
                type="text"
                value={name}
                onChange={(event) => setName(event.target.value)}
                className="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-white"
                placeholder="Your display name"
              />
            </div>
          )}

          <div>
            <label className="block text-sm text-slate-300 mb-1">Email</label>
            <input
              type="email"
              value={email}
              onChange={(event) => setEmail(event.target.value)}
              className="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-white"
              placeholder="you@example.com"
            />
          </div>

          <div>
            <div className="flex items-center justify-between mb-1">
              <label className="block text-sm text-slate-300">Password</label>
              {mode === "login" && (
                <button
                  type="button"
                  onClick={() => setShowForgot(true)}
                  className="text-xs text-blue-400 hover:text-blue-300"
                >
                  Forgot password?
                </button>
              )}
            </div>
            <input
              type="password"
              value={password}
              onChange={(event) => setPassword(event.target.value)}
              className="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-white"
              placeholder="At least 8 characters"
            />
          </div>

          <label className="flex items-center gap-2 text-sm text-slate-300 cursor-pointer hover:text-slate-200">
            <input
              type="checkbox"
              checked={rememberMe}
              onChange={(event) => setRememberMe(event.target.checked)}
              className="w-4 h-4 rounded border-slate-600 bg-slate-800 text-blue-500 focus:ring-blue-500 focus:ring-2"
            />
            <span>Remember me</span>
          </label>

          {error && <p className="text-sm text-red-400">{error}</p>}

          <Button onClick={submit} className="w-full" disabled={isSubmitting}>
            {isSubmitting ? "Please wait..." : mode === "login" ? "Login" : "Create Account"}
          </Button>
        </div>

        {/* Forgot Password Modal */}
        {showForgot && (
          <ForgotPasswordModal
            email={email}
            setEmail={setEmail}
            onClose={() => setShowForgot(false)}
            onSent={() => setResetSent(true)}
          />
        )}

        {/* Reset Success Message */}
        {resetSent && (
          <div className="mt-4 p-4 bg-green-900/30 border border-green-700 rounded-lg">
            <p className="text-sm text-green-400">
              ✓ Password reset link sent! Check your email.
            </p>
          </div>
        )}
      </div>
    </div>
  )
}

function ForgotPasswordModal({
  email,
  setEmail,
  onClose,
  onSent,
}: {
  email: string
  setEmail: (email: string) => void
  onClose: () => void
  onSent: () => void
}) {
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleSubmit = async () => {
    setError(null)

    if (!email.trim()) {
      setError("Email is required")
      return
    }

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

      const data = await res.json()
      if (!res.ok) {
        setError(data.error || "Failed to send reset link")
        return
      }

      onSent()
      onClose()
    } catch {
      setError("Failed to send reset link")
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
      <div className="w-full max-w-md border border-slate-800 rounded-xl bg-slate-900 p-6">
        <h2 className="text-xl font-semibold text-white mb-2">Reset Password</h2>
        <p className="text-sm text-slate-400 mb-4">
          Enter your email and we&apos;ll send you a link to reset your password.
        </p>

        <div className="space-y-4">
          <div>
            <label className="block text-sm text-slate-300 mb-1">Email</label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="w-full px-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-white"
              placeholder="you@example.com"
            />
          </div>

          {error && <p className="text-sm text-red-400">{error}</p>}

          <div className="flex gap-2">
            <Button onClick={onClose} variant="outline" className="flex-1">
              Cancel
            </Button>
            <Button onClick={handleSubmit} className="flex-1" disabled={isSubmitting}>
              {isSubmitting ? "Sending..." : "Send Link"}
            </Button>
          </div>
        </div>
      </div>
    </div>
  )
}
