/* eslint-disable react-hooks/rules-of-hooks */
import React, {useEffect, useState} from 'react';
import {StyleSheet, View} from 'react-native';
import {Meta, StoryObj} from '@storybook/react';
import {IconUser} from '@tabler/icons-react-native';
import {ListItem} from '@components/_HuGo/List';
import {Typography} from '@components/_core/Typography';
import {Section} from '@interfaces/section';
import {SPACING, useTheme} from '@shared/theme';

import {SectionList} from './index';

interface SectionListItemMock {
  id: number;
  title: string;
}

type SectionListMock = Section<SectionListItemMock>[];

const SECTION_LIST_MOCK: SectionListMock = ['A', 'B', 'C'].map(section => ({
  title: section,
  data: Array.from({length: 10}, (_, index) => ({
    id: index + 1,
    title: `Item nro ${index + 1}`,
  })),
}));

const ITEM_PER_PAGE = 10;

const styles = StyleSheet.create({
  decorator: {margin: -SPACING.x2},
  list: {paddingVertical: SPACING.x2, paddingBottom: SPACING.x2},
});

const getList = (offset = ITEM_PER_PAGE) => {
  return new Promise<SectionListMock>(res => {
    setTimeout(() => {
      res(SECTION_LIST_MOCK.slice(0, offset));
    }, 1000);
  });
};

const meta: Meta = {
  title: 'Custom/SectionList',
};

export const SectionListComponent: StoryObj = {
  argTypes: {},
  args: {},
  decorators: Story => (
    <View style={styles.decorator}>
      <Story />
    </View>
  ),
  render: () => {
    const {theme, spacing} = useTheme();
    const [isLoading, setIsLoading] = useState(true);
    const [isRefreshing, setIsRefreshing] = useState(false);
    const [data, setData] = useState<SectionListMock>();
    const [offset, setOffset] = useState(ITEM_PER_PAGE);

    const onNextPage = async () => {
      const nextOffset = offset + ITEM_PER_PAGE;
      const response = await getList(nextOffset);
      setData(response);
      setOffset(nextOffset);
    };

    const onRefresh = async () => {
      setIsRefreshing(true);
      const response = await getList(offset);
      setData(response);
      setIsRefreshing(false);
    };

    useEffect(() => {
      getList().then(response => {
        setIsLoading(false);
        setData(response);
      });
    }, []);

    return (
      <SectionList
        sections={data ?? []}
        withDivider
        isLoading={isLoading}
        isRefreshing={isRefreshing}
        hasNextPage={offset < SECTION_LIST_MOCK.length}
        onNextPage={onNextPage}
        onRefresh={onRefresh}
        renderItem={({item, index}) => (
          <ListItem
            title={item.title}
            avatar={{Icon: IconUser}}
            isFirstItem={index === 0}
            isLastItem={index === data!.length - 1}
          />
        )}
        renderSectionHeader={({section: {title}}) => (
          <View
            style={{
              backgroundColor: theme.neutralBgTrans,
              padding: spacing.x2,
            }}>
            <Typography weight="semiBold">{title}</Typography>
          </View>
        )}
        style={styles.list}
      />
    );
  },
};

export default meta;
