import React, { useEffect, useRef } from 'react';
import { Animated } from 'react-native';
import { CardContainer } from '../CardContainer';
import { AlternativeItem } from './AlternativeItem';
import { BasicItem } from './BasicItem';
import { CustomItem } from './CustomItem';
import { Group } from './Group';
import { ProductItem } from './Product';
import { WrapperItem } from './WrapperItem';
import type { SkeletonType } from './skeleton';
import { ProductCart } from './ProductCart';
import { AutoComplete } from './AutoComplete';
import { SearchResult } from './SearchResult';
import { OrderCard } from './OrderCard';

export const Skeleton = ({
  type,
  withCardContainer = true,
  withFooter = false,
  style = {},
  nItems,
  children,
  ...rest
}: SkeletonType) => {
  const opacity = useRef(new Animated.Value(0.2));

  useEffect(() => {
    Animated.loop(
      Animated.sequence([
        Animated.timing(opacity.current, {
          toValue: 1,
          useNativeDriver: true,
          duration: 500,
        }),
        Animated.timing(opacity.current, {
          toValue: 0.2,
          useNativeDriver: true,
          duration: 800,
        }),
      ])
    ).start();
  }, [opacity]);

  const skeleton = () => {
    const listSkeletons = {
      CardBasicItem: (
        <BasicItem opacity={opacity.current} withFooter={withFooter} />
      ),
      CardGroup: <Group opacity={opacity.current} nItems={nItems} />,
      CardAlternativeItem: <AlternativeItem opacity={opacity.current} />,
      ProductItem: <ProductItem opacity={opacity.current} />,
      ProductCart: <ProductCart opacity={opacity.current} />,
      WrapperItem: (
        <WrapperItem
          opacity={opacity.current}
          style={style}
          children={children}
        />
      ),
      AutoComplete: <AutoComplete opacity={opacity.current} nItems={nItems} />,
      SearchResult: <SearchResult opacity={opacity.current} nItems={nItems} />,
      OrderCard: <OrderCard opacity={opacity.current} nItems={nItems} />,
    };

    if (type && listSkeletons?.[type]) {
      return listSkeletons[type];
    }

    return <CustomItem opacity={opacity.current} style={style} />;
  };

  if (withCardContainer) {
    return (
      <CardContainer alignItems="flex-start" {...rest}>
        {skeleton()}
      </CardContainer>
    );
  }

  return skeleton();
};
