import React, { useRef, useState } from 'react';
import { View, Text, Image, StyleSheet, TouchableOpacity, Platform } from 'react-native';
import ActionSheet, { SheetManager } from 'react-native-actions-sheet';
import { Colors } from 'src/theme';
import { getFontSize } from 'src/utils';
import { FlashList } from '@shopify/flash-list';
import { API_HOST } from 'src/constants';
import { useNavigation } from '@react-navigation/native';
import { NAVIGATION_PAGES } from 'src/types';
import { useSubscription } from 'src/screens/OfflineMapsScreen/useSubscription';

const MultipleSeriesModal = () => {
  const navigation = useNavigation();
  const { isPremium, loading } = useSubscription();
  const [seriesData, setSeriesData] = useState<any>(null);
  const [markers, setMarkers] = useState<any[]>([]);

  const shouldOpenWarningModalRef = useRef(false);
  const shouldOpenPremiumWarningModalRef = useRef(false);

  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 handleSheetOpen = (payload: any) => {
    setSeriesData(payload);
    setMarkers(payload?.markers || []);
  };

  const handleToggleSeries = (item: any) => {
    if (!seriesData) return;

    if (!seriesData.token) {
      shouldOpenWarningModalRef.current = true;
      SheetManager.hide('multiple-series-modal');

      return;
    }
    seriesData.setSelectedMarker(item);

    seriesData.toggleSeries(item);
    setMarkers((prevMarkers) =>
      prevMarkers.map((marker) =>
        marker.id === item.id ? { ...marker, visited: item.visited === 1 ? 0 : 1 } : marker
      )
    );
  };

  const handleItemPress = (item: any) => {
    if (!seriesData) return;

    seriesData.setSelectedMarker(item);
    SheetManager.hide('multiple-series-modal');
  };

  return (
    <ActionSheet
      id="multiple-series-modal"
      gestureEnabled={Platform.OS === 'ios'}
      onBeforeShow={(sheetRef) => {
        const payload = sheetRef || null;
        handleSheetOpen(payload);
      }}
      onClose={() => {
        if (shouldOpenWarningModalRef.current) {
          if (!seriesData) return;

          shouldOpenWarningModalRef.current = false;
          seriesData.setIsWarningModalVisible(true);
        } else if (shouldOpenPremiumWarningModalRef.current) {
          if (!seriesData) return;

          shouldOpenPremiumWarningModalRef.current = false;
          seriesData.setPremiumModalVisible(true);
        }
      }}
      containerStyle={styles.sheetContainer}
      defaultOverlayOpacity={0.5}
    >
      {seriesData && (
        <View style={styles.container}>
          <FlashList
            data={markers}
            keyExtractor={(item, index) => item.id.toString() + index.toString()}
            showsVerticalScrollIndicator={true}
            persistentScrollbar={true}
            renderItem={({ item }) => {
              const formattedCount = formatNumber(item.no_visited);
              const parsedAvatars =
                typeof item.avatars === 'string' ? JSON.parse(item.avatars) : item.avatars;

              return (
                <TouchableOpacity style={styles.option} onPress={() => handleItemPress(item)}>
                  <View style={styles.imageContainer}>
                    <Image
                      source={{ uri: item.icon?.uri || '' }}
                      style={styles.icon}
                      resizeMode="contain"
                    />
                  </View>

                  <View style={{ flex: 1, gap: 8 }}>
                    <View style={{ justifyContent: 'space-between', flex: 1 }}>
                      <Text style={styles.name}>{item.series_name}</Text>
                      <Text style={styles.description}>{item.name}</Text>
                    </View>

                    <View
                      style={{
                        flexDirection: 'row',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                        flex: 1
                      }}
                    >
                      {parsedAvatars && (
                        <TouchableOpacity
                          onPress={() => {
                            if (!isPremium) {
                              shouldOpenPremiumWarningModalRef.current = true;
                              SheetManager.hide('multiple-series-modal');

                              return;
                            }
                            SheetManager.hide('multiple-series-modal');
                            navigation.navigate(
                              ...([
                                NAVIGATION_PAGES.USERS_LIST,
                                {
                                  id: item.id,
                                  isFromHere: false,
                                  type: 'series'
                                }
                              ] as never)
                            );
                          }}
                          style={styles.userImageContainer}
                        >
                          {parsedAvatars?.map((avatar: number, index: number) => (
                            <Image
                              key={avatar}
                              source={{ uri: API_HOST + '/img/avatars/' + avatar + '.webp' }}
                              style={styles.userImageSmall}
                            />
                          ))}
                          <View style={styles.userCountContainer}>
                            <Text style={styles.userCount}>{formattedCount}</Text>
                          </View>
                        </TouchableOpacity>
                      )}

                      <TouchableOpacity
                        onPress={() => handleToggleSeries(item)}
                        style={[styles.markButton, item.visited === 1 && styles.visitedButton]}
                      >
                        {item.visited === 1 ? (
                          <View style={styles.completedContainer}>
                            <Text style={[styles.calloutButtonText, { color: Colors.DARK_BLUE }]}>
                              Completed
                            </Text>
                          </View>
                        ) : (
                          <Text style={styles.calloutButtonText}>To Complete</Text>
                        )}
                      </TouchableOpacity>
                    </View>
                  </View>
                </TouchableOpacity>
              );
            }}
          />
        </View>
      )}
    </ActionSheet>
  );
};

const styles = StyleSheet.create({
  sheetContainer: {
    height: '85%',
    borderTopLeftRadius: 15,
    borderTopRightRadius: 15
  },
  container: {
    minHeight: 200,
    height: '100%',
    backgroundColor: 'white',
    paddingHorizontal: 16,
    paddingTop: 8,
    gap: 16
  },
  completedContainer: { flexDirection: 'row', alignItems: 'center', gap: 6 },
  calloutButtonText: {
    color: Colors.WHITE,
    fontSize: getFontSize(13),
    fontWeight: '700'
  },
  icon: {
    width: 32,
    height: 32
  },
  markButton: {
    paddingHorizontal: 12,
    paddingVertical: 6,
    backgroundColor: Colors.ORANGE,
    borderRadius: 6,
    height: 30,
    alignItems: 'center',
    justifyContent: 'center'
  },
  visitedButton: {
    backgroundColor: Colors.WHITE,
    borderWidth: 1,
    borderColor: Colors.BORDER_LIGHT
  },
  option: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: Colors.FILL_LIGHT,
    paddingVertical: 8,
    paddingHorizontal: 12,
    borderRadius: 8,
    marginBottom: 6
  },
  imageContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    marginRight: 8
  },
  name: {
    fontSize: getFontSize(14),
    fontFamily: 'montserrat-700',
    color: Colors.DARK_BLUE,
    flex: 1
  },
  description: {
    fontSize: getFontSize(12),
    fontWeight: '600',
    color: Colors.DARK_BLUE,
    flex: 1
  },
  userCountContainer: {
    width: 28,
    height: 28,
    borderRadius: 14,
    backgroundColor: Colors.DARK_LIGHT,
    alignItems: 'center',
    justifyContent: 'center',
    marginLeft: -6
  },
  userCount: {
    fontSize: 12,
    color: Colors.DARK_BLUE,
    lineHeight: 24
  },
  userImageContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginLeft: 6
  },
  userImageSmall: {
    width: 28,
    height: 28,
    borderRadius: 14,
    marginLeft: -6,
    borderWidth: 1,
    borderColor: Colors.DARK_LIGHT,
    resizeMode: 'cover'
  }
});

export default MultipleSeriesModal;
