import React, { useState, useEffect, useMemo, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  RefreshControl,
  FlatList,
  Alert,
  ActivityIndicator,
} from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import type { AppDispatch } from '@/store/store';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { Container, LoadingSpinner, ErrorState } from '@/shared/components/ui';
import { useTheme } from '@/shared/styles/useTheme';
import { showError, showSuccess, showInfo } from '@/shared/utils/Toast';
import type { CrmData, CrmLead, CrmTask, CrmContact, CrmDeal, CrmSalesOrder, CrmPurchaseOrder, CrmInvoice } from '../types/CrmTypes';
import { LeadCard, TaskCard, ContactCard, DealCard, SalesOrderCard, PurchaseOrderCard, InvoiceCard } from '../components/CrmDataCards';
import { 
  selectLeads, 
  selectTasks, 
  selectContacts, 
  selectDeals,
  selectSalesOrders,
  selectPurchaseOrders,
  selectInvoices,
  selectCrmLoading,
  selectCrmErrors,
  selectLeadsPagination,
  selectTasksPagination,
  selectContactsPagination,
  selectDealsPagination,
  selectSalesOrdersPagination,
  selectPurchaseOrdersPagination,
  selectInvoicesPagination,
  selectCrmCounts
} from '../store/selectors';
import { 
  fetchAllCrmData, 
  fetchLeads, 
  fetchTasks,
  fetchContacts,
  fetchDeals,
  fetchSalesOrders,
  fetchPurchaseOrders,
  fetchInvoices,
  fetchCrmCounts,
  resetLeadsPagination,
  resetTasksPagination,
  resetContactsPagination,
  resetDealsPagination,
  resetSalesOrdersPagination,
  resetPurchaseOrdersPagination,
  resetInvoicesPagination
} from '../store/crmSlice';
import type { RootState } from '@/store/store';

const ZohoCrmDataScreen: React.FC = () => {
  const { colors, fonts, spacing, shadows } = useTheme();
  const dispatch = useDispatch<AppDispatch>();
  const [selectedTab, setSelectedTab] = useState<'leads' | 'tasks' | 'contacts' | 'deals' | 'salesOrders' | 'purchaseOrders' | 'invoices'>('leads');
  const [refreshing, setRefreshing] = useState(false);

  // Redux selectors
  const leads = useSelector(selectLeads);
  const tasks = useSelector(selectTasks);
  const contacts = useSelector(selectContacts);
  const deals = useSelector(selectDeals);
  const salesOrders = useSelector(selectSalesOrders);
  const purchaseOrders = useSelector(selectPurchaseOrders);
  const invoices = useSelector(selectInvoices);
  const loading = useSelector(selectCrmLoading);
  const errors = useSelector(selectCrmErrors);
  
  // Pagination selectors
  const leadsPagination = useSelector(selectLeadsPagination);
  const tasksPagination = useSelector(selectTasksPagination);
  const contactsPagination = useSelector(selectContactsPagination);
  const dealsPagination = useSelector(selectDealsPagination);
  const salesOrdersPagination = useSelector(selectSalesOrdersPagination);
  const purchaseOrdersPagination = useSelector(selectPurchaseOrdersPagination);
  const invoicesPagination = useSelector(selectInvoicesPagination);
  const counts = useSelector(selectCrmCounts);

  // Create CRM data object from Redux state
  const crmData: CrmData = useMemo(() => ({
    leads: leads || [],
    tasks: tasks || [],
    contacts: contacts || [],
    deals: deals || [],
    salesOrders: salesOrders || [],
    purchaseOrders: purchaseOrders || [],
    invoices: invoices || [],
  }), [leads, tasks, contacts, deals, salesOrders, purchaseOrders, invoices]);

  // Fetch CRM data using Redux
  const fetchCrmData = useCallback(async (showRefresh = false) => {
    try {
      if (showRefresh) {
        setRefreshing(true);
      }

      // Dispatch Redux action to fetch all CRM data
      await dispatch(fetchAllCrmData()).unwrap();
      
      if (showRefresh) {
        showSuccess('CRM data refreshed successfully');
      }
    } catch (err) {
      const errorMessage = 'Failed to fetch CRM data';
      showError(errorMessage);
    } finally {
      setRefreshing(false);
    }
  }, [dispatch]);

  // Load more data for infinite scrolling
  const loadMoreData = useCallback(async (dataType: string) => {
    try {
      let pagination;
      let fetchAction;

      switch (dataType) {
        case 'leads':
          pagination = leadsPagination;
          fetchAction = fetchLeads;
          break;
        case 'tasks':
          pagination = tasksPagination;
          fetchAction = fetchTasks;
          break;
        case 'contacts':
          pagination = contactsPagination;
          fetchAction = fetchContacts;
          break;
        case 'deals':
          pagination = dealsPagination;
          fetchAction = fetchDeals;
          break;
        case 'salesOrders':
          pagination = salesOrdersPagination;
          fetchAction = fetchSalesOrders;
          break;
        case 'purchaseOrders':
          pagination = purchaseOrdersPagination;
          fetchAction = fetchPurchaseOrders;
          break;
        case 'invoices':
          pagination = invoicesPagination;
          fetchAction = fetchInvoices;
          break;
        default:
          return; // Unknown data type
      }

      console.log(`[Infinite Scroll] ${dataType}:`, {
        currentPage: pagination.page,
        moreRecords: pagination.moreRecords,
        isLoading: loading[dataType as keyof typeof loading],
        currentDataLength: crmData[dataType as keyof CrmData]?.length || 0
      });

      // Check if there are more records and not currently loading
      if (!pagination.moreRecords || loading[dataType as keyof typeof loading]) {
        console.log(`[Infinite Scroll] ${dataType}: Skipping - no more records or already loading`);
        return;
      }

      console.log(`[Infinite Scroll] ${dataType}: Fetching page ${pagination.page + 1}`);

      // Fetch next page
      await (dispatch(fetchAction({
        page: pagination.page + 1,
        limit: 20,
        append: true
      }) as any)).unwrap();

      console.log(`[Infinite Scroll] ${dataType}: Successfully loaded page ${pagination.page + 1}`);

    } catch (err) {
      console.error(`[Infinite Scroll] ${dataType}: Error:`, err);
      showError(`Failed to load more ${dataType}`);
    }
  }, [dispatch, leadsPagination, tasksPagination, contactsPagination, dealsPagination, salesOrdersPagination, purchaseOrdersPagination, invoicesPagination, loading, crmData]);

  useEffect(() => {
    fetchCrmData();
    // Fetch counts in parallel
    dispatch(fetchCrmCounts());
  }, []);

  const handleRefresh = useCallback(() => {
    // Reset pagination for all data types before refreshing
    dispatch(resetLeadsPagination());
    dispatch(resetTasksPagination());
    dispatch(resetContactsPagination());
    dispatch(resetDealsPagination());
    dispatch(resetSalesOrdersPagination());
    dispatch(resetPurchaseOrdersPagination());
    dispatch(resetInvoicesPagination());
    
    // Then fetch fresh data and counts
    fetchCrmData(true);
    dispatch(fetchCrmCounts());
  }, [fetchCrmData, dispatch]);

  const handleRetry = useCallback(() => {
    fetchCrmData();
  }, [fetchCrmData]);

  const handleCardPress = useCallback((item: any, type: string) => {
    showInfo(`Viewing ${type}: ${item.name || item.subject || `${item.firstName} ${item.lastName}`}`);
  }, []);

  // Render loading footer for infinite scroll
  const renderFooter = useCallback((dataType: string) => {
    const isLoadingMore = loading[dataType as keyof typeof loading];
    if (!isLoadingMore) return null;

    return (
      <View style={styles.footerLoader}>
        <ActivityIndicator size="small" color={colors.primary} />
        <Text style={[styles.footerText, { color: colors.textLight }]}>
          Loading more...
        </Text>
      </View>
    );
  }, [loading, colors]);

  // Get current loading state and error
  const isLoading = loading.leads || loading.tasks || loading.contacts || loading.deals || 
                   loading.salesOrders || loading.purchaseOrders || loading.invoices;
  const hasError = errors.leads || errors.tasks || errors.contacts || errors.deals || 
                  errors.salesOrders || errors.purchaseOrders || errors.invoices;


  // Tab configuration with counts from API
  const tabs = [
    { 
      key: 'leads', 
      label: 'Leads', 
      icon: 'account-heart', 
      count: counts?.leads || crmData.leads.length 
    },
    { 
      key: 'tasks', 
      label: 'Tasks', 
      icon: 'check-circle', 
      count: counts?.tasks || crmData.tasks.length 
    },
    { 
      key: 'contacts', 
      label: 'Contacts', 
      icon: 'account-group', 
      count: counts?.contacts || crmData.contacts.length 
    },
    { 
      key: 'deals', 
      label: 'Deals', 
      icon: 'handshake', 
      count: counts?.deals || crmData.deals.length 
    },
    { 
      key: 'salesOrders', 
      label: 'Sales Orders', 
      icon: 'shopping', 
      count: counts?.salesOrders || crmData.salesOrders.length 
    },
    { 
      key: 'purchaseOrders', 
      label: 'Purchase Orders', 
      icon: 'cart', 
      count: counts?.purchaseOrders || crmData.purchaseOrders.length 
    },
    { 
      key: 'invoices', 
      label: 'Invoices', 
      icon: 'receipt', 
      count: counts?.invoices || crmData.invoices.length 
    },
  ] as const;

  const renderTabContent = useCallback(() => {
    const commonFlatListProps = {
      numColumns: 1,
      showsVerticalScrollIndicator: false,
      contentContainerStyle: styles.listContainer,
      refreshControl: (
        <RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />
      ),
    };

    switch (selectedTab) {
      case 'leads':
        return (
          <FlatList
            data={crmData.leads}
            renderItem={({ item }) => (
              <LeadCard
                lead={item}
                onPress={() => handleCardPress(item, 'Lead')}
              />
            )}
            keyExtractor={(item) => `lead-${item.id}`}
            onEndReached={() => loadMoreData('leads')}
            onEndReachedThreshold={0.1}
            ListFooterComponent={() => renderFooter('leads')}
            {...commonFlatListProps}
          />
        );
      case 'tasks':
        return (
          <FlatList
            data={crmData.tasks}
            renderItem={({ item }) => (
              <TaskCard
                task={item}
                onPress={() => handleCardPress(item, 'Task')}
              />
            )}
            keyExtractor={(item) => `task-${item.id}`}
            onEndReached={() => loadMoreData('tasks')}
            onEndReachedThreshold={0.1}
            ListFooterComponent={() => renderFooter('tasks')}
            {...commonFlatListProps}
          />
        );
      case 'contacts':
        return (
          <FlatList
            data={crmData.contacts}
            renderItem={({ item }) => (
              <ContactCard
                contact={item}
                onPress={() => handleCardPress(item, 'Contact')}
              />
            )}
            keyExtractor={(item) => `contact-${item.id}`}
            onEndReached={() => loadMoreData('contacts')}
            onEndReachedThreshold={0.1}
            ListFooterComponent={() => renderFooter('contacts')}
            {...commonFlatListProps}
          />
        );
      case 'deals':
        return (
          <FlatList
            data={crmData.deals}
            renderItem={({ item }) => (
              <DealCard
                deal={item}
                onPress={() => handleCardPress(item, 'Deal')}
              />
            )}
            keyExtractor={(item) => `deal-${item.id}`}
            onEndReached={() => loadMoreData('deals')}
            onEndReachedThreshold={0.1}
            ListFooterComponent={() => renderFooter('deals')}
            {...commonFlatListProps}
          />
        );
      case 'salesOrders':
        return (
          <FlatList
            data={crmData.salesOrders}
            renderItem={({ item }) => (
              <SalesOrderCard
                salesOrder={item}
                onPress={() => handleCardPress(item, 'Sales Order')}
              />
            )}
            keyExtractor={(item) => `sales-order-${item.id}`}
            onEndReached={() => loadMoreData('salesOrders')}
            onEndReachedThreshold={0.1}
            ListFooterComponent={() => renderFooter('salesOrders')}
            {...commonFlatListProps}
          />
        );
      case 'purchaseOrders':
        return (
          <FlatList
            data={crmData.purchaseOrders}
            renderItem={({ item }) => (
              <PurchaseOrderCard
                purchaseOrder={item}
                onPress={() => handleCardPress(item, 'Purchase Order')}
              />
            )}
            keyExtractor={(item) => `purchase-order-${item.id}`}
            onEndReached={() => loadMoreData('purchaseOrders')}
            onEndReachedThreshold={0.1}
            ListFooterComponent={() => renderFooter('purchaseOrders')}
            {...commonFlatListProps}
          />
        );
      case 'invoices':
        return (
          <FlatList
            data={crmData.invoices}
            renderItem={({ item }) => (
              <InvoiceCard
                invoice={item}
                onPress={() => handleCardPress(item, 'Invoice')}
              />
            )}
            keyExtractor={(item) => `invoice-${item.id}`}
            onEndReached={() => loadMoreData('invoices')}
            onEndReachedThreshold={0.1}
            ListFooterComponent={() => renderFooter('invoices')}
            {...commonFlatListProps}
          />
        );
      default:
        return null;
    }
  }, [selectedTab, crmData, handleCardPress, loadMoreData, renderFooter, refreshing, handleRefresh]);

  // Conditional returns after all hooks
  if (isLoading && !crmData.leads.length) {
    return <LoadingSpinner />;
  }

  if (hasError && !crmData.leads.length) {
    return <ErrorState onRetry={handleRetry} />;
  }

  return (
      <View style={[styles.container, { backgroundColor: colors.background }]}>
        {/* Fixed Header */}
        <View style={styles.header}>
          <Text style={[styles.title, { color: colors.text, fontFamily: fonts.bold }]}>
            Zoho CRM Data
          </Text>
          <TouchableOpacity onPress={handleRefresh} disabled={refreshing}>
            <Icon name="refresh" size={24} color={colors.primary} />
          </TouchableOpacity>
        </View>

        {/* Fixed Tabs */}
        <View style={styles.tabsContainer}>
          <ScrollView horizontal showsHorizontalScrollIndicator={false}>
            <View style={styles.tabs}>
              {tabs.map((tab) => (
                <TouchableOpacity
                  key={tab.key}
                  style={[
                    styles.tab,
                    selectedTab === tab.key && { backgroundColor: colors.primary },
                  ]}
                  onPress={() => setSelectedTab(tab.key)}
                  activeOpacity={0.8}
                >
                  <Icon
                    name={tab.icon}
                    size={20}
                    color={selectedTab === tab.key ? colors.surface : colors.textLight}
                  />
                  <Text
                    style={[
                      styles.tabText,
                      {
                        color: selectedTab === tab.key ? colors.surface : colors.textLight,
                        fontFamily: fonts.medium,
                      },
                    ]}
                  >
                    {tab.label}
                  </Text>
                  <View
                    style={[
                      styles.countBadge,
                      { backgroundColor: selectedTab === tab.key ? colors.surface : colors.primary },
                    ]}
                  >
                    <Text
                      style={[
                        styles.countText,
                        {
                          color: selectedTab === tab.key ? colors.primary : colors.surface,
                          fontFamily: fonts.bold,
                        },
                      ]}
                    >
                      {tab.count}
                    </Text>
                  </View>
                </TouchableOpacity>
              ))}
            </View>
          </ScrollView>
        </View>

        {/* Scrollable Content */}
        <View style={styles.content}>
          {renderTabContent()}
        </View>
      </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 12,
  },
  title: {
    fontSize: 24,
  },
  tabsContainer: {
    backgroundColor: '#FFFFFF',
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#E5E7EB',
  },
  tabs: {
    flexDirection: 'row',
    paddingHorizontal: 16,
  },
  tab: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 10,
    marginRight: 8,
    borderRadius: 20,
    backgroundColor: '#F1F5F9',
  },
  tabText: {
    marginLeft: 6,
    fontSize: 14,
  },
  countBadge: {
    marginLeft: 6,
    paddingHorizontal: 8,
    paddingVertical: 2,
    borderRadius: 10,
    minWidth: 20,
    alignItems: 'center',
  },
  countText: {
    fontSize: 12,
  },
  content: {
    flex: 1,
  },
  listContainer: {
    paddingHorizontal: 16,
    paddingBottom: 20,
  },
  footerLoader: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 16,
  },
  footerText: {
    marginLeft: 8,
    fontSize: 14,
  },
});

export default ZohoCrmDataScreen;
