import { useState } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '@/context/AuthContext'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import {
  Dialog, DialogContent, DialogHeader, DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { AlertCircle, CheckCircle, Loader2, Moon, Sun } from 'lucide-react'
import { useTheme } from '@/hooks/useTheme'
import api from '@/services/api'

const loginSchema = z.object({
  email: z.string().email('Bitte geben Sie eine gueltige E-Mail-Adresse ein'),
  password: z.string().min(1, 'Passwort ist erforderlich'),
  mfa_code: z.string().optional(),
})

type LoginFormValues = z.infer<typeof loginSchema>

export function LoginPage() {
  const { login } = useAuth()
  const { theme, toggleTheme } = useTheme()
  const navigate = useNavigate()
  const [error, setError] = useState<string | null>(null)
  const [showMfa, setShowMfa] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [legalDialog, setLegalDialog] = useState<{ title: string; url: string } | null>(null)
  const [showForgot, setShowForgot] = useState(false)
  const [forgotEmail, setForgotEmail] = useState('')
  const [forgotLoading, setForgotLoading] = useState(false)
  const [forgotSent, setForgotSent] = useState(false)
  const [forgotError, setForgotError] = useState('')

  const handleForgotPassword = async () => {
    if (!forgotEmail.trim()) return
    setForgotLoading(true)
    setForgotError('')
    try {
      await api.post('/auth/forgot-password', { email: forgotEmail.trim() })
      setForgotSent(true)
    } catch {
      setForgotError('Ein Fehler ist aufgetreten. Bitte versuchen Sie es erneut.')
    } finally {
      setForgotLoading(false)
    }
  }

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<LoginFormValues>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      email: '',
      password: '',
      mfa_code: '',
    },
  })

  const onSubmit = async (data: LoginFormValues) => {
    setError(null)
    setIsSubmitting(true)
    try {
      await login({
        email: data.email,
        password: data.password,
        mfa_code: data.mfa_code || undefined,
      })
      navigate('/dashboard')
    } catch (err: unknown) {
      const axiosError = err as { response?: { data?: { detail?: string }; status?: number } }
      const detail = axiosError.response?.data?.detail || ''

      if (detail.toLowerCase().includes('mfa') || detail.toLowerCase().includes('2fa')) {
        setShowMfa(true)
        setError('Bitte geben Sie Ihren MFA-Code ein')
      } else if (axiosError.response?.status === 401) {
        setError('Ungueltige Anmeldedaten')
      } else if (axiosError.response?.status === 423) {
        setError('Konto gesperrt. Bitte kontaktieren Sie den Administrator.')
      } else {
        setError(detail || 'Ein Fehler ist aufgetreten')
      }
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className="flex min-h-screen flex-col items-center justify-center bg-background px-4">
      <Button
        variant="ghost"
        size="icon"
        onClick={toggleTheme}
        className="absolute top-4 right-4"
      >
        {theme === 'dark' ? <Sun className="h-5 w-5" /> : <Moon className="h-5 w-5" />}
        <span className="sr-only">Design umschalten</span>
      </Button>
      <Card className="w-full max-w-md">
        <CardHeader className="text-center">
          <CardTitle className="text-2xl">DAK Portal</CardTitle>
          <CardDescription>Melden Sie sich mit Ihrem Konto an</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
            {error && (
              <Alert variant="destructive">
                <AlertCircle className="h-4 w-4" />
                <AlertDescription>{error}</AlertDescription>
              </Alert>
            )}

            <div className="space-y-2">
              <Label htmlFor="email">E-Mail</Label>
              <Input
                id="email"
                type="email"
                placeholder="name@dak.de"
                autoComplete="email"
                {...register('email')}
              />
              {errors.email && (
                <p className="text-sm text-destructive">{errors.email.message}</p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="password">Passwort</Label>
              <Input
                id="password"
                type="password"
                autoComplete="current-password"
                {...register('password')}
              />
              {errors.password && (
                <p className="text-sm text-destructive">{errors.password.message}</p>
              )}
            </div>

            {showMfa && (
              <div className="space-y-2">
                <Label htmlFor="mfa_code">MFA-Code</Label>
                <Input
                  id="mfa_code"
                  type="text"
                  inputMode="numeric"
                  placeholder="123456"
                  autoComplete="one-time-code"
                  {...register('mfa_code')}
                />
              </div>
            )}

            <Button type="submit" className="w-full" disabled={isSubmitting}>
              {isSubmitting ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Wird angemeldet...
                </>
              ) : (
                'Anmelden'
              )}
            </Button>

            <div className="text-center">
              <button
                type="button"
                onClick={() => { setShowForgot(!showForgot); setForgotSent(false); setForgotError('') }}
                className="text-sm text-muted-foreground hover:text-foreground underline underline-offset-2 transition-colors"
              >
                Passwort vergessen?
              </button>
            </div>

            {showForgot && (
              <div className="space-y-3 rounded-lg border p-3">
                {forgotSent ? (
                  <div className="flex items-start gap-2">
                    <CheckCircle className="h-4 w-4 text-green-600 mt-0.5 shrink-0" />
                    <p className="text-sm text-muted-foreground">
                      Falls ein Konto mit dieser E-Mail existiert, wurde ein Link zum Zurücksetzen gesendet. Bitte prüfen Sie Ihr Postfach.
                    </p>
                  </div>
                ) : (
                  <>
                    <p className="text-sm text-muted-foreground">
                      Geben Sie Ihre E-Mail-Adresse ein. Sie erhalten einen Link zum Zurücksetzen Ihres Passworts.
                    </p>
                    <Input
                      type="email"
                      placeholder="name@dak.de"
                      value={forgotEmail}
                      onChange={(e) => setForgotEmail(e.target.value)}
                      onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); handleForgotPassword() } }}
                    />
                    {forgotError && <p className="text-sm text-destructive">{forgotError}</p>}
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      className="w-full"
                      onClick={handleForgotPassword}
                      disabled={forgotLoading || !forgotEmail.trim()}
                    >
                      {forgotLoading ? (
                        <>
                          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                          Wird gesendet...
                        </>
                      ) : (
                        'Reset-Link senden'
                      )}
                    </Button>
                  </>
                )}
              </div>
            )}

          </form>
        </CardContent>
      </Card>

      <div className="mt-4 flex items-center gap-3 text-xs text-muted-foreground">
        <button
          onClick={() => setLegalDialog({ title: 'Impressum', url: 'https://complexcaresolutions.de/impressum/' })}
          className="hover:text-foreground underline underline-offset-2 transition-colors"
        >
          Impressum
        </button>
        <span>·</span>
        <button
          onClick={() => setLegalDialog({ title: 'Datenschutzerklärung', url: 'https://www.complexcaresolutions.de/datenschutzerklaerung/' })}
          className="hover:text-foreground underline underline-offset-2 transition-colors"
        >
          Datenschutz
        </button>
      </div>

      <Dialog open={!!legalDialog} onOpenChange={(open) => { if (!open) setLegalDialog(null) }}>
        <DialogContent className="max-w-4xl h-[85vh] flex flex-col p-0">
          <DialogHeader className="px-6 pt-6 pb-2">
            <DialogTitle>{legalDialog?.title}</DialogTitle>
          </DialogHeader>
          <iframe
            src={legalDialog?.url}
            className="flex-1 w-full border-0 rounded-b-lg"
            title={legalDialog?.title}
          />
        </DialogContent>
      </Dialog>
    </div>
  )
}
