import { useBoolean, useDebounceFn, useThrottleFn } from "ahooks";
import { Activity, use, useEffect } from "react";
import {
  type PanelSize,
  useDefaultLayout,
  useGroupRef,
  usePanelRef,
} from "react-resizable-panels";
import {
  ResizableHandle,
  ResizablePanel,
  ResizablePanelGroup,
} from "@/components/ui/resizable";
import { Skeleton } from "@/components/ui/skeleton";
import { useSidebarStore } from "@/stores/sidebar-store";
import { BackendReadyPromise } from "@/api";
import { activityVisible } from "@/lib/activity-visible";
import { ActivityBar } from "./ActivityBar";
import { SideBar } from "./SideBar";
import { Tabs } from "./Tabs";
import { TaskSessionViewSkeleton } from "./Tabs/TaskPanel/views/TaskSessionView";
import { SideBarListSkeleton } from "./SideBar/components/SideBarListSkeleton";
import { useScheduleNotificationListener } from "./sse-listeners/schedule-notification-listener";
import { GlobalShortcutsProvider } from "@/hooks/use-global-shortcuts";

function SideBarSkeleton() {
  return (
    <div className="h-full w-[320px] shrink-0 bg-layout-sidebar hidden sm:block">
      <div className="border-b p-3">
        <Skeleton className="h-8 w-full rounded-none" />
      </div>
      <div className="space-y-1 p-2">
        <SideBarListSkeleton />
      </div>
    </div>
  );
}

function TabsSkeleton() {
  return (
    <div className="flex h-full min-w-0 flex-1 flex-col bg-layout-tabs-content">
      <div className="flex h-10 items-center gap-2 border-b bg-layout-tabs-bar px-2">
        <Skeleton className="h-6 w-32 rounded-none" />
        <Skeleton className="h-6 w-28 rounded-none" />
        <Skeleton className="h-6 w-40 rounded-none" />
      </div>
      <div className="flex-1 p-4">
        <TaskSessionViewSkeleton />
      </div>
    </div>
  );
}

export function LayoutSkeleton() {
  return (
    <div className="flex h-full">
      {/* ActivityBarSkeleton */}
      <Skeleton className="w-12 h-full animate-none rounded-none" />

      <div className="flex h-full min-w-0 flex-1">
        <SideBarSkeleton />
        <div className="w-px bg-border" />
        <TabsSkeleton />
      </div>
    </div>
  );
}

// --- --- --- --- --- ---

export function Layout() {
  use(BackendReadyPromise);

  useScheduleNotificationListener();

  const { defaultLayout, onLayoutChanged } = useDefaultLayout({
    id: "panels",
    storage: localStorage,
  });
  const { isOpen, open: openSidebar, close: closeSidebar } = useSidebarStore();
  const [isResizing, { setTrue: resizeStart, setFalse: resizeEnd }] =
    useBoolean(false);
  const groupRef = useGroupRef();
  const sideBarPanelRef = usePanelRef();

  const { run: handleSideBarResize } = useThrottleFn(
    (panelSize: PanelSize, _: string | number | undefined) => {
      const isClosed = panelSize.asPercentage === 0;
      if (isClosed && isOpen) {
        closeSidebar();
      } else if (!(isClosed || isOpen)) {
        openSidebar();
      }
    },
    { wait: 100 },
  );

  const { run: handleTabsResize } = useDebounceFn(
    // use an extra resized handler to ensure the isResizing state is reset
    (_panelSize: PanelSize, _: string | number | undefined) => {
      resizeEnd();
    },
    { wait: 300 },
  );

  useEffect(() => {
    if (groupRef.current === null || sideBarPanelRef.current === null) {
      return;
    }

    const isCollapsed = sideBarPanelRef.current.isCollapsed();
    try {
      if (isOpen && isCollapsed) {
        sideBarPanelRef.current.expand();
      } else if (!(isOpen || isCollapsed)) {
        sideBarPanelRef.current.collapse();
      }
    } catch (e) {
      console.warn(e);
    }
  }, [isOpen]);

  return (
    <GlobalShortcutsProvider>
      <div className="flex h-full">
        <ActivityBar />
        <ResizablePanelGroup
          className="h-full"
          orientation="horizontal"
          groupRef={groupRef}
          onLayoutChange={resizeStart}
          onLayoutChanged={(layout) => {
            resizeEnd();
            onLayoutChanged(layout);
          }}
          defaultLayout={defaultLayout}
          data-is-resizing={isResizing || undefined}
          data-resizable-group
        >
          <ResizablePanel
            id="sidebar"
            collapsible
            minSize={300}
            maxSize={"60%"}
            panelRef={sideBarPanelRef}
            onResize={handleSideBarResize}
          >
            <SideBar />
          </ResizablePanel>
          <ResizableHandle />
          <ResizablePanel
            id="tabs"
            minSize={300}
            className="relative"
            onResize={handleTabsResize}
          >
            <Activity mode={activityVisible(isResizing)}>
              <div className="absolute inset-0 z-50 select-none" />
            </Activity>
            <Tabs />
          </ResizablePanel>
        </ResizablePanelGroup>
      </div>
    </GlobalShortcutsProvider>
  );
}
