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 { NotificationType } from '../../types/types';
import './DspPage.css';
import GateSection from '../../components/dsp408/GateSection/GateSection';
import { invoke } from '@tauri-apps/api/core';
import LoadingOverlay from '../../components/LoadingOverlay/LoadingOverlay';

function DSPPage({
  dsp,
  onConnect,
  onDisconnect,
  notify,
}: {
  dsp: DSP;
  onConnect: () => void;
  onDisconnect: () => void;
  notify: (message: string, type?: NotificationType, dspName?: string) => void;
}) {
  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 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',
      icon: <KnobGainIcon />,
    },
    {
      id: 'inb',
      label: 'In B',
      icon: <KnobGainIcon />,
    },
    {
      id: 'inc',
      label: 'In C',
      icon: <KnobGainIcon />,
    },
    {
      id: 'ind',
      label: 'In D (TESTTEST)',
      icon: <KnobGainIcon />,
    },
    {
      id: 'out1',
      label: 'Out 1',
      icon: <KnobGainIcon />,
    },
    {
      id: 'out2',
      label: 'Out 2',
      icon: <KnobGainIcon />,
    },
    {
      id: 'out3',
      label: 'Out 3',
      icon: <KnobGainIcon />,
    },
    {
      id: 'out4',
      label: 'Out 4',
      icon: <KnobGainIcon />,
    },
    {
      id: 'out5',
      label: 'Out 5',
      icon: <KnobGainIcon />,
    },
    {
      id: 'out6',
      label: 'Out 6',
      icon: <KnobGainIcon />,
    },
    {
      id: 'out7',
      label: 'Out 7',
      icon: <KnobGainIcon />,
    },
    {
      id: 'out8',
      label: 'Out 8',
      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 = async (presetIndex: number) => {
    try {
      const success = await invoke<boolean>('recall_preset', {
        id: dsp.id,
        presetIndex,
      });

      if (success) {
        notify(`Preset ${presetIndex} recalled`, 'success', dsp.name);
      } else {
        notify('Failed to recall preset', 'error', dsp.name);
      }

      return success;
    } catch (err) {
      notify(`Preset recall failed: ${String(err)}`, 'error', dsp.name);
      return false;
    }
  };

  const setCurrentPresetName = async (name: string) => {
    try {
      const success = await invoke<boolean>('set_current_preset_name', {
        id: dsp.id,
        name,
      });

      if (success) {
        notify(`Preset renamed`, 'success', dsp.name);
      } else {
        notify('Failed to rename preset', 'error', dsp.name);
      }

      return success;
    } catch (err) {
      notify(`Preset rename failed: ${String(err)}`, 'error', dsp.name);
      return false;
    }
  };

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

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

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

      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={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;
