import { useCallback, useEffect, useRef } from 'react';
import { Text, TouchableOpacity, View, Image, Animated, Dimensions } from 'react-native';
import MarkIcon from 'assets/icons/mark.svg';
import EditSvg from 'assets/icons/travels-screens/pen-to-square.svg';
import CalendarSvg from 'assets/icons/travels-screens/calendar.svg';
import RotateSvg from 'assets/icons/travels-screens/rotate.svg';
import CheckSvg from 'assets/icons/travels-screens/circle-check.svg';
import CheckRegularSvg from 'assets/icons/travels-screens/circle-check-regular.svg';

import { styles } from './style';
import React from 'react';
import { Colors } from 'src/theme';
import { useFocusEffect, useNavigation } from '@react-navigation/native';
import { NAVIGATION_PAGES } from 'src/types';

interface Region {
  id: number;
  name: string;
  region_photos: string;
  visitors_count: number;
}

interface RegionPopupProps {
  region: Region;
  userAvatars: string[];
  userData: any;
  openEditModal: () => void;
  updateNM: (region: number, first: number, last: number, visits: number, quality: number) => void;
  updateDare: (region: number, visits: 0 | 1) => void;
  disabled?: boolean;
  updateSlow: (id: number, v: boolean, s11: boolean, s31: boolean, s101: boolean) => void;
  openEditSlowModal: () => void;
}

const RegionPopup: React.FC<RegionPopupProps> = ({
  region,
  userAvatars,
  userData,
  openEditModal,
  updateNM,
  updateDare,
  disabled,
  updateSlow,
  openEditSlowModal
}) => {
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const navigation = useNavigation();

  useEffect(() => {
    Animated.timing(fadeAnim, {
      toValue: 1,
      duration: 300,
      useNativeDriver: true
    }).start();
  }, [fadeAnim]);

  const splitRegionName = (fullName: string) => {
    const [name, ...rest] = fullName?.split(/ – | - /);
    const subname = rest?.join(' - ');
    return {
      regionTitle: name,
      regionSubtitle: subname ? subname : ''
    };
  };

  const { regionTitle, regionSubtitle } = splitRegionName(region.name);
  const regionImg = JSON.parse(region.region_photos)[0];

  function formatNumber(number: number) {
    if (number >= 1000 && number < 10000) {
      return (number / 1000).toFixed(1) + 'k';
    } else if (number >= 10000) {
      return (number / 1000).toFixed(0) + 'k';
    }
    return number.toString();
  }

  const formattedCount = formatNumber(region.visitors_count);

  const renderDurationIcon = (condition: 0 | 1) =>
    condition ? <CheckSvg fill={Colors.DARK_BLUE} /> : <CheckRegularSvg />;

  const isSmallScreen = Dimensions.get('window').width < 383;

  return (
    <Animated.View style={[styles.popupContainer, { opacity: fadeAnim }]}>
      <TouchableOpacity
        onPress={() => {
          if (userData?.type === 'countries') {
            navigation.navigate(
              ...([
                NAVIGATION_PAGES.COUNTRY_PREVIEW,
                {
                  regionId: region.id,
                  type: 'country',
                  disabled
                }
              ] as never)
            );
          } else {
            navigation.navigate(
              ...([
                NAVIGATION_PAGES.REGION_PREVIEW,
                {
                  regionId: region.id,
                  type: userData?.type,
                  disabled
                }
              ] as never)
            );
          }
        }}
        style={{ flex: 1 }}
      >
        <View style={styles.regionInfoContainer}>
          {regionImg && <Image source={{ uri: regionImg }} style={styles.regionImage} />}
          <View style={styles.regionTextContainer}>
            <Text style={styles.regionTitle}>{regionTitle}</Text>
            {regionSubtitle && <Text style={styles.regionSubtitle}>{regionSubtitle}</Text>}
            {userData?.type === 'countries' && (
              <View style={styles.infoContainer}>
                <Text style={styles.infoText} numberOfLines={2}>
                  {userData?.info_text}
                </Text>
                {!userData?.visited && (
                  <TouchableOpacity
                    onPress={() =>
                      navigation.navigate(
                        ...([
                          NAVIGATION_PAGES.EDIT_COUNTRY_DATA,
                          {
                            countryId: region.id,
                            countryName: regionTitle,
                            countryFlag: userData?.flag,
                            slow11: userData?.slow11,
                            slow31: userData?.slow31,
                            slow101: userData?.slow101,
                            isSlowList: false
                          }
                        ] as never)
                      )
                    }
                    style={styles.editRegionBtn}
                    hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
                  >
                    <EditSvg width={14} height={14} />
                  </TouchableOpacity>
                )}
              </View>
            )}
          </View>
        </View>

        <View>
          <View style={styles.separator} />
        </View>

        <View style={styles.bottomContainer}>
          <View style={styles.userContainer}>
            {userData?.visited && userData?.first_visit_year > 1 && !disabled && (
              <View style={styles.infoContent}>
                <CalendarSvg height={18} width={18} fill={Colors.DARK_BLUE} />
                <Text style={styles.visitedButtonText}>{userData?.first_visit_year}</Text>
              </View>
            )}

            {userData?.visited && userData?.type === 'nm' && !disabled && (
              <View style={styles.infoContent}>
                <RotateSvg fill={Colors.DARK_BLUE} />
                <Text style={styles.visitedButtonText}>
                  {userData.no_of_visits >= 10 ? '10+' : userData.no_of_visits}
                </Text>
              </View>
            )}
            {userData?.visited && userData?.type === 'countries' && !disabled && (
              <View style={styles.durationContainer}>
                <View style={styles.durationItem}>
                  {renderDurationIcon(userData.slow11)}
                  <View style={[styles.slowText, isSmallScreen ? { flexDirection: 'column' } : {}]}>
                    <Text style={styles.visitDuration}>11+ </Text>
                    <Text style={styles.visitDuration}>days</Text>
                  </View>
                </View>
                <View style={styles.durationItem}>
                  {renderDurationIcon(userData.slow31)}
                  <View style={[styles.slowText, isSmallScreen ? { flexDirection: 'column' } : {}]}>
                    <Text style={styles.visitDuration}>31+ </Text>
                    <Text style={styles.visitDuration}>days</Text>
                  </View>
                </View>
                <View style={styles.durationItem}>
                  {renderDurationIcon(userData.slow101)}
                  <View style={[styles.slowText, isSmallScreen ? { flexDirection: 'column' } : {}]}>
                    <Text style={styles.visitDuration}>101+ </Text>
                    <Text style={styles.visitDuration}>days</Text>
                  </View>
                </View>
              </View>
            )}

            {(!userData?.visited || userData?.type === 'dare' || disabled) && (
              <View style={styles.userImageContainer}>
                {userAvatars?.map((avatar, index) => (
                  <Image key={index} source={{ uri: avatar }} style={styles.userImage} />
                ))}
                <View style={styles.userCountContainer}>
                  <Text style={styles.userCount}>{formattedCount}</Text>
                </View>
              </View>
            )}
          </View>
          <View style={styles.btnContainer}>
            {userData?.visited &&
            userData?.type !== 'dare' &&
            !disabled &&
            (userData?.visited_regions <= 1 || userData?.type === 'nm') ? (
              <TouchableOpacity
                onPress={
                  userData?.type === 'countries'
                    ? () =>
                        navigation.navigate(
                          ...([
                            NAVIGATION_PAGES.EDIT_COUNTRY_DATA,
                            {
                              countryId: region.id,
                              countryName: regionTitle,
                              countryFlag: userData?.flag,
                              slow11: userData?.slow11,
                              slow31: userData?.slow31,
                              slow101: userData?.slow101,
                              isSlowList: false
                            }
                          ] as never)
                        )
                    : openEditModal
                }
                style={styles.editBtn}
              >
                <EditSvg width={14} height={14} />
              </TouchableOpacity>
            ) : null}
            <TouchableOpacity
              style={[
                styles.btn,
                userData?.visited && !disabled ? styles.visitedButton : styles.markVisitedButton
              ]}
              onPress={() => {
                if (
                  userData?.visited &&
                  !disabled &&
                  userData?.type === 'countries' &&
                  userData?.visited_regions > 1
                ) {
                  navigation.navigate(
                    ...([
                      NAVIGATION_PAGES.EDIT_COUNTRY_DATA,
                      {
                        countryId: region.id,
                        countryName: regionTitle,
                        countryFlag: userData?.flag,
                        slow11: userData?.slow11,
                        slow31: userData?.slow31,
                        slow101: userData?.slow101,
                        isSlowList: false
                      }
                    ] as never)
                  );
                  return;
                }

                userData?.type === 'nm'
                  ? updateNM(
                      region.id,
                      userData.visited ? 0 : 1,
                      userData.visited ? 0 : 1,
                      userData.visited ? 0 : 1,
                      3
                    )
                  : userData?.type === 'countries'
                    ? updateSlow(
                        region.id,
                        !userData.visited,
                        Boolean(userData.slow11),
                        Boolean(userData.slow31),
                        Boolean(userData.slow101)
                      )
                    : updateDare(region.id, userData.visited ? 0 : 1);
              }}
            >
              {userData?.visited &&
              !disabled &&
              userData?.type === 'countries' &&
              userData?.visited_regions > 1 ? (
                <View style={styles.visitedContainer}>
                  <EditSvg width={14} height={14} />
                  <Text style={styles.visitedButtonText}>Edit</Text>
                </View>
              ) : userData?.visited && !disabled ? (
                <View style={styles.visitedContainer}>
                  <MarkIcon width={16} height={16} />
                  <Text style={styles.visitedButtonText}>Visited</Text>
                </View>
              ) : (
                <Text style={[styles.markVisitedButtonText]}>Mark Visited</Text>
              )}
            </TouchableOpacity>
          </View>
        </View>
      </TouchableOpacity>
    </Animated.View>
  );
};

export default React.memo(RegionPopup);
