import React, { useEffect, useState, useCallback, JSX } from 'react';
import { View, Text, Image, TouchableOpacity } from 'react-native';
import { MaterialCommunityIcons } from '@expo/vector-icons';

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

import TrashSvg from 'assets/icons/travels-screens/trash-solid.svg';
import ChevronIcon from 'assets/icons/travels-screens/down-arrow.svg';
import CheckSvg from 'assets/icons/travels-screens/check.svg';
import SquareSvg from 'assets/icons/travels-screens/square.svg';
import CopySvg from 'assets/icons/travels-screens/copy.svg';

interface DateValue {
  year: number | null;
  month: number | null;
  day: number | null;
}

interface RegionItemProps {
  region: RegionAddData;
  onDelete: () => void;
  onQualityChange: () => void;
  onHiddenChange: () => void;
  visitStartDate?: DateValue | null;
  visitEndDate?: DateValue | null;
  onDateChange?: (field: 'visitStartDate' | 'visitEndDate', dateValue: DateValue) => void;
  openDatePicker?: (
    index: number,
    field: 'visitStartDate' | 'visitEndDate',
    initialDate?: DateValue | null
  ) => void;
  onDuplicate: () => void;
  onMoveUp: () => void;
  onMoveDown: () => void;
  index: number;
  total: number;
}

const RegionItem = ({
  region,
  onDelete,
  onQualityChange,
  onHiddenChange,
  visitStartDate,
  visitEndDate,
  onDateChange,
  openDatePicker,
  onDuplicate,
  onMoveUp,
  onMoveDown,
  index,
  total
}: RegionItemProps) => {
  const [name, ...rest] = region.region_name?.split(/ – | - /);
  const subname = rest?.join(' - ');
  const qualityName = region.quality
    ? qualityOptions.find((q) => q.id === region.quality)?.name
    : 'Good Visit';

  const formatDateForDisplay = useCallback((dateValue: DateValue | null): string => {
    if (!dateValue || !dateValue.year) return 'Select date';

    let result = dateValue.year.toString();

    if (dateValue.month) {
      result = `${dateValue.month.toString().padStart(2, '0')}.${result}`;

      if (dateValue.day) {
        result = `${dateValue.day.toString().padStart(2, '0')}.${result}`;
      }
    }

    return result;
  }, []);

  const isDateValid = useCallback((dateValue: DateValue | null): boolean => {
    return dateValue !== null && dateValue.year !== null;
  }, []);

  const renderDatePicker = useCallback(
    (field: 'visitStartDate' | 'visitEndDate', currentDate: DateValue | null): JSX.Element => (
      <TouchableOpacity
        style={styles.dateInput}
        onPress={() => openDatePicker?.(index, field, currentDate)}
      >
        <Text style={[styles.dateText, !isDateValid(currentDate) && styles.placeholderText]}>
          {formatDateForDisplay(currentDate)}
        </Text>
        <MaterialCommunityIcons name="chevron-down" size={20} color={Colors.DARK_BLUE} />
      </TouchableOpacity>
    ),
    [formatDateForDisplay, isDateValid, region.id, openDatePicker]
  );

  return (
    <View key={region.id} style={styles.regionItem}>
      <View style={styles.regionItemTop}>
        <View style={styles.regionHeader}>
          <Image
            source={{ uri: `${API_HOST}/img/flags_new/${region.flag1}` }}
            style={styles.flagStyle}
          />
          {region.flag2 && (
            <Image
              source={{ uri: `${API_HOST}/img/flags_new/${region.flag2}` }}
              style={[styles.flagStyle, { marginLeft: -17 }]}
            />
          )}
          <View style={styles.nameContainer}>
            <Text style={styles.regionName}>{name}</Text>
            <Text style={styles.regionSubname}>{subname}</Text>
          </View>
        </View>
        <TouchableOpacity style={styles.trashBtn} onPress={onDelete}>
          <TrashSvg fill={Colors.WHITE} />
        </TouchableOpacity>
      </View>

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

      <View style={styles.regionDatesContainer}>
        <View style={styles.dateRow}>
          <View style={styles.dateColumn}>
            <Text style={styles.dateFieldLabel}>Start of visit</Text>
            {renderDatePicker('visitStartDate', visitStartDate || null)}
          </View>
          <View style={styles.dateColumn}>
            <Text style={styles.dateFieldLabel}>End of visit</Text>
            {renderDatePicker('visitEndDate', visitEndDate || null)}
          </View>
        </View>
      </View>

      <Text style={styles.qualityOfVisit}>Quality of visit</Text>
      <View style={styles.regionItemBottom}>
        <TouchableOpacity style={styles.qualitySelector} onPress={onQualityChange}>
          <Text style={styles.qualityButtonText}>{qualityName}</Text>
          <ChevronIcon width={18} height={18} />
        </TouchableOpacity>
      </View>
      {region.can_be_hidden && (
        <View style={{ marginTop: 12, marginHorizontal: '25%' }}>
          <TouchableOpacity style={[styles.markCompletedButton]} onPress={onHiddenChange}>
            <View style={styles.completedContainer}>
              <View style={{ position: 'relative' }}>
                <SquareSvg />
              </View>
              {region.hidden && (
                <View style={{ position: 'absolute', left: 2, top: 1 }}>
                  <CheckSvg width={14} height={14} />
                </View>
              )}

              <Text style={styles.markCompletedButtonText}>Hidden</Text>
            </View>
          </TouchableOpacity>
        </View>
      )}
      <View style={styles.regionActionsRow}>
        <TouchableOpacity onPress={onDuplicate} style={styles.iconButton}>
          <CopySvg width={20} height={20} fill={Colors.DARK_BLUE} />
        </TouchableOpacity>

        <View style={styles.actionsRow}>
          <TouchableOpacity onPress={onMoveUp} style={styles.iconButton} disabled={index === 0}>
            <MaterialCommunityIcons
              name="arrow-up"
              size={20}
              color={index === 0 ? Colors.LIGHT_GRAY : Colors.DARK_BLUE}
            />
          </TouchableOpacity>

          <TouchableOpacity
            onPress={onMoveDown}
            style={styles.iconButton}
            disabled={index === total - 1}
          >
            <MaterialCommunityIcons
              name="arrow-down"
              size={20}
              color={index === total - 1 ? Colors.LIGHT_GRAY : Colors.DARK_BLUE}
            />
          </TouchableOpacity>
        </View>
      </View>
    </View>
  );
};

export default RegionItem;
