import { useState, useEffect } from 'react'
import { Link, useSearchParams, useNavigate } from 'react-router-dom'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { auth } from '@/lib/appwrite'
import { Mail, Loader2, CheckCircle, XCircle, Eye, EyeOff } from 'lucide-react'

export function ResetPassword() {
  const [searchParams] = useSearchParams()
  const navigate = useNavigate()
  
  const userId = searchParams.get('userId')
  const secret = searchParams.get('secret')

  const [password, setPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [showPassword, setShowPassword] = useState(false)
  const [loading, setLoading] = useState(false)
  const [success, setSuccess] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    if (!userId || !secret) {
      setError('Ungültiger oder abgelaufener Link')
    }
  }, [userId, secret])

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

    if (password !== confirmPassword) {
      setError('Passwörter stimmen nicht überein')
      return
    }

    if (password.length < 8) {
      setError('Passwort muss mindestens 8 Zeichen lang sein')
      return
    }

    if (!userId || !secret) {
      setError('Ungültiger Link')
      return
    }

    setLoading(true)

    try {
      await auth.resetPassword(userId, secret, password)
      setSuccess(true)
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Fehler beim Zurücksetzen des Passworts')
    } finally {
      setLoading(false)
    }
  }

  // Password strength indicator
  const getPasswordStrength = () => {
    if (!password) return { strength: 0, label: '', color: '' }
    
    let strength = 0
    if (password.length >= 8) strength++
    if (/[A-Z]/.test(password)) strength++
    if (/[a-z]/.test(password)) strength++
    if (/[0-9]/.test(password)) strength++
    if (/[^A-Za-z0-9]/.test(password)) strength++

    const levels = [
      { strength: 1, label: 'Sehr schwach', color: 'bg-red-500' },
      { strength: 2, label: 'Schwach', color: 'bg-orange-500' },
      { strength: 3, label: 'Mittel', color: 'bg-yellow-500' },
      { strength: 4, label: 'Stark', color: 'bg-green-500' },
      { strength: 5, label: 'Sehr stark', color: 'bg-green-600' },
    ]

    return levels[strength - 1] || { strength: 0, label: '', color: '' }
  }

  const passwordStrength = getPasswordStrength()

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-900 dark:to-slate-800 flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        {/* Logo */}
        <Link to="/" className="flex items-center justify-center mb-8 leading-none">
          <img 
            src="/logo.png" 
            alt="MailFlow Logo" 
            className="w-24 h-24 rounded-xl object-contain pr-[5px] block"
            style={{ display: 'block', margin: 0, padding: 0 }}
          />
          <span className="text-xl font-bold text-slate-900 dark:text-slate-100 ml-[5px]">
            Mail<span className="text-primary-600 dark:text-primary-400">Flow</span>
          </span>
        </Link>

        <Card className="shadow-xl border-0 dark:bg-slate-800 dark:border-slate-700">
          <CardHeader className="text-center pb-2">
            <CardTitle className="text-2xl dark:text-slate-100">
              {success ? 'Passwort geändert!' : 'Neues Passwort festlegen'}
            </CardTitle>
            <CardDescription className="dark:text-slate-400">
              {success 
                ? 'Dein Passwort wurde erfolgreich geändert.' 
                : 'Wähle ein sicheres neues Passwort für deinen Account.'
              }
            </CardDescription>
          </CardHeader>
          <CardContent>
            {success ? (
              <div className="text-center py-8">
                <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-green-100 dark:bg-green-900/30 flex items-center justify-center">
                  <CheckCircle className="w-8 h-8 text-green-600 dark:text-green-400" />
                </div>
                <p className="text-slate-600 dark:text-slate-400 mb-6">
                  Du kannst dich jetzt mit deinem neuen Passwort anmelden.
                </p>
                <Button onClick={() => navigate('/login')} className="w-full">
                  Zum Login
                </Button>
              </div>
            ) : !userId || !secret ? (
              <div className="text-center py-8">
                <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center">
                  <XCircle className="w-8 h-8 text-red-600 dark:text-red-400" />
                </div>
                <h3 className="font-semibold text-slate-900 dark:text-slate-100 mb-2">Ungültiger Link</h3>
                <p className="text-slate-600 dark:text-slate-400 mb-6">
                  Dieser Link zum Zurücksetzen des Passworts ist ungültig oder abgelaufen.
                </p>
                <Link to="/forgot-password">
                  <Button className="w-full">Neuen Link anfordern</Button>
                </Link>
              </div>
            ) : (
              <form onSubmit={handleSubmit} className="space-y-6">
                {error && (
                  <div className="p-3 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-lg text-red-700 dark:text-red-300 text-sm">
                    {error}
                  </div>
                )}

                <div className="space-y-2">
                  <Label htmlFor="password" className="dark:text-slate-200">Neues Passwort</Label>
                  <div className="relative">
                    <Input
                      id="password"
                      type={showPassword ? 'text' : 'password'}
                      placeholder="••••••••"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      required
                      autoFocus
                      className="dark:bg-slate-800 dark:border-slate-600 dark:text-slate-100"
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 dark:text-slate-500 hover:text-slate-600 dark:hover:text-slate-300"
                    >
                      {showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                    </button>
                  </div>
                  
                  {/* Password strength indicator */}
                  {password && (
                    <div className="space-y-1">
                      <div className="flex gap-1">
                        {[1, 2, 3, 4, 5].map((level) => (
                          <div
                            key={level}
                            className={`h-1 flex-1 rounded-full transition-colors ${
                              level <= passwordStrength.strength
                                ? passwordStrength.color
                                : 'bg-slate-200 dark:bg-slate-700'
                            }`}
                          />
                        ))}
                      </div>
                      <p className={`text-xs ${
                        passwordStrength.strength < 3 ? 'text-red-500 dark:text-red-400' : 'text-green-600 dark:text-green-400'
                      }`}>
                        {passwordStrength.label}
                      </p>
                    </div>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="confirmPassword" className="dark:text-slate-200">Passwort bestätigen</Label>
                  <Input
                    id="confirmPassword"
                    type={showPassword ? 'text' : 'password'}
                    placeholder="••••••••"
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                    required
                    className="dark:bg-slate-800 dark:border-slate-600 dark:text-slate-100"
                  />
                  {confirmPassword && password !== confirmPassword && (
                    <p className="text-xs text-red-500 dark:text-red-400">Passwörter stimmen nicht überein</p>
                  )}
                </div>

                <Button 
                  type="submit" 
                  className="w-full" 
                  disabled={loading || password !== confirmPassword || password.length < 8}
                >
                  {loading ? (
                    <>
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                      Wird gespeichert...
                    </>
                  ) : (
                    'Passwort speichern'
                  )}
                </Button>
              </form>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
