import { StackScreenProps } from '@react-navigation/stack';
import * as React from 'react';
import * as Animatable from 'react-native-animatable';
import { Div, Button, Image, Text, Avatar, Icon } from 'react-native-magnus';
import { FlatList } from 'react-native-gesture-handler';
import { RefreshControl } from 'react-native';

import { useTranslation } from 'react-i18next';
import { useRequest } from 'ahooks';

import { FinancialType } from '../utils/MoneyUtils';

import { MonthDate, getSearchDate } from '../utils/TimeUtils';
import request from '../utils/RequestUtils';
import ReacordCom from './ReacordCom';

import { PopoverPicker } from '../utils/SystemUtils';

// import { PopoverPicker } from 'teaset';

interface Result {
  list: Item[];
  last: boolean;
  current: number;
}

export default function MineRecordScreen({ navigation }: StackScreenProps) {
  const { t } = useTranslation();
  const [type, settype] = React.useState<string>('all');

  const [show, setshow] = React.useState<boolean>(false);

  const monthDate = new MonthDate();
  const [showDate, setshowDate] = React.useState<string>(monthDate.showList[0]);
  const [layout, setLayout] = React.useState<any>();
  const { data, loading, loadMore, loadingMore, reload } = useRequest(
    (d: Result | undefined) => {
      let current = 0;
      if (d && d.current) {
        current = Number(d.current) + 1;
      }
      return request.get(__DEV__ ? '/moneyRecord/all' : '/moneyRecord/my', {
        params: {
          query: {
            time: getSearchDate(showDate),
            type: type != 'all' ? type : '',
          },
          size: 10,
          page: current,
        },
      });
    },
    {
      refreshDeps: [showDate, type],
      formatResult: (response) => {
        return {
          list: response.content,
          current: response.number.toString(),
          last: response.last,
          empty: response.empty,
        };
      },
      isNoMore: (r: Result) => {
        if (r.last) {
          return true;
        } else {
          return false;
        }
      },
      defaultLoading: false,
      debounceInterval: 1000,
      loadMore: true,
    }
  );

  navigation.setOptions({
    headerTitle: () => {
      let name = t('wo-de-dui-zhang-dan');
      if (type !== 'all') {
        name += '(' + t(FinancialType.get(type).name) + ')';
      }
      return (
        <Button bg="yellow500" onPress={() => setshow(!show)}>
          {name}
        </Button>
      );
    },
  });

  return (
    <Div bg="gray100" flex={1}>
      {show && (
        <Div
          position="absolute"
          bg="black600"
          top={0}
          left={0}
          right={0}
          bottom={0}
          zIndex={2}
        >
          <Animatable.View animation="slideInDown" duration={300}>
            <Div bg="white">
              {[...FinancialType.keys()].map((item, index) => {
                const info = FinancialType.get(item);
                return (
                  <Button
                    bg="white"
                    block
                    key={index}
                    onPress={() => {
                      settype(item);
                      setshow(false);
                    }}
                  >
                    <Div row flex={1} alignItems="center">
                      <Icon
                        name={info.icon}
                        fontSize="6xl"
                        fontFamily="FontAwesome5"
                        color={type == item ? 'yellow500' : 'gray200'}
                      />
                      <Text fontSize="lg" ml={10} flex={1}>
                        {t(info.name)}
                      </Text>
                      {type == item && (
                        <Div p={2} rounded="circle" bg="yellow500">
                          <Icon
                            name="check"
                            fontSize="md"
                            color="white"
                            fontFamily="FontAwesome5"
                          />
                        </Div>
                      )}
                    </Div>
                  </Button>
                );
              })}
            </Div>
          </Animatable.View>
        </Div>
      )}

      <FlatList
        refreshControl={
          <RefreshControl refreshing={loading} onRefresh={reload} />
        }
        onEndReached={() => {
          if (!data.last && !loading && !loadingMore) {
            loadMore();
          }
        }}
        onEndReachedThreshold={0.5}
        contentContainerStyle={{
          flexGrow: 1,
          backgroundColor: '#f2f2f2',
        }}
        data={data.list}
        renderItem={({ item }) => {
          return (
            <Div px={15} bg="white">
              <ReacordCom info={item} />
            </Div>
          );
        }}
        keyExtractor={(item) => item.id.toString()}
        onLayout={(e) => {
          console.log(e);
        }}
        ListFooterComponent={() => {
          return (
            <>
              {!data.empty && (
                <Text p={15} textAlign="center">
                  {data.last ? t('dao-di-le') : t('jia-zai-zhong')}
                </Text>
              )}
            </>
          );
        }}
        stickyHeaderIndices={[0]}
        ListEmptyComponent={() => {
          return (
            <>
              {data.empty && (
                <Text textAlign="center" p={15}>
                  {t('wu-shu-ju')}
                </Text>
              )}
            </>
          );
        }}
        ListHeaderComponent={() => {
          return (
            <Div px={15} py={10} bg="gray100">
              <Button
                bg="gray100"
                borderWidth={1}
                borderColor="yellow500"
                color="yellow500"
                fontSize="sm"
                onPress={(e) => {
                  const { nativeEvent } = e;
                  PopoverPicker.show(
                    {
                      x: nativeEvent.pageX,
                      y: nativeEvent.pageY,
                      width: 120,
                    },
                    monthDate.showList,
                    showDate,
                    (item, index) => setshowDate(item)
                  );
                }}
              >
                {showDate}
              </Button>
            </Div>
          );
        }}
      />
    </Div>
  );
}
