import { useCallback, useEffect, useRef } from 'react';
import { Text, TouchableOpacity, View, Image, Animated, Dimensions, Platform } 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';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

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

const parseRegionPhotos = (value: unknown): string | undefined => {
  if (typeof value !== 'string' || !value.trim()) return undefined;
  try {
    const arr = JSON.parse(value);
    return Array.isArray(arr) && arr.length > 0 ? arr[0] : undefined;
  } catch {
    return undefined;
  }
};

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();
  const insets = useSafeAreaInsets();

  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 = parseRegionPhotos(region.region_photos);

  function formatNumber(value?: number | null) {
    const number = typeof value === 'number' && !isNaN(value) ? value : 0;

    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 },
        Platform.OS === 'android' ? { bottom: insets.bottom + 22 } : {}
      ]}
    >
      <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' &&
            userData?.type !== 'nm' &&
            !disabled &&
            userData?.visited_regions <= 1 ? (
              <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) || userData.edit_in_trips === 1
                  ? 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;
                } else if (userData?.type === 'nm' && userData?.edit_in_trips === 1) {
                  openEditModal();
                  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) ||
              (userData?.visited &&
                !disabled &&
                userData?.type === 'nm' &&
                userData?.edit_in_trips === 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);
