import React, { useCallback, useEffect } from 'react';
import {
  View,
  Text,
  FlatList,
  TouchableOpacity,
  StyleSheet,
  ActivityIndicator,
  RefreshControl,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { colors } from '../../theme/colors';
import { typography } from '../../theme/typography';
import { spacing } from '../../theme/spacing';
import { useSalesStore } from '../../stores/sales.store';
import { SaleCard } from '../../components/cards/SaleCard';
import type { Sale } from '../../types/sale';
import type { SalesStackParamList } from './types';

type NavigationProp = NativeStackNavigationProp<SalesStackParamList>;

interface TabItem {
  key: 'sales' | 'debts';
  label: string;
}

const TABS: TabItem[] = [
  { key: 'sales', label: 'Продажи' },
  { key: 'debts', label: 'Долги' },
];

function formatAmount(amount: number): string {
  return amount.toLocaleString('ru-RU') + ' \u20BD';
}

export function SalesScreen(): React.JSX.Element {
  const styles = createStyles();
  const navigation = useNavigation<NavigationProp>();
  const activeTab = useSalesStore((state) => state.activeTab);
  const sales = useSalesStore((state) => state.sales);
  const debts = useSalesStore((state) => state.debts);
  const debtsSummary = useSalesStore((state) => state.debtsSummary);
  const isLoading = useSalesStore((state) => state.isLoading);
  const isLoadingMore = useSalesStore((state) => state.isLoadingMore);
  const hasMore = useSalesStore((state) => state.hasMore);
  const debtsHasMore = useSalesStore((state) => state.debtsHasMore);
  const error = useSalesStore((state) => state.error);
  const setActiveTab = useSalesStore((state) => state.setActiveTab);
  const fetchSales = useSalesStore((state) => state.fetchSales);
  const fetchMoreSales = useSalesStore((state) => state.fetchMoreSales);
  const fetchDebts = useSalesStore((state) => state.fetchDebts);
  const fetchMoreDebts = useSalesStore((state) => state.fetchMoreDebts);
  const fetchDebtsSummary = useSalesStore((state) => state.fetchDebtsSummary);

  const currentData = activeTab === 'sales' ? sales : debts;
  const currentHasMore = activeTab === 'sales' ? hasMore : debtsHasMore;

  useEffect(() => {
    fetchSales();
  }, []);

  const handleRefresh = useCallback(() => {
    if (activeTab === 'sales') {
      fetchSales(true);
    } else {
      fetchDebts(true);
      fetchDebtsSummary();
    }
  }, [activeTab, fetchSales, fetchDebts, fetchDebtsSummary]);

  const handleLoadMore = useCallback(() => {
    if (!currentHasMore || isLoadingMore) return;
    if (activeTab === 'sales') {
      fetchMoreSales();
    } else {
      fetchMoreDebts();
    }
  }, [activeTab, currentHasMore, isLoadingMore, fetchMoreSales, fetchMoreDebts]);

  const handleTabPress = useCallback(
    (tab: 'sales' | 'debts') => {
      setActiveTab(tab);
    },
    [setActiveTab],
  );

  const handleCardPress = useCallback(
    (sale: Sale) => {
      // Sale detail navigation can be added later
    },
    [],
  );

  const handleCreatePress = useCallback(() => {
    navigation.navigate('CreateSale');
  }, [navigation]);

  const renderItem = useCallback(
    ({ item }: { item: Sale }) => (
      <SaleCard sale={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.emptyTitle}>
          {activeTab === 'sales' ? 'Нет продаж' : 'Нет долгов'}
        </Text>
        <Text style={styles.emptySubtitle}>
          {activeTab === 'sales'
            ? 'Здесь будут отображаться ваши продажи'
            : 'У ваших клиентов нет задолженностей'}
        </Text>
      </View>
    );
  }, [isLoading, activeTab]);

  return (
    <View style={styles.container}>
      {/* Tab selector */}
      <View style={styles.tabsContainer}>
        {TABS.map((tab) => {
          const isActive = tab.key === activeTab;
          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>
            </TouchableOpacity>
          );
        })}
      </View>

      {/* Debts summary banner */}
      {activeTab === 'debts' && debtsSummary && debtsSummary.count > 0 && (
        <View style={styles.debtsBanner}>
          <View style={styles.debtsBannerContent}>
            <Text style={styles.debtsBannerLabel}>Общая задолженность</Text>
            <Text style={styles.debtsBannerAmount}>
              {formatAmount(debtsSummary.totalAmount)}
            </Text>
          </View>
          <View style={styles.debtsBannerCount}>
            <Text style={styles.debtsBannerCountText}>
              {debtsSummary.count}
            </Text>
            <Text style={styles.debtsBannerCountLabel}>
              {debtsSummary.count === 1
                ? 'долг'
                : debtsSummary.count < 5
                  ? 'долга'
                  : 'долгов'}
            </Text>
          </View>
        </View>
      )}

      {/* Error banner */}
      {error && (
        <View style={styles.errorBanner}>
          <Text style={styles.errorText}>{error}</Text>
        </View>
      )}

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

      {/* FAB */}
      <TouchableOpacity
        style={styles.fab}
        onPress={handleCreatePress}
        activeOpacity={0.8}
      >
        <Text style={styles.fabIcon}>+</Text>
      </TouchableOpacity>
    </View>
  );
}

const createStyles = () => StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  tabsContainer: {
    flexDirection: 'row',
    paddingHorizontal: spacing.lg,
    paddingVertical: spacing.md,
    backgroundColor: colors.white,
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
  },
  tab: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: spacing.lg,
    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,
  },
  debtsBanner: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#FFEBEE',
    marginHorizontal: spacing.lg,
    marginTop: spacing.md,
    padding: spacing.lg,
    borderRadius: 12,
    borderLeftWidth: 4,
    borderLeftColor: colors.error,
  },
  debtsBannerContent: {
    flex: 1,
  },
  debtsBannerLabel: {
    ...typography.caption,
    color: colors.error,
    marginBottom: spacing.xs,
  },
  debtsBannerAmount: {
    ...typography.h3,
    fontWeight: '700',
    color: colors.error,
  },
  debtsBannerCount: {
    alignItems: 'center',
    backgroundColor: colors.error,
    borderRadius: 12,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
  },
  debtsBannerCountText: {
    ...typography.subtitle,
    fontWeight: '700',
    color: colors.white,
  },
  debtsBannerCountLabel: {
    ...typography.caption,
    color: colors.white,
  },
  errorBanner: {
    backgroundColor: colors.error,
    padding: spacing.md,
  },
  errorText: {
    ...typography.bodySmall,
    color: colors.white,
    textAlign: 'center',
  },
  listContent: {
    padding: spacing.lg,
    paddingBottom: 100,
    flexGrow: 1,
  },
  loadingContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  emptyContainer: {
    alignItems: 'center',
    paddingTop: spacing.xxxl * 2,
  },
  emptyTitle: {
    ...typography.subtitle,
    color: colors.text,
    marginBottom: spacing.sm,
  },
  emptySubtitle: {
    ...typography.body,
    color: colors.textMuted,
    textAlign: 'center',
  },
  footer: {
    paddingVertical: spacing.lg,
    alignItems: 'center',
  },
  fab: {
    position: 'absolute',
    bottom: 24,
    right: 24,
    width: 56,
    height: 56,
    borderRadius: 28,
    backgroundColor: colors.primary,
    alignItems: 'center',
    justifyContent: 'center',
    shadowColor: colors.black,
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.2,
    shadowRadius: 8,
    elevation: 6,
  },
  fabIcon: {
    fontSize: 28,
    fontWeight: '400',
    color: colors.white,
    marginTop: -2,
  },
});
