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

/**
 * Shown at login when the account is already at its device limit. Instead of a
 * dead-end error, the user gets a scrollable list of their registered devices
 * and can remove one to free a slot — a removed device's checked-out files are
 * force-checked-in server-side. "Done" enables once there's room and finishes
 * the login (registering this device).
 */
export function DeviceLimitModal() {
  const { deviceLimit, removeLimitDevice, finishDeviceLogin, cancelDeviceLogin } = useConnection();
  const [busy, setBusy] = useState(false);

  if (!deviceLimit) return null;
  const { devices, maxDevices } = deviceLimit;
  const canFinish = devices.length < maxDevices && !busy;

  const remove = async (id) => {
    setBusy(true);
    await removeLimitDevice(id);
    setBusy(false);
  };

  const done = async () => {
    setBusy(true);
    await finishDeviceLogin(); // clears deviceLimit on success
    setBusy(false);
  };

  return (
    <AppModal title="Device limit reached" icon="assets/account.svg" onClose={cancelDeviceLogin}>
      <p className="device-modal-intro">
        Your account is signed in on the maximum of {maxDevices} device
        {maxDevices === 1 ? '' : 's'}. Remove one to make room for this device, then
        click Done. Anything a removed device had checked out is automatically
        checked back in.
      </p>
      <ul className="device-line-list">
        {devices.map((device) => (
          <DeviceLine key={device.deviceId} device={device} onRemove={() => remove(device.deviceId)} busy={busy} />
        ))}
        {!devices.length && <li className="device-line-empty">No devices to remove.</li>}
      </ul>
      <div className="device-modal-actions">
        <button
          type="button"
          className="revision-pill-btn revision-pill-btn--primary"
          onClick={done}
          disabled={!canFinish}
          title={canFinish ? undefined : `Remove a device to get below ${maxDevices}.`}
        >
          Done
        </button>
      </div>
    </AppModal>
  );
}

export function DeviceLine({ device, onRemove, busy }) {
  const count = device.filesCheckedOut;
  return (
    <li className="device-line">
      <div className="device-line-main">
        <span className="device-line-name">{device.name}</span>
        <span className="device-line-host">{device.hostname}</span>
      </div>
      <span className={`device-line-checkouts${count ? ' device-line-checkouts--active' : ''}`}>
        {count ? `${count} file${count === 1 ? '' : 's'} checked out` : 'No files checked out'}
      </span>
      <button
        type="button"
        className="device-line-remove"
        aria-label={`Remove ${device.name}`}
        title={`Remove ${device.name}`}
        onClick={onRemove}
        disabled={busy}
      >
        <img src="assets/close.svg" alt="" />
      </button>
    </li>
  );
}
