'use client';

import { useState } from 'react';
import { Eye, EyeOff, Lock, CheckCircle, Check, X, AlertCircle, KeyRound } from 'lucide-react';
import { useLanguage } from '@client/contexts/LanguageContext';

export default function ChangePasswordForm() {
  const { t } = useLanguage();
  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 [loading, setLoading] = useState(false);
  const [done, setDone] = useState(false);
  const [error, setError] = useState('');

  const rules = [
    { label: t('changePassword.ruleMinChars', 'At least 8 characters'), pass: newPassword.length >= 8 },
    { label: t('changePassword.ruleUppercase', 'One uppercase letter'), pass: /[A-Z]/.test(newPassword) },
    { label: t('changePassword.ruleNumber', 'One number'), pass: /[0-9]/.test(newPassword) },
  ];

  const allValid = rules.every(r => r.pass) && newPassword === confirmPassword && currentPassword.length > 0;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!allValid) return;
    setLoading(true);
    setError('');
    try {
      const res = await fetch('/api/auth/change-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ currentPassword, newPassword }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || t('changePassword.errorDefault', 'Failed to change password'));
      setDone(true);
    } catch (err: any) {
      setError(err?.message || t('changePassword.errorDefault', 'Failed to change password. Please try again.'));
    } finally {
      setLoading(false);
    }
  };

  const handleReset = () => {
    setCurrentPassword('');
    setNewPassword('');
    setConfirmPassword('');
    setDone(false);
    setError('');
  };

  return (
    <div className="max-w-lg mx-auto">
      <div className="mb-6">
        <h1 className="text-xl font-bold" style={{ color: 'hsl(var(--foreground))' }}>{t('changePassword.title', 'Change Password')}</h1>
        <p className="text-sm mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('changePassword.description', "Update your account password. You'll need your current password to make changes.")}</p>
      </div>

      <div className="card p-6">
        {done ? (
          <div className="text-center py-6">
            <div className="w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4" style={{ backgroundColor: 'hsl(var(--success-bg))' }}>
              <CheckCircle size={32} style={{ color: 'hsl(var(--success))' }} />
            </div>
            <h2 className="text-lg font-bold mb-2" style={{ color: 'hsl(var(--foreground))' }}>{t('changePassword.updatedTitle', 'Password Updated')}</h2>
            <p className="text-sm mb-6" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('changePassword.updatedDesc', 'Your password has been changed successfully.')}</p>
            <button onClick={handleReset} className="btn-ghost text-sm font-semibold" style={{ color: 'hsl(var(--primary))' }}>
              {t('changePassword.changeAgain', 'Change again')}
            </button>
          </div>
        ) : (
          <form onSubmit={handleSubmit} className="space-y-5">
            {error && (
              <div className="flex items-center gap-2 p-3 rounded-xl text-sm" style={{ backgroundColor: 'hsl(0, 84%, 97%)', color: 'hsl(0, 84%, 44%)', border: '1px solid hsl(0, 84%, 90%)' }}>
                <AlertCircle size={15} className="shrink-0" />
                {error}
              </div>
            )}

            <div>
              <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('changePassword.currentPassword', 'Current Password')}</label>
              <div className="relative">
                <Lock size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
                <input
                  type={showCurrent ? 'text' : 'password'}
                  className="input-base pl-9 pr-10"
                  placeholder={t('changePassword.currentPlaceholder', 'Enter current password')}
                  value={currentPassword}
                  onChange={e => setCurrentPassword(e.target.value)}
                  required
                />
                <button type="button" className="absolute right-3 top-1/2 -translate-y-1/2" onClick={() => setShowCurrent(!showCurrent)} style={{ color: 'hsl(var(--muted-foreground))' }}>
                  {showCurrent ? <EyeOff size={15} /> : <Eye size={15} />}
                </button>
              </div>
            </div>

            <div className="pt-2" style={{ borderTop: '1px solid hsl(var(--border))' }}>
              <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('changePassword.newPassword', 'New Password')}</label>
              <div className="relative">
                <KeyRound size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
                <input
                  type={showNew ? 'text' : 'password'}
                  className="input-base pl-9 pr-10"
                  placeholder={t('changePassword.newPlaceholder', 'Enter new password')}
                  value={newPassword}
                  onChange={e => setNewPassword(e.target.value)}
                  required
                />
                <button type="button" className="absolute right-3 top-1/2 -translate-y-1/2" onClick={() => setShowNew(!showNew)} style={{ color: 'hsl(var(--muted-foreground))' }}>
                  {showNew ? <EyeOff size={15} /> : <Eye size={15} />}
                </button>
              </div>
              {newPassword && (
                <div className="mt-2 space-y-1">
                  {rules.map(r => (
                    <div key={r.label} className="flex items-center gap-2 text-xs">
                      {r.pass ? <Check size={12} style={{ color: 'hsl(var(--success))' }} /> : <X size={12} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                      <span style={{ color: r.pass ? 'hsl(var(--success))' : 'hsl(var(--muted-foreground))' }}>{r.label}</span>
                    </div>
                  ))}
                </div>
              )}
            </div>

            <div>
              <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('changePassword.confirmPassword', 'Confirm New Password')}</label>
              <div className="relative">
                <KeyRound size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
                <input
                  type={showConfirm ? 'text' : 'password'}
                  className="input-base pl-9 pr-10"
                  placeholder={t('changePassword.confirmPlaceholder', 'Confirm new password')}
                  value={confirmPassword}
                  onChange={e => setConfirmPassword(e.target.value)}
                  required
                />
                <button type="button" className="absolute right-3 top-1/2 -translate-y-1/2" onClick={() => setShowConfirm(!showConfirm)} style={{ color: 'hsl(var(--muted-foreground))' }}>
                  {showConfirm ? <EyeOff size={15} /> : <Eye size={15} />}
                </button>
              </div>
              {confirmPassword && newPassword !== confirmPassword && (
                <p className="text-xs mt-1" style={{ color: 'hsl(var(--danger))' }}>{t('changePassword.mismatch', 'Passwords do not match')}</p>
              )}
            </div>

            <button
              type="submit"
              disabled={loading || !allValid}
              className="btn-primary w-full justify-center py-2.5 disabled:opacity-50"
            >
              {loading ? (
                <span className="flex items-center gap-2">
                  <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                  {t('changePassword.updating', 'Updating...')}
                </span>
              ) : t('changePassword.updateButton', 'Update Password')}
            </button>
          </form>
        )}
      </div>
    </div>
  );
}
