'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
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, Building2, User, Mail, Lock, Loader2, Check } from 'lucide-react'
import { LogoRound } from '@/components/ui/logo'

export default function RegisterPage() {
  const [organizationName, setOrganizationName] = useState('')
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [privacyAccepted, setPrivacyAccepted] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [isSuccess, setIsSuccess] = useState(false)
  const router = useRouter()
  const { toast } = useToast()

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

    if (password !== confirmPassword) {
      toast({ title: 'Passwörter stimmen nicht überein', variant: 'destructive' })
      return
    }

    if (password.length < 8) {
      toast({ title: 'Passwort muss mindestens 8 Zeichen haben', variant: 'destructive' })
      return
    }

    setIsLoading(true)
    try {
      const res = await fetch('/api/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ organizationName, name, email, password, privacyAccepted }),
      })

      const data = await res.json()

      if (res.ok) {
        setIsSuccess(true)
      } else {
        toast({
          title: 'Registrierung fehlgeschlagen',
          description: data.error || 'Bitte versuchen Sie es erneut.',
          variant: 'destructive',
        })
      }
    } catch {
      toast({ title: 'Fehler', description: 'Verbindung zum Server fehlgeschlagen.', variant: 'destructive' })
    } finally {
      setIsLoading(false)
    }
  }

  if (isSuccess) {
    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 text-center">
            <div className="w-16 h-16 bg-green-600 rounded-full flex items-center justify-center mx-auto mb-4">
              <Check className="w-8 h-8 text-white" />
            </div>
            <h1 className="text-2xl font-bold text-foreground">Fast geschafft!</h1>
            <p className="text-muted-foreground mt-2">
              Ihr Konto und Ihre Organisation wurden erfolgreich erstellt.
            </p>
            <div className="bg-amber-50 dark:bg-amber-950/30 rounded-lg p-4 mt-4 text-sm border border-amber-200 dark:border-amber-800">
              <p className="font-medium text-amber-800 dark:text-amber-400">E-Mail bestätigen</p>
              <p className="text-amber-700 dark:text-amber-500 mt-1">
                Wir haben Ihnen eine E-Mail mit einem Bestätigungslink gesendet. Bitte klicken Sie auf den Link, um Ihr Konto zu aktivieren.
              </p>
            </div>
            <Button
              className="w-full mt-6 bg-red-600 hover:bg-red-700"
              onClick={() => router.push('/login')}
            >
              Zur Anmeldeseite
            </Button>
          </div>
        </div>
      </div>
    )
  }

  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 py-8">
        <div className="bg-card rounded-xl shadow-2xl p-8 border border-border">
          {/* Header */}
          <div className="flex flex-col items-center mb-6">
            <LogoRound size={56} className="mb-3" />
            <h1 className="text-2xl font-bold text-foreground">Konto erstellen</h1>
            <p className="text-muted-foreground text-sm mt-1">
              Erstellen Sie Ihr Konto für die Feuerwehr Krokier-App
            </p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-4">
            {/* Organization */}
            <div className="space-y-1.5">
              <Label htmlFor="org" className="text-sm flex items-center gap-1.5">
                <Building2 className="w-3.5 h-3.5 text-muted-foreground" />
                Organisation / Feuerwehr
              </Label>
              <Input
                id="org"
                placeholder="z.B. Feuerwehr Wohlen"
                value={organizationName}
                onChange={(e) => setOrganizationName(e.target.value)}
                required
                disabled={isLoading}
              />
            </div>

            {/* Name */}
            <div className="space-y-1.5">
              <Label htmlFor="name" className="text-sm flex items-center gap-1.5">
                <User className="w-3.5 h-3.5 text-muted-foreground" />
                Ihr Name
              </Label>
              <Input
                id="name"
                placeholder="Vor- und Nachname"
                value={name}
                onChange={(e) => setName(e.target.value)}
                required
                disabled={isLoading}
              />
            </div>

            {/* Email */}
            <div className="space-y-1.5">
              <Label htmlFor="email" className="text-sm flex items-center gap-1.5">
                <Mail className="w-3.5 h-3.5 text-muted-foreground" />
                E-Mail-Adresse
              </Label>
              <Input
                id="email"
                type="email"
                placeholder="name@feuerwehr.ch"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
                disabled={isLoading}
              />
            </div>

            {/* Password */}
            <div className="space-y-1.5">
              <Label htmlFor="password" className="text-sm flex items-center gap-1.5">
                <Lock className="w-3.5 h-3.5 text-muted-foreground" />
                Passwort
              </Label>
              <Input
                id="password"
                type="password"
                placeholder="Mindestens 8 Zeichen"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                required
                disabled={isLoading}
              />
            </div>

            {/* Confirm Password */}
            <div className="space-y-1.5">
              <Label htmlFor="confirmPassword" className="text-sm flex items-center gap-1.5">
                <Lock className="w-3.5 h-3.5 text-muted-foreground" />
                Passwort bestätigen
              </Label>
              <Input
                id="confirmPassword"
                type="password"
                placeholder="Passwort wiederholen"
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                required
                disabled={isLoading}
              />
            </div>

            {/* Privacy Policy Checkbox */}
            <div className="pt-2 border-t border-border">
              <label className="flex items-start gap-2.5 cursor-pointer">
                <input
                  type="checkbox"
                  checked={privacyAccepted}
                  onChange={(e) => setPrivacyAccepted(e.target.checked)}
                  className="mt-0.5 w-4 h-4 rounded border-gray-300 text-red-600 focus:ring-red-500 cursor-pointer"
                  disabled={isLoading}
                />
                <span className="text-xs text-muted-foreground leading-relaxed">
                  Ich habe die{' '}
                  <Link href="/datenschutz" target="_blank" className="text-red-500 hover:text-red-400 underline font-medium">
                    Datenschutzerklärung
                  </Link>{' '}
                  gelesen und akzeptiere die Nutzungsbedingungen.
                </span>
              </label>
            </div>

            <Button
              type="submit"
              className="w-full bg-red-600 hover:bg-red-700"
              disabled={isLoading || !organizationName || !name || !email || !password || !confirmPassword || !privacyAccepted}
            >
              {isLoading ? (
                <><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Wird erstellt...</>
              ) : (
                'Kostenlos registrieren'
              )}
            </Button>
          </form>

          <div className="mt-6 text-center text-sm text-muted-foreground">
            Bereits registriert?{' '}
            <Link href="/login" className="text-red-600 hover:text-red-500 font-medium">
              Anmelden
            </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>
  )
}
