'use client'

import { useState, useEffect, Suspense } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import Link from 'next/link'
import { useAuth } from '@/components/providers/auth-provider'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useToast } from '@/components/ui/use-toast'
import { ArrowLeft, Loader2 } from 'lucide-react'
import { LogoRound } from '@/components/ui/logo'

export default function LoginPage() {
  return (
    <Suspense fallback={<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900"><Loader2 className="w-8 h-8 animate-spin text-gray-400" /></div>}>
      <LoginForm />
    </Suspense>
  )
}

function LoginForm() {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [rememberMe, setRememberMe] = useState(true)
  const [isLoading, setIsLoading] = useState(false)
  const [resendLoading, setResendLoading] = useState(false)
  const [resendSuccess, setResendSuccess] = useState(false)
  const [tenantLogo, setTenantLogo] = useState<string | null>(null)
  const [tenantName, setTenantName] = useState<string | null>(null)
  const { login } = useAuth()
  const router = useRouter()
  const searchParams = useSearchParams()
  const { toast } = useToast()
  const redirectTo = searchParams.get('redirect')
  const tenantSlug = searchParams.get('tenant')
  const verified = searchParams.get('verified')
  const errorParam = searchParams.get('error')

  // Fetch tenant logo if slug is provided
  useEffect(() => {
    if (tenantSlug) {
      fetch(`/api/tenants/by-slug/${tenantSlug}`)
        .then(res => res.ok ? res.json() : null)
        .then(data => {
          if (data?.tenant) {
            setTenantLogo(data.tenant.logoUrl)
            setTenantName(data.tenant.name)
          }
        })
        .catch(() => {})
    }
  }, [tenantSlug])

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

    const result = await login(email, password, rememberMe)

    if (result.success) {
      toast({
        title: 'Erfolgreich angemeldet',
        description: 'Willkommen bei Lageplan!',
      })
      // Redirect: use explicit redirect param, or tenant slug, or /app
      if (redirectTo) {
        router.push(redirectTo)
      } else {
        try {
          const meRes = await fetch('/api/auth/me')
          if (meRes.ok) {
            const meData = await meRes.json()
            if (meData.user?.tenantSlug) {
              router.push(`/${meData.user.tenantSlug}`)
              return
            }
          }
        } catch {}
        router.push('/app')
      }
    } else {
      toast({
        title: 'Anmeldung fehlgeschlagen',
        description: result.error || 'Bitte überprüfen Sie Ihre Zugangsdaten.',
        variant: 'destructive',
      })
    }

    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">
            {tenantLogo ? (
              <img src={tenantLogo} alt={tenantName || 'Logo'} className="w-16 h-16 object-contain mb-3 rounded-lg" />
            ) : (
              <LogoRound size={56} className="mb-3" />
            )}
            <h1 className="text-2xl font-bold text-foreground">Anmelden</h1>
            <p className="text-muted-foreground text-sm mt-1">
              {tenantName || 'Feuerwehr Krokier-App'}
            </p>
          </div>

          {verified === 'true' && (
            <div className="bg-green-50 dark:bg-green-950/30 border border-green-200 dark:border-green-800 rounded-lg p-3 mb-4 text-sm text-green-700 dark:text-green-400 text-center">
              E-Mail-Adresse erfolgreich bestätigt! Sie können sich jetzt anmelden.
            </div>
          )}
          {errorParam === 'invalid-token' && (
            <div className="bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-800 rounded-lg p-3 mb-4 text-sm text-red-700 dark:text-red-400 text-center">
              <p>Ungültiger oder abgelaufener Bestätigungslink.</p>
              <p className="mt-1 text-xs">Geben Sie Ihre E-Mail ein und klicken Sie unten, um einen neuen Link zu erhalten.</p>
              {resendSuccess ? (
                <p className="mt-2 text-green-600 dark:text-green-400 font-medium">Neue Bestätigungsmail gesendet!</p>
              ) : (
                <button
                  type="button"
                  disabled={resendLoading || !email}
                  onClick={async () => {
                    setResendLoading(true)
                    try {
                      const res = await fetch('/api/auth/resend-verification', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ email }),
                      })
                      if (res.ok) setResendSuccess(true)
                      else toast({ title: 'Fehler', description: 'Konnte Bestätigungsmail nicht senden.', variant: 'destructive' })
                    } catch { toast({ title: 'Fehler', description: 'Verbindungsfehler.', variant: 'destructive' }) }
                    setResendLoading(false)
                  }}
                  className="mt-2 text-xs font-medium text-red-600 dark:text-red-400 underline hover:no-underline disabled:opacity-50"
                >
                  {resendLoading ? 'Wird gesendet...' : 'Bestätigungsmail erneut senden'}
                </button>
              )}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="space-y-1.5">
              <Label htmlFor="email">E-Mail</Label>
              <Input
                id="email"
                type="email"
                placeholder="name@feuerwehr.ch"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
                disabled={isLoading}
              />
            </div>

            <div className="space-y-1.5">
              <div className="flex items-center justify-between">
                <Label htmlFor="password">Passwort</Label>
                <Link href="/forgot-password" className="text-xs text-red-600 hover:text-red-500">
                  Passwort vergessen?
                </Link>
              </div>
              <Input
                id="password"
                type="password"
                placeholder="••••••••"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                required
                disabled={isLoading}
              />
            </div>

            <label className="flex items-center gap-2 cursor-pointer select-none">
              <input
                type="checkbox"
                checked={rememberMe}
                onChange={(e) => setRememberMe(e.target.checked)}
                className="w-4 h-4 rounded border-gray-300 text-red-600 focus:ring-red-500"
              />
              <span className="text-sm text-muted-foreground">Angemeldet bleiben</span>
            </label>

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

          <div className="mt-6 text-center text-sm text-muted-foreground">
            Noch kein Konto?{' '}
            <Link href="/register" className="text-red-600 hover:text-red-500 font-medium">
              Kostenlos registrieren
            </Link>
          </div>
        </div>

        {/* Back to landing */}
        <div className="text-center mt-4">
          <Link href="/" 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 Startseite
          </Link>
        </div>
      </div>
    </div>
  )
}
