import React, { useState } from 'react';
import { View, Text, Image, StyleSheet, TouchableOpacity, Platform } from 'react-native';
import { FlashList } from '@shopify/flash-list';
import ActionSheet, { SheetManager } from 'react-native-actions-sheet';
import { Colors } from 'src/theme';
import { API_HOST } from 'src/constants';
import { getFontSize } from 'src/utils';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Loading } from 'src/components';
import { usePostGetProfileSeriesData } from '@api/user';
import { storage, StoreType } from 'src/storage';

import CheckSvg from 'assets/icons/travels-screens/circle-check.svg';
import CloseSVG from 'assets/icons/close.svg';

const SeriesModal = () => {
  const token = storage.get('token', StoreType.STRING) as string;
  const insets = useSafeAreaInsets();

  const [userId, setUserId] = useState<number | null>(null);
  const [seriesId, setSeriesId] = useState<number | null>(null);

  const { data: seriesData } = usePostGetProfileSeriesData(
    token,
    userId ?? 0,
    seriesId ?? 0,
    seriesId && userId ? true : false
  );

  const handleSheetOpen = (payload: any) => {
    setSeriesId(payload?.seriesId);
    setUserId(payload?.userId);
  };

  const renderCountryItem = ({ item: country }: { item: any }) => {
    const visibleItems = country.items;

    return (
      <View style={styles.countryContainer}>
        {country.icon || country.name ? (
          <>
            <View style={styles.countryHeader}>
              {country.icon ? (
                <Image source={{ uri: `${API_HOST}${country.icon}` }} style={styles.flagIcon} />
              ) : null}
              {country.name ? <Text style={styles.countryName}>{country.name}</Text> : null}
            </View>

            <View style={styles.divider}></View>
          </>
        ) : null}

        <View style={styles.sitesContainer}>
          {visibleItems.map((site: { item_id: number; name: string }, index: number) => (
            <View key={index} style={styles.siteItem}>
              <View style={styles.checkIcon}>
                <CheckSvg width={16} height={16} fill={Colors.DARK_BLUE} />
              </View>
              <Text style={styles.siteName}>{site.name}</Text>
            </View>
          ))}
        </View>
      </View>
    );
  };

  const renderHeader = () => (
    <View style={styles.headerContainer}>
      <Image source={{ uri: `${API_HOST}${seriesData?.series_icon}` }} style={styles.seriesIcon} />
      <Text style={styles.seriesTitle}>{seriesData?.series_name}</Text>
    </View>
  );

  return (
    <ActionSheet
      id="visited-series-modal"
      gestureEnabled={Platform.OS === 'ios'}
      onBeforeShow={(sheetRef) => {
        const payload = sheetRef || null;
        handleSheetOpen(payload);
      }}
      containerStyle={styles.sheetContainer}
      defaultOverlayOpacity={0.5}
    >
      {Platform.OS === 'android' && (
        <TouchableOpacity
          onPress={() => SheetManager.hide('visited-series-modal')}
          style={{ marginLeft: 14, padding: 4 }}
          hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }}
        >
          <CloseSVG />
        </TouchableOpacity>
      )}

      {seriesData ? (
        <View style={[styles.container, { paddingBottom: insets.bottom }]}>
          {renderHeader()}
          <View style={styles.listContainer}>
            <FlashList
              keyExtractor={(item, index) => item.name + index.toString()}
              data={seriesData.items_grouped}
              renderItem={renderCountryItem}
              estimatedItemSize={200}
              showsVerticalScrollIndicator={false}
              ItemSeparatorComponent={() => <View style={styles.separator} />}
            />
          </View>
        </View>
      ) : (
        <View style={[styles.container, { paddingBottom: insets.bottom, paddingTop: 0 }]}>
          <Loading />
        </View>
      )}
    </ActionSheet>
  );
};

const styles = StyleSheet.create({
  sheetContainer: {
    borderTopLeftRadius: 15,
    borderTopRightRadius: 15,
    height: '92%'
  },
  container: {
    backgroundColor: 'white',
    paddingHorizontal: 16,
    paddingTop: 8,
    height: '100%'
  },
  listContainer: {
    flex: 1,
    minHeight: 300
  },
  headerContainer: {
    alignItems: 'center',
    paddingBottom: 12,
    gap: 8
  },
  seriesIcon: {
    width: 32,
    height: 32
  },
  seriesTitle: {
    fontSize: getFontSize(14),
    fontFamily: 'montserrat-700',
    color: Colors.DARK_BLUE,
    textAlign: 'center'
  },
  countryContainer: {
    backgroundColor: Colors.FILL_LIGHT,
    borderRadius: 8,
    padding: 12,
    gap: 8
  },
  countryHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8
  },
  flagIcon: {
    width: 24,
    height: 24,
    borderRadius: 12,
    borderWidth: 0.5,
    borderColor: Colors.BORDER_LIGHT
  },
  countryName: {
    fontSize: getFontSize(14),
    fontFamily: 'montserrat-700',
    color: Colors.DARK_BLUE
  },
  divider: {
    height: 1,
    backgroundColor: '#D3D3D3'
  },
  sitesContainer: {
    gap: 8
  },
  siteItem: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 8
  },
  checkIcon: {
    width: 24,
    height: 24,
    justifyContent: 'center',
    alignItems: 'center'
  },
  siteName: {
    fontSize: getFontSize(12),
    color: Colors.DARK_BLUE,
    fontWeight: '600',
    flex: 1
  },
  separator: {
    height: 8
  }
});

export default SeriesModal;
