import React, { useCallback, useEffect } from 'react';
import {
  View,
  Text,
  FlatList,
  ScrollView,
  TouchableOpacity,
  StyleSheet,
  ActivityIndicator,
  RefreshControl,
} from 'react-native';
import { colors } from '../../theme/colors';
import { typography } from '../../theme/typography';
import { spacing } from '../../theme/spacing';
import { useFunnelStore } from '../../stores/funnel.store';
import { FunnelCard } from '../../components/cards/FunnelCard';
import type { FunnelEntry, FunnelStage } from '../../types/funnel';

interface StageTab {
  key: FunnelStage;
  label: string;
}

const STAGE_TABS: StageTab[] = [
  { key: 'NEW', label: 'Новые' },
  { key: 'ASSIGNED', label: 'Назначенные' },
  { key: 'COMPLETED', label: 'Проведённые' },
  { key: 'REGULAR', label: 'Постоянные' },
];

interface FunnelScreenProps {
  navigation: {
    navigate: (screen: string, params?: Record<string, unknown>) => void;
  };
}

export function FunnelScreen({ navigation }: FunnelScreenProps): React.JSX.Element {
  const styles = createStyles();
  const activeStage = useFunnelStore((state) => state.activeStage);
  const entriesByStage = useFunnelStore((state) => state.entriesByStage);
  const isLoading = useFunnelStore((state) => state.isLoading);
  const isLoadingMore = useFunnelStore((state) => state.isLoadingMore);
  const setActiveStage = useFunnelStore((state) => state.setActiveStage);
  const fetchByStage = useFunnelStore((state) => state.fetchByStage);
  const fetchMore = useFunnelStore((state) => state.fetchMore);

  const currentEntries = entriesByStage[activeStage];

  useEffect(() => {
    void fetchByStage(activeStage);
  }, []);

  const handleRefresh = useCallback(() => {
    void fetchByStage(activeStage, true);
  }, [activeStage, fetchByStage]);

  const handleLoadMore = useCallback(() => {
    if (currentEntries.hasMore && !isLoadingMore) {
      void fetchMore(activeStage);
    }
  }, [activeStage, currentEntries.hasMore, isLoadingMore, fetchMore]);

  const handleCardPress = useCallback(
    (entry: FunnelEntry) => {
      navigation.navigate('FunnelAction', { clientId: entry.clientId });
    },
    [navigation],
  );

  const handleTabPress = useCallback(
    (stage: FunnelStage) => {
      setActiveStage(stage);
    },
    [setActiveStage],
  );

  const renderItem = useCallback(
    ({ item }: { item: FunnelEntry }) => <FunnelCard entry={item} onPress={handleCardPress} />,
    [handleCardPress],
  );

  const renderFooter = useCallback(() => {
    if (!isLoadingMore) return null;
    return (
      <View style={styles.footer}>
        <ActivityIndicator size="small" color={colors.primary} />
      </View>
    );
  }, [isLoadingMore]);

  const renderEmpty = useCallback(() => {
    if (isLoading) return null;
    return (
      <View style={styles.emptyContainer}>
        <Text style={styles.emptyText}>
          Нет клиентов на этапе "{STAGE_TABS.find((t) => t.key === activeStage)?.label}"
        </Text>
      </View>
    );
  }, [isLoading, activeStage]);

  return (
    <View style={styles.container}>
      <ScrollView
        horizontal
        showsHorizontalScrollIndicator={false}
        style={styles.tabsScroll}
        contentContainerStyle={styles.tabsContainer}
      >
        {STAGE_TABS.map((tab) => {
          const isActive = tab.key === activeStage;
          const count = entriesByStage[tab.key].total;
          return (
            <TouchableOpacity
              key={tab.key}
              style={[styles.tab, isActive && styles.tabActive]}
              onPress={() => handleTabPress(tab.key)}
              activeOpacity={0.7}
            >
              <Text style={[styles.tabText, isActive && styles.tabTextActive]}>{tab.label}</Text>
              {count > 0 && (
                <View style={[styles.tabBadge, isActive && styles.tabBadgeActive]}>
                  <Text style={[styles.tabBadgeText, isActive && styles.tabBadgeTextActive]}>
                    {count}
                  </Text>
                </View>
              )}
            </TouchableOpacity>
          );
        })}
      </ScrollView>

      {isLoading && currentEntries.data.length === 0 ? (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={colors.primary} />
        </View>
      ) : (
        <FlatList
          data={currentEntries.data}
          keyExtractor={(item) => item.id}
          renderItem={renderItem}
          contentContainerStyle={styles.listContent}
          ListEmptyComponent={renderEmpty}
          ListFooterComponent={renderFooter}
          onEndReached={handleLoadMore}
          onEndReachedThreshold={0.3}
          refreshControl={
            <RefreshControl
              refreshing={isLoading && currentEntries.data.length > 0}
              onRefresh={handleRefresh}
              colors={[colors.primary]}
              tintColor={colors.primary}
            />
          }
        />
      )}
    </View>
  );
}

const createStyles = () =>
  StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.background,
    },
    tabsScroll: {
      backgroundColor: colors.white,
      borderBottomWidth: 1,
      borderBottomColor: colors.border,
      flexGrow: 0,
    },
    tabsContainer: {
      flexDirection: 'row',
      paddingHorizontal: spacing.lg,
      paddingVertical: spacing.md,
    },
    tab: {
      flexDirection: 'row',
      alignItems: 'center',
      paddingHorizontal: spacing.md,
      paddingVertical: spacing.sm,
      borderRadius: 20,
      backgroundColor: colors.background,
      marginRight: spacing.sm,
    },
    tabActive: {
      backgroundColor: colors.primary,
    },
    tabText: {
      ...typography.bodySmall,
      fontWeight: '600',
      color: colors.textSecondary,
    },
    tabTextActive: {
      color: colors.white,
    },
    tabBadge: {
      minWidth: 20,
      height: 20,
      borderRadius: 10,
      backgroundColor: colors.border,
      alignItems: 'center',
      justifyContent: 'center',
      marginLeft: spacing.xs,
      paddingHorizontal: 4,
    },
    tabBadgeActive: {
      backgroundColor: 'rgba(255, 255, 255, 0.3)',
    },
    tabBadgeText: {
      ...typography.caption,
      fontWeight: '700',
      color: colors.textSecondary,
      fontSize: 10,
    },
    tabBadgeTextActive: {
      color: colors.white,
    },
    listContent: {
      padding: spacing.lg,
      flexGrow: 1,
    },
    loadingContainer: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
    },
    emptyContainer: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      paddingTop: spacing.xxxl * 2,
    },
    emptyText: {
      ...typography.body,
      color: colors.textMuted,
      textAlign: 'center',
    },
    footer: {
      paddingVertical: spacing.lg,
      alignItems: 'center',
    },
  });
