import { 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 { 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>}
          </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 ? (
              <TouchableOpacity
                onPress={userData?.type === 'countries' ? openEditSlowModal : openEditModal}
                style={styles.editBtn}
              >
                <EditSvg width={14} height={14} />
              </TouchableOpacity>
            ) : null}
            <TouchableOpacity
              style={[
                styles.btn,
                userData?.visited && !disabled ? styles.visitedButton : styles.markVisitedButton
              ]}
              onPress={() =>
                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 ? (
                <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);
