'use client'

import { useState } from 'react'
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { ArrowLeft, Loader2, Mail, CheckCircle, ExternalLink } from 'lucide-react'
import { LogoRound } from '@/components/ui/logo'

export default function ForgotPasswordPage() {
  const [email, setEmail] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [sent, setSent] = useState(false)
  const [message, setMessage] = useState('')
  const [resetUrl, setResetUrl] = useState<string | null>(null)
  const [error, setError] = useState('')

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsLoading(true)
    setError('')
    setResetUrl(null)

    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) {
        setSent(true)
        setMessage(data.message)
        if (data.resetUrl) {
          setResetUrl(data.resetUrl)
        }
      } else {
        setError(data.error || 'Ein Fehler ist aufgetreten.')
      }
    } catch {
      setError('Verbindungsfehler. Bitte versuchen Sie es erneut.')
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 px-4">
      <div className="w-full max-w-md">
        <div className="bg-card rounded-xl shadow-2xl p-8 border border-border">
          <div className="flex flex-col items-center mb-6">
            <LogoRound size={56} className="mb-3" />
            <h1 className="text-2xl font-bold text-foreground">Passwort vergessen</h1>
            <p className="text-muted-foreground text-sm mt-1 text-center">
              Geben Sie Ihre E-Mail-Adresse ein und wir senden Ihnen einen Link zum Zurücksetzen.
            </p>
          </div>

          {sent ? (
            <div className="text-center space-y-4">
              <div className="w-12 h-12 bg-green-600/20 rounded-full flex items-center justify-center mx-auto">
                <CheckCircle className="w-6 h-6 text-green-500" />
              </div>
              <p className="text-sm text-muted-foreground">{message}</p>
              {resetUrl && (
                <div className="mt-4 p-3 bg-muted rounded-lg">
                  <p className="text-xs text-muted-foreground mb-2">Reset-Link (kein SMTP konfiguriert):</p>
                  <Link href={resetUrl} className="text-sm text-red-500 hover:text-red-400 break-all flex items-center gap-1 justify-center">
                    <ExternalLink className="w-3.5 h-3.5 flex-shrink-0" />
                    Link öffnen
                  </Link>
                </div>
              )}
              <div className="pt-2">
                <Link href="/login" className="text-sm text-red-600 hover:text-red-500 font-medium">
                  Zurück zur Anmeldung
                </Link>
              </div>
            </div>
          ) : (
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="space-y-1.5">
                <Label htmlFor="email">E-Mail</Label>
                <div className="relative">
                  <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                  <Input
                    id="email"
                    type="email"
                    placeholder="name@feuerwehr.ch"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    required
                    disabled={isLoading}
                    className="pl-10"
                  />
                </div>
              </div>

              {error && (
                <p className="text-sm text-destructive">{error}</p>
              )}

              <Button
                type="submit"
                className="w-full bg-red-600 hover:bg-red-700"
                disabled={isLoading || !email}
              >
                {isLoading ? (
                  <><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Senden...</>
                ) : (
                  'Link senden'
                )}
              </Button>
            </form>
          )}
        </div>

        <div className="text-center mt-4">
          <Link href="/login" className="text-sm text-gray-400 hover:text-gray-300 inline-flex items-center gap-1">
            <ArrowLeft className="w-3.5 h-3.5" />
            Zurück zur Anmeldung
          </Link>
        </div>
      </div>
    </div>
  )
}
