import { useMemo, useState } from 'react';
import { FormProvider } from 'react-hook-form';
import { MemoryRouter } from 'react-router-dom';

import useHuPagination from '@hooks/useHuPagination';
import Stack from '@mui/material/Stack';
import { type Meta, type StoryObj } from '@storybook/react-vite';

import { SidebarWrapper } from './components/SidebarWrapper';
import {
  articleModelMock,
  defaultCapabilitiesMock,
  rootModelMock,
} from './mock';
import { type LibrariesTreeItem, type SortedItem } from './types';
import { type SidebarModel } from './types/model';
import LibrariesSidebar, { type LibrariesSidebarProps } from '.';

const meta: Meta<typeof LibrariesSidebar> = {
  component: LibrariesSidebar,
  parameters: { layout: 'fullscreen' },
  title: 'Composed Components/LibrariesSidebar',
  tags: ['autodocs'],
  args: {
    model: rootModelMock,
    capabilities: defaultCapabilitiesMock,
    onBack: () => console.log('onBack'),
    onSort: payload => console.log('onSort', payload),
    onAdd: () => console.log('onAdd'),
  },
  decorators: [
    Story => (
      <MemoryRouter>
        <Stack
          sx={{
            width: '100%',
            minHeight: '100vh',
            maxWidth: 'min-content',
            mx: 'auto',
          }}
        >
          <Story />
        </Stack>
      </MemoryRouter>
    ),
  ],
};

export default meta;

type Story = StoryObj<typeof LibrariesSidebar>;

const Template = (args: LibrariesSidebarProps) => {
  const { Search, form } = useHuPagination();
  const search = form.watch('params.search') ?? '';

  const [selected, setSelected] = useState<{
    parentId: number | undefined;
    model: SidebarModel;
  }>({ parentId: undefined, model: args.model });

  const baseModel = selected.parentId ? articleModelMock : args.model;

  const filteredModel = useMemo(() => {
    if (!search.trim()) return baseModel;
    const query = search.toLowerCase();
    return {
      ...baseModel,
      nodes: baseModel.nodes.filter(node =>
        node.title.toLowerCase().includes(query),
      ),
    };
  }, [search, baseModel]);

  const handleItemClick = (item: LibrariesTreeItem) => {
    const isRoot = !item.parentId;

    if (isRoot) {
      setSelected({
        parentId: item.id,
        model: { ...articleModelMock, headerTitle: item.title },
      });
    } else {
      console.log('onChildItemClick', item);
    }
  };

  const handleBack = () =>
    setSelected({ parentId: undefined, model: args.model });

  const handleSort = (sortedItems: SortedItem[]) => {
    console.log('handleOnSort', sortedItems);
  };

  return (
    <FormProvider {...form}>
      <SidebarWrapper>
        <Stack sx={{ px: 1, py: 1, backgroundColor: 'white' }}>
          <Search inputProps={{ variant: 'custom' }} />
        </Stack>
        <LibrariesSidebar
          {...args}
          model={filteredModel}
          parentId={selected.parentId}
          onBack={handleBack}
          onSort={handleSort}
          onItemClick={handleItemClick}
        />
      </SidebarWrapper>
    </FormProvider>
  );
};

export const Default: Story = {
  render: args => <Template {...args} />,
};

export const Empty: Story = {
  args: { model: { headerTitle: '', nodes: [] } },
  render: args => <Template {...args} />,
};

export const Loading: Story = {
  args: { loading: true },
  render: args => <Template {...args} />,
};
