import React from 'react';
import {
  ActivityIndicator,
  ScrollView,
  StyleSheet,
  View,
  ViewStyle,
} from 'react-native';
import { useStyles, useTheme } from '../../hooks';
import { ComponentStyleProp, LLComponentStyleFn } from '../../types';
import { LLPickerEmptyComponent } from './LLPickerEmptyComponent';

export type LLBasePickerStyles = {
  pickerContainer: ViewStyle;
  pickerItemsScrollview: ViewStyle;
  pickerItemContainer: ViewStyle;
  pickerLoadingIndicator: ViewStyle;
};

export type BasePickerData = {
  id: string;
};

export type LLBasePickerProps<TItem extends BasePickerData> =
  ComponentStyleProp<LLBasePickerStyles> & {
    visible: boolean;
    loading?: boolean;
    packItems: TItem[];
    EmptyPickerComponent?: typeof LLPickerEmptyComponent;
    PickerItemComponent: ({ item }: { item: TItem }) => JSX.Element;
    PickerHeaderComponent?: () => JSX.Element;
  };

export function LLBasePicker<TItem extends BasePickerData>({
  visible,
  loading,
  packItems,
  styles: stylesProp,
  EmptyPickerComponent = LLPickerEmptyComponent,
  PickerItemComponent,
  PickerHeaderComponent,
}: LLBasePickerProps<TItem>) {
  const { theme } = useTheme();
  const pickerStyles = useStyles({
    componentStylesFn: getPickerStyles,
    stylesProp,
  });

  if (!visible) {
    return null;
  }

  return (
    <View style={pickerStyles.pickerContainer}>
      {PickerHeaderComponent && PickerHeaderComponent()}
      {loading ? (
        <ActivityIndicator
          size={'large'}
          color={theme.text}
          style={pickerStyles.pickerLoadingIndicator}
        />
      ) : (
        <ScrollView
          style={pickerStyles.pickerItemsScrollview}
          keyboardShouldPersistTaps={'always'}
        >
          <View style={pickerStyles.pickerItemContainer}>
            {!packItems || packItems.length === 0 ? (
              <EmptyPickerComponent />
            ) : (
              packItems.map((item) => (
                <PickerItemComponent key={item.id} item={item} />
              ))
            )}
          </View>
        </ScrollView>
      )}
    </View>
  );
}

const getPickerStyles: LLComponentStyleFn<LLBasePickerStyles> = ({ theme }) =>
  StyleSheet.create({
    pickerContainer: {
      minHeight: 300,
      maxHeight: 300,
      backgroundColor: theme.secondaryBackground,
    },
    pickerItemsScrollview: {
      paddingTop: 10,
    },
    pickerItemContainer: {
      position: 'relative',
      flexDirection: 'row',
      flexWrap: 'wrap',
      justifyContent: 'space-evenly',
    },
    pickerLoadingIndicator: {
      flex: 1,
    },
  });
