import { Modal, Badge, MonoText } from '@cameleer/design-system';
import { Check } from 'lucide-react';
import type { Environment } from '../api/queries/admin/environments';
import { envColorVar } from './env-colors';
import styles from './EnvironmentSwitcherModal.module.css';

interface EnvironmentSwitcherModalProps {
  open: boolean;
  onClose: () => void;
  envs: Environment[];
  value: string | undefined;
  onPick: (slug: string) => void;
  /** When true, ESC/backdrop do nothing — the user must pick one. */
  forced?: boolean;
}

export function EnvironmentSwitcherModal({
  open,
  onClose,
  envs,
  value,
  onPick,
  forced = false,
}: EnvironmentSwitcherModalProps) {
  const title = forced ? 'Select an environment' : 'Switch environment';
  const handleClose = forced ? () => { /* locked */ } : onClose;

  return (
    <Modal open={open} onClose={handleClose} title={title} size="sm">
      {envs.length === 0 ? (
        <div className={styles.empty}>
          No environments — ask an admin to create one.
        </div>
      ) : (
        <ul className={styles.list} role="listbox" aria-label="Environments">
          {envs.map((env) => {
            const selected = env.slug === value;
            return (
              <li key={env.id}>
                <button
                  type="button"
                  className={`${styles.row} ${selected ? styles.rowSelected : ''}`}
                  onClick={() => onPick(env.slug)}
                  aria-selected={selected}
                  role="option"
                >
                  <span className={styles.dot} style={{ background: envColorVar(env.color) }} aria-hidden />
                  <div className={styles.labels}>
                    <div className={styles.name}>{env.displayName}</div>
                    <MonoText size="xs" className={styles.slug}>{env.slug}</MonoText>
                  </div>
                  <div className={styles.badges}>
                    {env.production && <Badge label="PROD" color="error" />}
                    {!env.production && <Badge label="NON-PROD" color="auto" />}
                    {!env.enabled && <Badge label="DISABLED" color="warning" />}
                  </div>
                  {selected && <Check size={16} className={styles.check} aria-label="current" />}
                </button>
              </li>
            );
          })}
        </ul>
      )}
    </Modal>
  );
}
