import { useState } from 'react';
import { DSP } from '../../types/types';
import Sidebar from '../../components/Sidebar/Sidebar';
import { InfoIcon, KnobGainIcon } from '../../assets/icons/AudioIcons';
import ConnectionPanel from '../../components/dsp408/ConnectionSection/ConnectionSection';
import GainSection from '../../components/dsp408/GainSection/GainSection';
import { DSP408Device } from '../../hooks/useDSP408';
import './DspPage.css';
import GateSection from '../../components/dsp408/GateSection/GateSection';
import LoadingOverlay from '../../components/LoadingOverlay/LoadingOverlay';
import { InputChannel, OutputChannel } from '../../types/dsp408State';

function DSPPage({
  dsp,
  dsp408,
}: {
  dsp: DSP;
  dsp408: DSP408Device;
}) {
  const [activeSidebar, setActiveSidebar] = useState('overview');
  const [sidebarExpanded, setSidebarExpanded] = useState(false);
  const [selectedPreset, setSelectedPreset] = useState(dsp.state?.presets.current_index ?? 0);
  const [presetLoading, setPresetLoading] = useState(false);
  const inputStates = dsp.state?.current_config.input_states;
  const outputStates = dsp.state?.current_config.output_states;
  const sidebarItems = [
    {
      id: 'overview',
      label: 'Overview',
      icon: <InfoIcon />,
    },
    {
      id: 'gain',
      label: 'Gain',
      icon: <KnobGainIcon />,
    },
    {
      id: 'gate',
      label: 'Gate',
      icon: <KnobGainIcon />,
    },
    {
      id: 'compressor',
      label: 'Compressor',
      icon: <KnobGainIcon />,
    },
    {
      id: 'limiter',
      label: 'Limiter',
      icon: <KnobGainIcon />,
    },
    {
      id: 'delay',
      label: 'Delay',
      icon: <KnobGainIcon />,
    },
    {
      id: 'matrix',
      label: 'Matrix',
      icon: <KnobGainIcon />,
    },
    {
      id: 'geq',
      label: 'Graphic Equalizer',
      icon: <KnobGainIcon />,
    },
    {
      id: 'ina',
      label: `In A (${inputStates?.[InputChannel.InA]?.name})`,
      icon: <KnobGainIcon />,
    },
    {
      id: 'inb',
      label: `In B (${inputStates?.[InputChannel.InB]?.name})`,
      icon: <KnobGainIcon />,
    },
    {
      id: 'inc',
      label: `In C (${inputStates?.[InputChannel.InC]?.name})`,
      icon: <KnobGainIcon />,
    },
    {
      id: 'ind',
      label: `In D (${inputStates?.[InputChannel.InD]?.name})`,
      icon: <KnobGainIcon />,
    },

    {
      id: 'out1',
      label: `Out 1 (${outputStates?.[OutputChannel.Out1]?.name})`,
      icon: <KnobGainIcon />,
    },
    {
      id: 'out2',
      label: `Out 2 (${outputStates?.[OutputChannel.Out2]?.name})`,
      icon: <KnobGainIcon />,
    },
    {
      id: 'out3',
      label: `Out 3 (${outputStates?.[OutputChannel.Out3]?.name})`,
      icon: <KnobGainIcon />,
    },
    {
      id: 'out4',
      label: `Out 4 (${outputStates?.[OutputChannel.Out4]?.name})`,
      icon: <KnobGainIcon />,
    },
    {
      id: 'out5',
      label: `Out 5 (${outputStates?.[OutputChannel.Out5]?.name})`,
      icon: <KnobGainIcon />,
    },
    {
      id: 'out6',
      label: `Out 6 (${outputStates?.[OutputChannel.Out6]?.name})`,
      icon: <KnobGainIcon />,
    },
    {
      id: 'out7',
      label: `Out 7 (${outputStates?.[OutputChannel.Out7]?.name})`,
      icon: <KnobGainIcon />,
    },
    {
      id: 'out8',
      label: `Out 8 (${outputStates?.[OutputChannel.Out8]?.name})`,
      icon: <KnobGainIcon />,
    },
    {
      id: 'miscellaneous',
      label: 'Miscellaneous',
      icon: <KnobGainIcon />,
    },
  ];
  const presets = dsp.state?.presets.names
    ? [
        {
          id: 'f00',
          name: 'Factory Preset',
        },
        ...dsp.state.presets.names.map((name, index) => ({
          id: `u${String(index + 1).padStart(2, '0')}`,
          name,
        })),
      ]
    : [
        {
          id: 'f00',
          name: 'Factory Preset',
        },
        ...Array.from({ length: 20 }, (_, index) => ({
          id: `u${String(index + 1).padStart(2, '0')}`,
          name: 'Default Preset',
        })),
      ];

  // const { recallPreset, setCurrentPresetName } = useDSPPresets(dsp, setDsps, notify);

  const onAppChange = async (id: string) => {
    const presetIndex = presets.findIndex((preset) => preset.id === id);
    if (presetIndex === -1) return;

    setPresetLoading(true);
    const success = await dsp408.recallPreset(presetIndex);
    if (success) {
      setSelectedPreset(presetIndex);
    }
    setPresetLoading(false);
  };

  const renderTab = () => {
    switch (activeSidebar) {
      case 'overview':
        return <ConnectionPanel dsp={dsp} onConnect={dsp408.connect} onDisconnect={dsp408.disconnect} />;

      // case 'gain':
      //   return <GainSection dsp={dsp} notify={notify} />;

      // case 'gate':
      //   return <GateSection dsp={dsp} notify={notify} />;

      default:
        return null;
    }
  };

  return (
    <div className={`app-root ${sidebarExpanded ? 'app-root--sidebar-expanded' : ''}`}>
      <Sidebar
        items={sidebarItems}
        activeId={activeSidebar}
        onSelect={setActiveSidebar}
        appName={dsp.name}
        appOptions={presets}
        selectedAppId={presets[selectedPreset]?.id}
        onAppChange={onAppChange}
        onAppRename={dsp408.setCurrentPresetName}
        expanded={sidebarExpanded}
        onToggle={() => setSidebarExpanded((v) => !v)}
      />

      <LoadingOverlay
        active={presetLoading}
        label="Recalling preset…"
        overlayClassName="dsp-loading-overlay"
      >
        <div className="dsp-content">{renderTab()}</div>
      </LoadingOverlay>
    </div>
  );
}

export default DSPPage;
