import { create } from "zustand";
import { persist } from "zustand/middleware";
import type { SidebarSectionId } from "@/components/sidebar/types";

interface SidebarState {
  open: boolean;
  width: number;
  collapsedSections: Record<SidebarSectionId, boolean>;
  trashConfirm: boolean;
  viewMode: "section" | "filesystem";
  setOpen: (open: boolean) => void;
  setWidth: (width: number) => void;
  toggleSection: (section: SidebarSectionId) => void;
  setSectionCollapsed: (section: SidebarSectionId, collapsed: boolean) => void;
  setTrashConfirm: (value: boolean) => void;
  setViewMode: (mode: SidebarState["viewMode"]) => void;
  setCollapsedSections: (collapsed: Record<SidebarSectionId, boolean>) => void;
}

const sectionDefaults: Record<SidebarSectionId, boolean> = {
  starred: true,
  public: true,
  shared: true,
  private: false,
  templates: true,
};

export const useSidebarStore = create<SidebarState>()(
  persist(
    (set) => ({
      open: false,
      width: 280,
      collapsedSections: { ...sectionDefaults },
      trashConfirm: true,
      viewMode: "section",
      setOpen: (open) => set({ open }),
      setWidth: (width) => set({ width }),
      toggleSection: (section) =>
        set((state) => ({
          collapsedSections: {
            ...state.collapsedSections,
            [section]: !state.collapsedSections[section],
          },
        })),
      setSectionCollapsed: (section, collapsed) =>
        set((state) => ({
          collapsedSections: {
            ...state.collapsedSections,
            [section]: collapsed,
          },
        })),
      setTrashConfirm: (value) => set({ trashConfirm: value }),
      setViewMode: (mode) => set({ viewMode: mode }),
      setCollapsedSections: (collapsed) => set({ collapsedSections: collapsed }),
    }),
    {
      name: "sidebar-ui",
      version: 4,
      skipHydration: true,
      migrate: (persistedState, version) => {
        const state = persistedState as
          | Partial<
              Pick<
                SidebarState,
                "width" | "collapsedSections" | "trashConfirm" | "viewMode"
              >
            >
          | undefined;
        if (!state) return state;
        if (version >= 4) return state;

        const nextCollapsedSections = {
          ...sectionDefaults,
          ...(state.collapsedSections ?? {}),
        };

        return {
          ...state,
          collapsedSections: nextCollapsedSections,
        };
      },
      partialize: (state) => ({
        width: state.width,
        collapsedSections: state.collapsedSections,
        trashConfirm: state.trashConfirm,
        viewMode: state.viewMode,
      }),
    },
  ),
);
