import React, { FC, useState, useEffect, useRef, forwardRef, useImperativeHandle } from 'react';
import { TouchableOpacity, View, Animated, Easing, Platform } from 'react-native';

import { ModalStyles } from './styles';
import { Colors } from '../../../../theme';

import { Button, SelectSheet } from '../../../../components';
import { ButtonVariants } from '../../../../types/components';

import { dataAge, dataRanking } from '../utils';

import {
  filterAgeType,
  FilterButtonProps,
  filterCountryType,
  filterRankingType,
  ModalProps,
  FilterModalRef
} from '../utils/types';
import FilterIcon from '../../../../../assets/icons/filter.svg';
import { useConnection } from 'src/contexts/ConnectionContext';

export const FilterModal = forwardRef<FilterModalRef, ModalProps>(({
  countriesData,
  applyFilter,
  isCountryHidden
}, ref) => {
  const netInfo = useConnection();

  const [confirmedAge, setConfirmedAge] = useState<filterAgeType>(null);
  const [confirmedRanking, setConfirmedRanking] = useState<filterRankingType>(null);
  const [confirmedCountry, setConfirmedCountry] = useState<filterCountryType>(null);

  const [filterAge, setFilterAge] = useState<filterAgeType>(null);
  const [filterRanking, setFilterRanking] = useState<filterRankingType>(null);
  const [filterCountry, setFilterCountry] = useState<filterCountryType>(null);

  const [isOpen, setIsOpen] = useState(false);
  const slideAnim = useRef(new Animated.Value(-800)).current;

  const [viewHeight, setViewHeight] = useState(600);

  useImperativeHandle(ref, () => ({
    toggle: () => {
      if (isOpen) {
        setFilterAge(confirmedAge);
        setFilterRanking(confirmedRanking);
        setFilterCountry(confirmedCountry);
        setIsOpen(false);
      } else {
        setIsOpen(true);
      }
    },
    open: () => setIsOpen(true),
    close: () => {
      setFilterAge(confirmedAge);
      setFilterRanking(confirmedRanking);
      setFilterCountry(confirmedCountry);
      setIsOpen(false);
    }
  }));

  useEffect(() => {
    if (isOpen) {
      Animated.spring(slideAnim, {
        toValue: 0,
        speed: 20,
        bounciness: 2,
        useNativeDriver: true,
      }).start();
    } else {
      Animated.timing(slideAnim, {
        toValue: -viewHeight - 50,
        duration: 150,
        easing: Easing.in(Easing.ease),
        useNativeDriver: true,
      }).start();
    }
  }, [isOpen, viewHeight]);

  return (
    <Animated.View
      style={{
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        zIndex: 200,
        elevation: 200,
        transform: [{ translateY: slideAnim }],
      }}
    >
      <View
        onLayout={(e) => setViewHeight(e.nativeEvent.layout.height)}
        style={{
          backgroundColor: 'white',
          paddingTop: 15,
          paddingBottom: 20,
          paddingHorizontal: '5%',
          borderBottomLeftRadius: 20,
          borderBottomRightRadius: 20,
          shadowColor: '#000',
          shadowOffset: { width: 0, height: 4 },
          shadowOpacity: 0.15,
          shadowRadius: 10,
          elevation: 8,
        }}
      >
        <View style={{ display: 'flex', alignItems: 'center' }}>
          {!isCountryHidden && (
            <SelectSheet
              style={[ModalStyles.dropdown, { width: '100%' }] as any}
              data={countriesData}
              disabled={!netInfo?.isInternetReachable}
              labelField="name"
              valueField="two"
              value={filterCountry?.two ?? null}
              placeholder="Country"
              onChange={(item) => setFilterCountry(item)}
              searchable={true}
              searchPlaceholder="Search country..."
              initialSnapPoint={Platform.OS === 'android' ? 100 : 70}
            />
          )}

          <View style={[ModalStyles.ageAndRankingWrapper, !isCountryHidden ? { marginTop: 20 } : {}]}>
            <SelectSheet
              style={ModalStyles.dropdown}
              data={dataRanking}
              labelField="label"
              valueField="value"
              value={filterRanking?.value ?? null}
              placeholder="Ranking"
              onChange={(item) => setFilterRanking(item)}
              initialSnapPoint={Platform.OS === 'android' ? 100 : 70}
            />
            <SelectSheet
              style={ModalStyles.dropdown}
              data={dataAge}
              disabled={!netInfo?.isInternetReachable}
              labelField="label"
              valueField="value"
              value={filterAge?.value ?? null}
              placeholder="Age"
              onChange={(item) => setFilterAge(item)}
              initialSnapPoint={Platform.OS === 'android' ? 100 : 70}
            />
          </View>
          <View style={ModalStyles.buttonsWrapper}>
            <Button
              variant={ButtonVariants.OPACITY}
              containerStyles={{
                borderColor: Colors.DARK_BLUE,
                backgroundColor: 'white',
                width: '45%'
              }}
              textStyles={{
                color: Colors.DARK_BLUE
              }}
              onPress={() => {
                setFilterAge(null);
                setFilterRanking(null);
                setFilterCountry(null);
              }}
              children={'Clear'}
            />
            <Button
              variant={ButtonVariants.FILL}
              containerStyles={{
                borderColor: Colors.DARK_BLUE,
                backgroundColor: Colors.DARK_BLUE,
                width: '45%'
              }}
              textStyles={{
                color: Colors.WHITE
              }}
              onPress={() => {
                setConfirmedAge(filterAge);
                setConfirmedRanking(filterRanking);
                setConfirmedCountry(filterCountry);
                applyFilter(filterAge, filterRanking, filterCountry);
                setIsOpen(false);
              }}
              children={'Show'}
            />
          </View>
        </View>
      </View>
    </Animated.View>
  );
});

export const FilterButton: FC<FilterButtonProps> = ({ onPress }) => {
  return (
    <TouchableOpacity style={{ padding: 5 }} onPress={onPress}>
      <FilterIcon />
    </TouchableOpacity>
  );
};
