import { useState } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import 'react-perfect-scrollbar/dist/css/styles.css';

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

import { mockDataParser, useMockUsersQueryForAutocomplete } from './mocks';
import { type UserAutoCompleteProps } from './types';
import UserAutoComplete from './index';

type StoryComponentArgs = Omit<
  UserAutoCompleteProps,
  'usersQuery' | 'usersQueryDataParser'
> & { empty?: boolean };

const UserAutoCompleteWithMockQuery = ({
  empty,
  ...rest
}: StoryComponentArgs) => {
  const [search, setSearch] = useState('');
  const [selectedUserIds, setSelectedUserIds] = useState(rest.value);
  const usersQuery = useMockUsersQueryForAutocomplete(search, empty);

  return (
    <>
      <UserAutoComplete
        {...rest}
        usersQuery={usersQuery}
        usersQueryDataParser={mockDataParser}
        value={selectedUserIds}
        searchValue={search}
        onSearch={setSearch}
        onChange={setSelectedUserIds}
      />
    </>
  );
};

const meta: Meta<typeof UserAutoCompleteWithMockQuery> = {
  component: UserAutoCompleteWithMockQuery,
  title: 'Composed Components/Inputs/UserAutoComplete',
  tags: ['autodocs'],
  decorators: [
    Story => {
      const queryClient = new QueryClient({
        defaultOptions: {
          queries: {
            retry: false,
          },
        },
      });

      return (
        <QueryClientProvider client={queryClient}>
          <Box sx={{ height: '500px', width: '100%' }}>
            <Story />
          </Box>
        </QueryClientProvider>
      );
    },
  ],
  args: {
    selectionLimit: 3,
    value: new Set([1, 3]),
    slotProps: {
      search: {
        placeholder: 'Buscar usuario',
      },
      emptyStateCard: {
        title: 'No hay usuarios disponibles',
        description:
          'No se encontraron usuarios que coincidan con los criterios de búsqueda',
      },
      userAvatar: {
        profileProps: {
          showEmail: true,
        },
      },
    },
  },
};

export default meta;

type Story = StoryObj<typeof UserAutoCompleteWithMockQuery>;

export const Default: Story = {};

export const Empty: Story = {
  args: {
    empty: true,
  },
};
