'use client';

import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { CheckCircle2 } from 'lucide-react';
import Modal from '@/components/ui/Modal';
import ActionButton from '@/components/ui/ActionButton';
import { iamAuthApi } from '@/lib/api/auth';

interface ChangePasswordModalProps {
  isOpen: boolean;
  onClose: () => void;
}

export default function ChangePasswordModal({ isOpen, onClose }: ChangePasswordModalProps) {
  const [oldPassword, setOldPassword]         = useState('');
  const [newPassword, setNewPassword]         = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [error, setError]                     = useState('');
  const [success, setSuccess]                 = useState(false);

  const changePasswordMutation = useMutation({
    mutationFn: () => iamAuthApi.changePassword({ oldPassword, newPassword, confirmPassword }),
    onSuccess: () => {
      setSuccess(true);
      setTimeout(() => handleClose(), 1500);
    },
    onError: (err: any) => {
      const msg = err.response?.data?.message || '';
      if (err.response?.status === 401) {
        setError('Current password is incorrect.');
      } else if (msg === 'new_password_same_as_old') {
        setError('New password must be different from the current password.');
      } else if (msg === 'new_passwords_do_not_match') {
        setError('New passwords do not match.');
      } else {
        setError(msg || 'Failed to change password. Please try again.');
      }
    },
  });

  const handleClose = () => {
    setOldPassword('');
    setNewPassword('');
    setConfirmPassword('');
    setError('');
    setSuccess(false);
    onClose();
  };

  const handleSubmit = () => {
    setError('');
    if (newPassword.length < 6) {
      setError('New password must be at least 6 characters.');
      return;
    }
    if (newPassword !== confirmPassword) {
      setError('New passwords do not match.');
      return;
    }
    if (newPassword === oldPassword) {
      setError('New password must be different from the current password.');
      return;
    }
    changePasswordMutation.mutate();
  };

  return (
    <Modal isOpen={isOpen} onClose={handleClose} title="Change Password">
      <form
        onSubmit={(e) => { e.preventDefault(); handleSubmit(); }}
        className="space-y-4"
      >
        {success && (
          <div className="flex items-start gap-3 rounded-lg bg-emerald-50 dark:bg-emerald-900/20 border border-emerald-200 dark:border-emerald-800 px-4 py-3">
            <CheckCircle2 className="w-4 h-4 mt-0.5 text-emerald-600 dark:text-emerald-400 flex-shrink-0" />
            <p className="text-sm text-emerald-700 dark:text-emerald-300">Password changed successfully.</p>
          </div>
        )}

        {error && (
          <div className="rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 px-4 py-3">
            <p className="text-sm text-red-700 dark:text-red-300">{error}</p>
          </div>
        )}

        <div>
          <label className="label">Current Password *</label>
          <input
            type="password"
            className="input"
            value={oldPassword}
            onChange={(e) => { setOldPassword(e.target.value); setError(''); }}
            placeholder="Enter current password"
            autoComplete="current-password"
            required
          />
        </div>
        <div>
          <label className="label">New Password *</label>
          <input
            type="password"
            className="input"
            value={newPassword}
            onChange={(e) => { setNewPassword(e.target.value); setError(''); }}
            placeholder="Enter new password"
            autoComplete="new-password"
            minLength={6}
            required
          />
        </div>
        <div>
          <label className="label">Confirm New Password *</label>
          <input
            type="password"
            className="input"
            value={confirmPassword}
            onChange={(e) => { setConfirmPassword(e.target.value); setError(''); }}
            placeholder="Re-enter new password"
            autoComplete="new-password"
            minLength={6}
            required
          />
        </div>

        <div className="flex justify-end gap-2 pt-4">
          <ActionButton type="button" variant="secondary" onClick={handleClose}>
            Cancel
          </ActionButton>
          <ActionButton
            type="submit"
            loading={changePasswordMutation.isPending}
            disabled={success || !oldPassword || !newPassword || !confirmPassword}
          >
            Change Password
          </ActionButton>
        </div>
      </form>
    </Modal>
  );
}
