import React, { useState } from 'react';
import { View, Text, TouchableOpacity, Image } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import moment from 'moment';

import { TripsData } from '../../utils/types';
import { API_HOST } from 'src/constants';
import { Colors } from 'src/theme';
import { NAVIGATION_PAGES } from 'src/types';
import { styles } from './styles';

import CalendarIcon from 'assets/icons/travels-screens/calendar.svg';
import EditIcon from 'assets/icons/travels-screens/pen-to-square.svg';
import ArrowIcon from 'assets/icons/chevron-left.svg';
import WarningIcon from 'assets/icons/warning.svg';

const TripItem = ({ item, isNew }: { item: TripsData; isNew?: boolean }) => {
  const navigation = useNavigation();
  const [showAllRegions, setShowAllRegions] = useState(false);

  const formatDate = (dateString: string) => {
    const date = moment(dateString);
    const formattedDate = date.format('MMM DD');
    const year = date.format('YYYY');

    return (
      <Text style={styles.alignCenter}>
        <Text style={styles.tripDateText}>{formattedDate}</Text>
        {'\n'}
        <Text style={styles.tripDateText}>{year}</Text>
      </Text>
    );
  };

  const MAX_VISIBLE_REGIONS = 3;
  const totalRegions = item.regions?.length || 0;
  const visibleRegions = showAllRegions
    ? item.regions
    : item.regions?.slice(0, MAX_VISIBLE_REGIONS);

  return (
    <View style={styles.tripItemContainer}>
      {isNew && item.dates_missing === 1 ? (
        <View style={{ flexDirection: 'row', gap: 6, alignItems: 'center', marginBottom: 10 }}>
          <WarningIcon color={Colors.RED} width={16} height={16} />
          <Text style={{ fontSize: 14, fontWeight: '600', color: Colors.RED }}>
            Fill in exact dates.
          </Text>
        </View>
      ) : null}
      <View style={styles.tripHeaderContainer}>
        <View style={styles.tripDateContainer}>
          <CalendarIcon fill={Colors.DARK_BLUE} />
          <Text style={[styles.tripDateText, { marginLeft: 8 }]}>{formatDate(item.date_from)}</Text>
          <Text style={styles.tripDateText}>-</Text>
          <Text style={styles.tripDateText}>{formatDate(item.date_to)}</Text>
        </View>
        <TouchableOpacity
          style={styles.editButton}
          onPress={() =>
            navigation.navigate(
              ...([NAVIGATION_PAGES.ADD_TRIP_2025, { editTripId: item.id }] as never)
            )
          }
        >
          <EditIcon />
          <Text style={styles.editButtonText}>Edit</Text>
        </TouchableOpacity>
      </View>

      <View style={styles.divider} />

      {item.description && (
        <>
          <Text style={styles.descriptionTitle}>Description</Text>
          <Text style={styles.descriptionText}>{item.description}</Text>
        </>
      )}

      <Text style={styles.visitedRegionsTitle}>Visited regions</Text>
      <View style={styles.regionsContainer}>
        {visibleRegions?.map((region, index) => {
          if (!region.id || !region.region_name) return null;
          const [name, ...rest] = region.region_name?.split(/ – | - /);
          const subname = rest?.join(' - ');

          return (
            <View key={`${region.id}-${index}`} style={styles.regionItem}>
              <Image source={{ uri: API_HOST + region.flag1 }} style={styles.flagIcon} />
              {region.flag2 && (
                <Image
                  source={{ uri: API_HOST + region.flag2 }}
                  style={[styles.flagIcon, { marginLeft: -5 }]}
                />
              )}
              <View style={styles.nameContainer}>
                <Text style={styles.regionName}>{name}</Text>
                <Text style={styles.regionSubname}>{subname}</Text>
              </View>
            </View>
          );
        })}
      </View>

      {totalRegions > MAX_VISIBLE_REGIONS && (
        <TouchableOpacity
          style={styles.showMoreButton}
          hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
          onPress={() => setShowAllRegions(!showAllRegions)}
        >
          <ArrowIcon
            fill={Colors.DARK_BLUE}
            style={[styles.headerIcon, showAllRegions ? styles.rotate : null]}
          />
          <Text style={styles.showMoreText}>
            {showAllRegions ? 'Show less' : `Show more (${totalRegions - MAX_VISIBLE_REGIONS})`}
          </Text>
        </TouchableOpacity>
      )}
    </View>
  );
};

export default TripItem;
