import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { X, Eye, EyeOff } from 'lucide-react'
import { changePassword } from '../../api/auth'
import { showToast } from '../../utils/toast'

interface Props {
  open: boolean
  onClose: () => void
}

export function ChangePasswordModal({ open, onClose }: Props) {
  const [currentPassword, setCurrentPassword] = useState('')
  const [newPassword, setNewPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [showCurrent, setShowCurrent] = useState(false)
  const [showNew, setShowNew] = useState(false)
  const [showConfirm, setShowConfirm] = useState(false)
  const [saving, setSaving] = useState(false)

  const errors: string[] = []
  if (newPassword && newPassword.length < 8) errors.push('Mindestens 8 Zeichen')
  if (confirmPassword && newPassword !== confirmPassword) errors.push('Passwörter stimmen nicht überein')

  const canSubmit =
    currentPassword.trim() &&
    newPassword.length >= 8 &&
    newPassword === confirmPassword &&
    !saving

  const handleSubmit = async () => {
    if (!canSubmit) return
    setSaving(true)
    try {
      await changePassword({
        current_password: currentPassword,
        new_password: newPassword,
      })
      showToast.success('Passwort geändert ✅')
      onClose()
    } catch (err) {
      showToast.error(err instanceof Error ? err.message : 'Fehler beim Ändern')
    } finally {
      setSaving(false)
    }
  }

  const PasswordField = ({
    label,
    value,
    onChange,
    show,
    onToggle,
    placeholder,
  }: {
    label: string
    value: string
    onChange: (v: string) => void
    show: boolean
    onToggle: () => void
    placeholder: string
  }) => (
    <div>
      <label className="block text-sm font-medium text-espresso mb-1">{label}</label>
      <div className="relative">
        <input
          type={show ? 'text' : 'password'}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          className="w-full bg-surface border border-sand rounded-xl px-4 py-3 pr-12 text-espresso placeholder:text-warm-grey/50 focus:outline-none focus:ring-2 focus:ring-primary/30 min-h-[44px]"
          placeholder={placeholder}
        />
        <button
          type="button"
          onClick={onToggle}
          className="absolute right-2 top-1/2 -translate-y-1/2 min-w-[44px] min-h-[44px] flex items-center justify-center text-warm-grey"
        >
          {show ? <EyeOff size={18} /> : <Eye size={18} />}
        </button>
      </div>
    </div>
  )

  return (
    <AnimatePresence>
      {open && (
        <motion.div
          className="fixed inset-0 z-50 flex items-end sm:items-center justify-center bg-black/40 backdrop-blur-sm"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          onClick={onClose}
        >
          <motion.div
            className="bg-cream w-full sm:max-w-md sm:rounded-2xl rounded-t-2xl p-6 max-h-[90vh] overflow-y-auto"
            initial={{ y: '100%' }}
            animate={{ y: 0 }}
            exit={{ y: '100%' }}
            transition={{ type: 'spring', damping: 25, stiffness: 300 }}
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-center justify-between mb-6">
              <h2 className="font-display text-xl text-espresso">Passwort ändern</h2>
              <button
                onClick={onClose}
                className="min-w-[44px] min-h-[44px] flex items-center justify-center text-warm-grey"
              >
                <X size={20} />
              </button>
            </div>

            <div className="space-y-4">
              <PasswordField
                label="Aktuelles Passwort"
                value={currentPassword}
                onChange={setCurrentPassword}
                show={showCurrent}
                onToggle={() => setShowCurrent(!showCurrent)}
                placeholder="••••••••"
              />
              <PasswordField
                label="Neues Passwort"
                value={newPassword}
                onChange={setNewPassword}
                show={showNew}
                onToggle={() => setShowNew(!showNew)}
                placeholder="Min. 8 Zeichen"
              />
              <PasswordField
                label="Passwort bestätigen"
                value={confirmPassword}
                onChange={setConfirmPassword}
                show={showConfirm}
                onToggle={() => setShowConfirm(!showConfirm)}
                placeholder="Nochmal eingeben"
              />

              {errors.length > 0 && (
                <div className="text-sm text-berry-red space-y-1">
                  {errors.map((e) => (
                    <p key={e}>⚠️ {e}</p>
                  ))}
                </div>
              )}

              <button
                onClick={handleSubmit}
                disabled={!canSubmit}
                className="w-full bg-primary text-white rounded-xl py-3 font-medium min-h-[44px] disabled:opacity-50 transition-opacity"
              >
                {saving ? 'Wird geändert...' : 'Passwort ändern'}
              </button>
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  )
}
