import { useState } from "react";
import { Logo } from "../Logo";
import type { MicrophoneStatus } from "../../hooks/useMicrophone";
import type { ConnectionStatus } from "../../hooks/useWebSocket";
import { ContractPickerModal } from "./ContractPickerModal";

export interface ContractOption {
  id: string;
  name: string;
}

interface ControlPanelProps {
  isListening: boolean;
  isConnected: boolean;
  micStatus: MicrophoneStatus;
  micVolume: number;
  hasTranscripts: boolean;
  onToggle: () => void;
  onNew: () => void;
  error?: string | null;
  // Contract selection
  contracts: ContractOption[];
  selectedContractId: string | null;
  onContractChange: (contractId: string | null) => void;
  contractsLoading?: boolean;
  // Connection status for loading state
  connectionStatus?: ConnectionStatus;
}

function getStatusText(isListening: boolean, micStatus: MicrophoneStatus): string {
  if (isListening) return "Listening...";

  switch (micStatus) {
    case "requesting":
      return "Requesting permission...";
    case "ready":
      return "Click to start";
    case "denied":
      return "Permission denied - click to retry";
    case "error":
      return "Error - click to retry";
    default:
      return "Click to start";
  }
}

export function ControlPanel({
  isListening,
  isConnected,
  micStatus,
  micVolume,
  hasTranscripts,
  onToggle,
  onNew,
  error,
  contracts,
  selectedContractId,
  onContractChange,
  contractsLoading,
  connectionStatus,
}: ControlPanelProps) {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const statusText = getStatusText(isListening, micStatus);
  const isRequesting = micStatus === "requesting";

  const selectedContract = contracts.find((c) => c.id === selectedContractId);

  return (
    <div className="panel p-4 flex flex-col items-center justify-center gap-3">
      {/* Logo button */}
      <div className="flex flex-col items-center gap-2">
        <Logo
          size={100}
          listening={isListening || isRequesting}
          onClick={isRequesting ? undefined : onToggle}
          className={isRequesting ? "opacity-50" : "cursor-pointer"}
          noHoverAnimation
        />
        <span className="font-mono text-xs text-[#9bc3ff] tracking-wide uppercase text-center">
          {statusText}
        </span>
      </div>

      {/* Status indicators */}
      <div className="font-mono text-xs text-center flex flex-col gap-1">
        {/* Microphone status */}
        <div
          className={`inline-flex flex-col gap-1 px-2 py-1 border ${
            micStatus === "ready" || micStatus === "recording"
              ? "border-[#3f6fb3] text-[#75aafc]"
              : micStatus === "denied" || micStatus === "error"
              ? "border-red-400/50 text-red-400"
              : "border-[rgba(117,170,252,0.25)] text-[#9bc3ff]"
          }`}
        >
          <div className="inline-flex items-center gap-1.5">
            <span
              className={`w-1.5 h-1.5 rounded-full ${
                micStatus === "ready" || micStatus === "recording"
                  ? "bg-[#75aafc]"
                  : micStatus === "denied" || micStatus === "error"
                  ? "bg-red-400"
                  : "bg-[#3f6fb3]"
              }`}
            />
            {micStatus === "ready" || micStatus === "recording"
              ? "MIC READY"
              : micStatus === "requesting"
              ? "REQUESTING..."
              : micStatus === "denied"
              ? "MIC DENIED"
              : micStatus === "error"
              ? "MIC ERROR"
              : "MIC IDLE"}
          </div>
          {isListening && (
            <div className="w-full h-1.5 bg-[#0f1c2f] overflow-hidden">
              <div
                className="h-full bg-[#75aafc] transition-all duration-75"
                style={{ width: `${micVolume * 100}%` }}
              />
            </div>
          )}
        </div>

        {/* Connection status */}
        <div
          className={`inline-flex flex-col gap-1 px-2 py-1 border ${
            isConnected
              ? "border-[#3f6fb3] text-[#75aafc]"
              : connectionStatus === "connecting"
              ? "border-[#3f6fb3] text-[#9bc3ff]"
              : "border-[rgba(117,170,252,0.25)] text-[#9bc3ff]"
          }`}
        >
          <div className="inline-flex items-center gap-1.5">
            <span
              className={`w-1.5 h-1.5 rounded-full ${
                isConnected ? "bg-[#75aafc]" : "bg-[#3f6fb3]"
              }`}
            />
            {isConnected
              ? "CONNECTED"
              : connectionStatus === "connecting"
              ? "LOADING MODELS..."
              : "DISCONNECTED"}
          </div>
          {connectionStatus === "connecting" && (
            <div className="w-full h-1.5 bg-[#0f1c2f] overflow-hidden">
              <div
                className="h-full w-1/3 bg-[#75aafc]"
                style={{
                  animation: "loading-slide 1.5s ease-in-out infinite",
                }}
              />
            </div>
          )}
        </div>
      </div>

      {/* Error display */}
      {error && (
        <div className="font-mono text-xs text-red-400 text-center px-2 py-1 border border-red-400/50 bg-red-400/10 max-w-[250px]">
          {error}
        </div>
      )}

      {/* Buttons */}
      <div className="flex gap-2">
        <button
          onClick={onNew}
          className="px-3 py-1.5 font-mono text-xs text-[#dbe7ff] bg-[#0d1b2d] border border-[#0f3c78] hover:border-[#3f6fb3] transition-colors uppercase tracking-wide"
          title={hasTranscripts ? "Save and start new session" : "Start new session"}
        >
          New
        </button>
        <button
          onClick={() => setIsModalOpen(true)}
          disabled={isListening || contractsLoading}
          className="px-3 py-1.5 font-mono text-xs text-[#dbe7ff] bg-[#0d1b2d] border border-[#0f3c78] hover:border-[#3f6fb3] transition-colors disabled:opacity-50 disabled:cursor-not-allowed uppercase tracking-wide"
          title={selectedContract ? `Saving to: ${selectedContract.name}` : "Transcript not saved"}
        >
          {selectedContract ? "Contract" : "Ephemeral"}
        </button>
      </div>

      <ContractPickerModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        contracts={contracts}
        selectedContractId={selectedContractId}
        onSelect={onContractChange}
        loading={contractsLoading}
      />
    </div>
  );
}
