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';
import Tooltip from 'react-native-walkthrough-tooltip';

const formatDate = (dateString: string | null) => {
  if (!dateString) return;
  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 getValidDate = (value?: string | null) => {
  if (!value) return null;

  const date = moment(value);
  return date.isValid() ? date : null;
};

const formatSingleLineDate = (dateString: string | null) => {
  const date = getValidDate(dateString);
  if (!date) return null;

  return `${date.format('MMM DD')} ${date.format('YYYY')}`;
};

const getTripDateLabel = (item: TripsData) => {
  const validFrom = getValidDate(item.date_from);
  const validTo = getValidDate(item.date_to);

  if (!validFrom && !validTo) {
    if (item.year) {
      return <Text style={[styles.tripDateText, { marginLeft: 8 }]}>{item.year}</Text>;
    }
    return null;
  }

  const fromYear = validFrom ? validFrom.format('YYYY') : null;
  const toYear = validTo ? validTo.format('YYYY') : null;

  if (item.dates_missing === 1) {
    if (!fromYear && !toYear) return null;

    if (fromYear && toYear && fromYear === toYear) {
      return <Text style={[styles.tripDateText, { marginLeft: 8 }]}>{toYear}</Text>;
    }

    return (
      <>
        {fromYear ? <Text style={[styles.tripDateText, { marginLeft: 8 }]}>{fromYear}</Text> : null}

        {fromYear && toYear ? <Text style={styles.tripDateText}>-</Text> : null}

        {toYear ? <Text style={styles.tripDateText}>{toYear}</Text> : null}
      </>
    );
  }

  const hasValidFrom = !!validFrom;
  const hasValidTo = !!validTo;

  if (!hasValidFrom && !hasValidTo) return null;

  if (hasValidFrom && !hasValidTo) {
    return (
      <Text style={[styles.tripDateText, { marginLeft: 8 }]}>
        {formatSingleLineDate(item.date_from)}
      </Text>
    );
  }

  if (!hasValidFrom && hasValidTo) {
    return (
      <Text style={[styles.tripDateText, { marginLeft: 8 }]}>
        {formatSingleLineDate(item.date_to)}
      </Text>
    );
  }

  if (validFrom && validTo && item.date_from === item.date_to) {
    return (
      <Text style={[styles.tripDateText, { marginLeft: 8 }]}>
        {formatSingleLineDate(item.date_from)}
      </Text>
    );
  }

  return (
    <>
      <Text style={{ marginLeft: 8 }}>{formatDate(item.date_from)}</Text>
      <Text style={styles.tripDateText}>-</Text>
      {formatDate(item.date_to)}
    </>
  );
};

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

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

  const shouldRenderWarning = item.dates_missing === 1;

  const tripDateLabel = getTripDateLabel(item);

  const renderMissingDatesWarning = () => (
    <Tooltip
      isVisible={toolTipVisible}
      content={
        <Text
          style={{
            flex: 1,
            fontSize: 14,
            fontWeight: '600',
            color: Colors.RED,
            paddingRight: 4
          }}
        >
          Fill in exact dates to get accurate statistics.
        </Text>
      }
      contentStyle={{ backgroundColor: Colors.WHITE }}
      placement="top"
      onClose={() => setToolTipVisible(false)}
      backgroundColor="transparent"
      allowChildInteraction={false}
    >
      <TouchableOpacity
        style={{
          alignItems: 'center',
          marginRight: 4
        }}
        onPress={() => setToolTipVisible(true)}
        hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
      >
        <WarningIcon color={Colors.RED} width={18} height={18} />
      </TouchableOpacity>
    </Tooltip>
  );

  return (
    <View style={styles.tripItemContainer}>
      <View style={styles.tripHeaderContainer}>
        <View style={styles.tripDateContainer}>
          {shouldRenderWarning ? (
            renderMissingDatesWarning()
          ) : null}
          {tripDateLabel ? (
            <>
              <CalendarIcon fill={Colors.DARK_BLUE} />
              {tripDateLabel}
            </>
          ) : null}
        </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;
