import { useEffect, useRef } from "react";
import type { ContractOption } from "./ControlPanel";

interface ContractPickerModalProps {
  isOpen: boolean;
  onClose: () => void;
  contracts: ContractOption[];
  selectedContractId: string | null;
  onSelect: (contractId: string | null) => void;
  loading?: boolean;
}

export function ContractPickerModal({
  isOpen,
  onClose,
  contracts,
  selectedContractId,
  onSelect,
  loading,
}: ContractPickerModalProps) {
  const modalRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!isOpen) return;

    function handleKeyDown(e: KeyboardEvent) {
      if (e.key === "Escape") {
        onClose();
      }
    }

    function handleClickOutside(e: MouseEvent) {
      if (modalRef.current && !modalRef.current.contains(e.target as Node)) {
        onClose();
      }
    }

    document.addEventListener("keydown", handleKeyDown);
    document.addEventListener("mousedown", handleClickOutside);

    return () => {
      document.removeEventListener("keydown", handleKeyDown);
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  const handleSelect = (contractId: string | null) => {
    onSelect(contractId);
    onClose();
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60">
      <div
        ref={modalRef}
        className="panel p-4 w-[300px] max-h-[400px] flex flex-col gap-3"
      >
        <div className="flex items-center justify-between">
          <h2 className="font-mono text-sm text-[#dbe7ff] uppercase tracking-wide">
            Select Contract
          </h2>
          <button
            onClick={onClose}
            className="font-mono text-xs text-[#9bc3ff] hover:text-[#dbe7ff] transition-colors"
          >
            [X]
          </button>
        </div>

        <div className="flex-1 overflow-y-auto flex flex-col gap-1 min-h-0">
          {loading ? (
            <div className="font-mono text-xs text-[#9bc3ff] text-center py-4">
              Loading...
            </div>
          ) : (
            <>
              <button
                onClick={() => handleSelect(null)}
                className={`w-full text-left px-3 py-2 font-mono text-xs border transition-colors ${
                  selectedContractId === null
                    ? "bg-[#0f3c78]/50 border-[#3f6fb3] text-[#dbe7ff]"
                    : "bg-[#0d1b2d] border-[#0f3c78] text-[#9bc3ff] hover:border-[#3f6fb3] hover:text-[#dbe7ff]"
                }`}
              >
                <span className="uppercase tracking-wide">Ephemeral</span>
                <span className="block text-[10px] text-[#75aafc] mt-0.5">
                  Transcript not saved
                </span>
              </button>

              {contracts.map((contract) => (
                <button
                  key={contract.id}
                  onClick={() => handleSelect(contract.id)}
                  className={`w-full text-left px-3 py-2 font-mono text-xs border transition-colors ${
                    selectedContractId === contract.id
                      ? "bg-[#0f3c78]/50 border-[#3f6fb3] text-[#dbe7ff]"
                      : "bg-[#0d1b2d] border-[#0f3c78] text-[#9bc3ff] hover:border-[#3f6fb3] hover:text-[#dbe7ff]"
                  }`}
                >
                  <span className="block truncate">{contract.name}</span>
                </button>
              ))}

              {contracts.length === 0 && (
                <div className="font-mono text-xs text-[#9bc3ff] text-center py-4">
                  No contracts available
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}
