import { Construction } from 'lucide-react';
import { usePanelChannel } from 'hooks/usePanelChannel';
import { useDashboardState } from 'state/useDashboardState';
import { SOULSEEK_SECTION_CHANNEL, SOULSEEK_SECTIONS, soulseekZoomKey, type SoulseekSectionId } from './shared';
import { SearchView } from './SearchView';
import { SoulseekTransfers } from './SoulseekTransfers';
import { SoulseekUploads } from './SoulseekUploads';
import { SoulseekRooms } from './SoulseekRooms';
import { SoulseekDashboard } from './SoulseekDashboard';
import { SoulseekChat } from './SoulseekChat';
import { SoulseekUsers } from './SoulseekUsers';
import { SoulseekSystem } from './SoulseekSystem';

// Right panel of the /soulseek workspace — renders the UI for the section the nav selected. The panel
// header's +/- controls set a per-panel zoom factor, persisted via useDashboardState (same store as the
// layout config); we read it here and apply it as a CSS scale, with a compensating width/height so the
// scaled content still fills the panel and inner scroll keeps working.

const Placeholder = ({ id }: { id: SoulseekSectionId }) => {
  const label = SOULSEEK_SECTIONS.find((s) => s.id === id)?.label ?? id;
  return (
    <div className="flex h-full flex-col items-center justify-center gap-3 text-center">
      <div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-muted text-muted-foreground">
        <Construction className="h-6 w-6" />
      </div>
      <div>
        <div className="text-base font-semibold">{label}</div>
        <div className="text-sm text-muted-foreground">Coming soon</div>
      </div>
    </div>
  );
};

const sectionView = (section: SoulseekSectionId) => {
  switch (section) {
    case 'dashboard':
      return <SoulseekDashboard />;
    case 'search':
      return <SearchView />;
    case 'downloads':
      return <SoulseekTransfers />;
    case 'uploads':
      return <SoulseekUploads />;
    case 'rooms':
      return <SoulseekRooms />;
    case 'chat':
      return <SoulseekChat />;
    case 'users':
      return <SoulseekUsers />;
    case 'system':
      return <SoulseekSystem />;
    default:
      return <Placeholder id={section} />;
  }
};

type SoulseekViewProps = { panelId: string };

export const SoulseekView = ({ panelId }: SoulseekViewProps) => {
  const [section] = usePanelChannel<SoulseekSectionId>(SOULSEEK_SECTION_CHANNEL, 'dashboard');
  const { value: zoom } = useDashboardState<number>(soulseekZoomKey(panelId), 1);
  const z = zoom ?? 1;

  if (z === 1) return <div className="h-full w-full">{sectionView(section)}</div>;

  // transform: scale doesn't reflow, so size the box to 1/z and let the scale bring it back to 100%.
  const inv = `${100 / z}%`;
  return (
    <div className="h-full w-full overflow-hidden">
      <div style={{ width: inv, height: inv, transform: `scale(${z})`, transformOrigin: 'top left' }}>
        {sectionView(section)}
      </div>
    </div>
  );
};
