import { useState } from 'react';
import { AppModal } from './AppModal';
import { useConnection } from '../../context/ConnectionContext';

/** Popup over the Account modal: old / new / confirm, server-verified. */
export function ChangePasswordModal({ onClose }) {
  const { changePassword } = useConnection();
  const [oldPassword, setOldPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirm, setConfirm] = useState('');
  const [error, setError] = useState(null);
  const [busy, setBusy] = useState(false);

  const submit = async () => {
    if (busy) return;
    if (!newPassword) {
      setError('Enter a new password.');
      return;
    }
    if (newPassword !== confirm) {
      setError('New passwords do not match.');
      return;
    }
    setBusy(true);
    setError(null);
    const result = await changePassword(oldPassword, newPassword);
    setBusy(false);
    if (result.ok) onClose(true);
    else setError(result.error);
  };

  const field = (value, setter, placeholder, autoFocus = false) => (
    <input
      type="password"
      className="connection-field"
      value={value}
      placeholder={placeholder}
      autoFocus={autoFocus}
      onChange={(e) => {
        setter(e.target.value);
        setError(null);
      }}
    />
  );

  return (
    <AppModal title="Change Password" icon="assets/account.svg" onClose={() => onClose(false)}>
      <div
        className="login-form"
        onKeyDown={(e) => {
          if (e.key === 'Enter') {
            e.preventDefault();
            submit();
          }
        }}
      >
        {field(oldPassword, setOldPassword, 'Current password', true)}
        {field(newPassword, setNewPassword, 'New password')}
        {field(confirm, setConfirm, 'Confirm new password')}
        {error && <p className="connection-card-error connection-card-error--flush">{error}</p>}
        <button
          type="button"
          className="connection-action connection-action--login"
          disabled={busy}
          onClick={submit}
        >
          {busy ? 'Changing…' : 'Change Password'}
        </button>
      </div>
    </AppModal>
  );
}
