import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { authApi } from '../services/api';
import Button from '../components/ui/Button';
import Input from '../components/ui/Input';
import Card from '../components/ui/Card';

const MIN_LENGTH = 12;

function checkComplexity(pw: string) {
  return {
    length: pw.length >= MIN_LENGTH,
    upper: /[A-Z]/.test(pw),
    lower: /[a-z]/.test(pw),
    digit: /[0-9]/.test(pw),
    special: /[^A-Za-z0-9]/.test(pw),
  };
}

function ComplexityHint({ pw }: { pw: string }) {
  const c = checkComplexity(pw);
  const items: [boolean, string][] = [
    [c.length, `Mindestens ${MIN_LENGTH} Zeichen`],
    [c.upper, 'Großbuchstabe'],
    [c.lower, 'Kleinbuchstabe'],
    [c.digit, 'Ziffer'],
    [c.special, 'Sonderzeichen'],
  ];
  return (
    <ul className="text-xs mt-2 space-y-0.5">
      {items.map(([ok, label]) => (
        <li key={label} className={ok ? 'text-green-700' : 'text-gray-500'}>
          {ok ? '✓' : '○'} {label}
        </li>
      ))}
    </ul>
  );
}

export default function ChangeInitialPassword() {
  const { logout, user } = useAuth();
  const navigate = useNavigate();
  const [newPassword, setNewPassword] = useState('');
  const [repeat, setRepeat] = useState('');
  const [error, setError] = useState('');
  const [isSaving, setIsSaving] = useState(false);

  const c = checkComplexity(newPassword);
  const meetsComplexity = c.length && c.upper && c.lower && c.digit && c.special;
  const matches = newPassword.length > 0 && newPassword === repeat;
  const canSubmit = meetsComplexity && matches && !isSaving;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    if (!canSubmit) return;
    setIsSaving(true);
    try {
      const res = await authApi.changeInitialPortalPassword(newPassword);
      if (!res.success) {
        throw new Error(res.error || 'Passwort konnte nicht geändert werden');
      }
      await logout();
      navigate('/login?changed=1', { replace: true });
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Fehler beim Setzen des Passworts');
      setIsSaving(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-100 p-4">
      <Card className="w-full max-w-md">
        <div className="text-center mb-6">
          <h1 className="text-2xl font-bold text-gray-900">Neues Passwort vergeben</h1>
          <p className="text-gray-600 mt-2 text-sm">
            Hallo {user?.firstName || 'Kunde'}, Sie haben sich mit einem Einmalpasswort
            angemeldet. Bitte vergeben Sie jetzt Ihr eigenes Passwort. Danach werden Sie
            ausgeloggt und können sich mit dem neuen Passwort anmelden.
          </p>
        </div>

        {error && (
          <div className="mb-4 p-3 bg-red-50 border border-red-200 text-red-700 rounded-lg text-sm">
            {error}
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <Input
              label="Neues Passwort"
              type="password"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              required
              autoComplete="new-password"
            />
            {newPassword.length > 0 && <ComplexityHint pw={newPassword} />}
          </div>

          <div>
            <Input
              label="Passwort wiederholen"
              type="password"
              value={repeat}
              onChange={(e) => setRepeat(e.target.value)}
              required
              autoComplete="new-password"
            />
            {repeat.length > 0 && !matches && (
              <p className="text-xs text-red-600 mt-1">Passwörter stimmen nicht überein</p>
            )}
          </div>

          <Button type="submit" className="w-full" disabled={!canSubmit}>
            {isSaving ? 'Speichere...' : 'Passwort setzen und ausloggen'}
          </Button>
        </form>
      </Card>
    </div>
  );
}
