'use client';

import { useState } from 'react';
import { X, Loader2 } from 'lucide-react';
import { getErrorMessage } from '@/lib/errors';
import { useSystemConfig } from '@/hooks/useSystemConfig';

interface ChangePasswordDialogProps {
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
  title?: string;
  requireCurrentPassword?: boolean;
  variant?: 'admin' | 'user';
}

export default function ChangePasswordDialog({
  open,
  onClose,
  onSuccess,
  title = 'Change Password',
  requireCurrentPassword = true,
  variant = 'user',
}: ChangePasswordDialogProps) {
  const sysConfig = useSystemConfig();
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

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

    if (requireCurrentPassword && !currentPassword) {
      setError('Current password is required');
      return;
    }

    if (newPassword.length < sysConfig.minPasswordLength) {
      setError(`New password must be at least ${sysConfig.minPasswordLength} characters`);
      return;
    }

    if (newPassword !== confirmPassword) {
      setError('Passwords do not match');
      return;
    }

    if (newPassword === currentPassword) {
      setError('New password must be different from the current password');
      return;
    }

    setLoading(true);
    try {
      if (variant === 'admin') {
        const { adminService } = await import('@/services/admin.service');
        if (requireCurrentPassword) {
          await adminService.changePassword({ currentPassword, newPassword });
        } else {
          await adminService.adminChangePassword('', newPassword);
        }
      } else {
        const { authService } = await import('@/services/auth.service');
        await authService.changePassword({ currentPassword, newPassword });
      }
      onSuccess();
      onClose();
      setCurrentPassword('');
      setNewPassword('');
      setConfirmPassword('');
    } catch (err: any) {
      setError(getErrorMessage(err));
    } finally {
      setLoading(false);
    }
  };

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" onClick={onClose}>
      <div className="w-full max-w-md rounded-xl border border-line bg-white shadow-2xl dark:border-white/10 dark:bg-slate-900" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between border-b border-line p-5 dark:border-white/10">
          <h2 className="text-lg font-semibold text-ink dark:text-white">{title}</h2>
          <button onClick={onClose} className="rounded-lg p-1 text-ink-muted hover:text-ink dark:text-slate-400 dark:hover:text-white">
            <X className="h-5 w-5" />
          </button>
        </div>
        <form onSubmit={handleSubmit} className="p-5 space-y-4">
          {error && (
            <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-600 dark:text-red-400">
              {error}
            </div>
          )}
          {requireCurrentPassword && (
            <div>
              <label className="mb-1 block text-sm font-medium text-ink dark:text-slate-300">Current Password <span className="text-red-500 dark:text-red-400">*</span></label>
              <input
                type="password"
                value={currentPassword}
                onChange={(e) => setCurrentPassword(e.target.value)}
                required
                placeholder="Enter current password"
                className="w-full rounded-lg border border-line bg-white px-4 py-2 text-ink placeholder:text-ink-faint focus:border-primary-500 focus:outline-none dark:border-white/10 dark:bg-white/5 dark:text-white dark:placeholder:text-slate-400 dark:focus:border-blue-500"
              />
            </div>
          )}
          <div>
            <label className="mb-1 block text-sm font-medium text-ink dark:text-slate-300">New Password <span className="text-red-500 dark:text-red-400">*</span></label>
            <input
              type="password"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              required
              minLength={sysConfig.minPasswordLength}
              placeholder={`Minimum ${sysConfig.minPasswordLength} characters`}
              className="w-full rounded-lg border border-line bg-white px-4 py-2 text-ink placeholder:text-ink-faint focus:border-primary-500 focus:outline-none dark:border-white/10 dark:bg-white/5 dark:text-white dark:placeholder:text-slate-400 dark:focus:border-blue-500"
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-ink dark:text-slate-300">Confirm New Password <span className="text-red-500 dark:text-red-400">*</span></label>
            <input
              type="password"
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              required
              minLength={sysConfig.minPasswordLength}
              placeholder="Repeat new password"
              className="w-full rounded-lg border border-line bg-white px-4 py-2 text-ink placeholder:text-ink-faint focus:border-primary-500 focus:outline-none dark:border-white/10 dark:bg-white/5 dark:text-white dark:placeholder:text-slate-400 dark:focus:border-blue-500"
            />
          </div>
          <div className="flex justify-end gap-3 border-t border-line pt-4 dark:border-white/10">
            <button
              type="button"
              onClick={onClose}
              className="rounded-lg border border-line px-4 py-2 text-sm text-ink-muted hover:bg-surface-raised dark:border-white/10 dark:text-slate-300 dark:hover:bg-white/5"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={loading}
              className="rounded-lg bg-primary-600 px-4 py-2 text-sm font-semibold text-white hover:bg-primary-700 disabled:opacity-50 flex items-center gap-2 dark:bg-blue-600 dark:hover:bg-blue-700"
            >
              {loading && <Loader2 className="h-4 w-4 animate-spin" />}
              {requireCurrentPassword ? 'Change Password' : 'Set Password'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
