import React, { useState, useEffect, useMemo, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  RefreshControl,
  FlatList,
  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 { LoadingSpinner, ErrorState } from '@/shared/components/ui';
import { useTheme } from '@/shared/styles/useTheme';
import { showError, showSuccess, showInfo } from '@/shared/utils/Toast';
import { EventCard, LeadCard, TaskCard, AccountCard, OpportunityCard } from '../components/SalesforceDataCards';
import { 
  selectSalesforceEvents,
  selectSalesforceLeads, 
  selectSalesforceTasks, 
  selectSalesforceAccounts, 
  selectSalesforceOpportunities,
  selectSalesforceCrmLoading,
  selectSalesforceCrmErrors,
  selectEventsPagination,
  selectLeadsPagination,
  selectTasksPagination,
  selectAccountsPagination,
  selectOpportunitiesPagination,
  selectSalesforceCrmCounts
} from '../store/selectors';
import { 
  fetchAllSalesforceCrmData,
  fetchSalesforceEvents, 
  fetchSalesforceLeads, 
  fetchSalesforceTasks,
  fetchSalesforceAccounts,
  fetchSalesforceOpportunities,
  fetchSalesforceCrmCounts,
  resetEventsPagination,
  resetLeadsPagination,
  resetTasksPagination,
  resetAccountsPagination,
  resetOpportunitiesPagination
} from '../store/salesforceCrmSlice';

const SalesforceDataScreen: React.FC = () => {
  const { colors, fonts } = useTheme();
  const dispatch = useDispatch<AppDispatch>();
  const [selectedTab, setSelectedTab] = useState<'events' | 'leads' | 'tasks' | 'accounts' | 'opportunities'>('leads');
  const [refreshing, setRefreshing] = useState(false);

  // Redux selectors
  const events = useSelector(selectSalesforceEvents);
  const leads = useSelector(selectSalesforceLeads);
  const tasks = useSelector(selectSalesforceTasks);
  const accounts = useSelector(selectSalesforceAccounts);
  const opportunities = useSelector(selectSalesforceOpportunities);
  const loading = useSelector(selectSalesforceCrmLoading);
  const errors = useSelector(selectSalesforceCrmErrors);
  
  // Pagination selectors
  const eventsPagination = useSelector(selectEventsPagination);
  const leadsPagination = useSelector(selectLeadsPagination);
  const tasksPagination = useSelector(selectTasksPagination);
  const accountsPagination = useSelector(selectAccountsPagination);
  const opportunitiesPagination = useSelector(selectOpportunitiesPagination);
  const counts = useSelector(selectSalesforceCrmCounts);

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

      // Dispatch Redux action to fetch all Salesforce CRM data
      await dispatch(fetchAllSalesforceCrmData()).unwrap();
      
      if (showRefresh) {
        showSuccess('Salesforce data refreshed successfully');
      }
    } catch (err) {
      const errorMessage = 'Failed to fetch Salesforce 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 'events':
          pagination = eventsPagination;
          fetchAction = fetchSalesforceEvents;
          break;
        case 'leads':
          pagination = leadsPagination;
          fetchAction = fetchSalesforceLeads;
          break;
        case 'tasks':
          pagination = tasksPagination;
          fetchAction = fetchSalesforceTasks;
          break;
        case 'accounts':
          pagination = accountsPagination;
          fetchAction = fetchSalesforceAccounts;
          break;
        case 'opportunities':
          pagination = opportunitiesPagination;
          fetchAction = fetchSalesforceOpportunities;
          break;
        default:
          return;
      }

      // Check if there are more records and not currently loading
      if (!pagination.moreRecords || loading[dataType as keyof typeof loading]) {
        return;
      }

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

    } catch (err) {
      showError(`Failed to load more ${dataType}`);
    }
  }, [dispatch, eventsPagination, leadsPagination, tasksPagination, accountsPagination, opportunitiesPagination, loading]);

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

  const handleRefresh = useCallback(() => {
    // Reset pagination for all data types before refreshing
    dispatch(resetEventsPagination());
    dispatch(resetLeadsPagination());
    dispatch(resetTasksPagination());
    dispatch(resetAccountsPagination());
    dispatch(resetOpportunitiesPagination());
    
    // Then fetch fresh data and counts
    fetchSalesforceData(true);
    dispatch(fetchSalesforceCrmCounts());
  }, [fetchSalesforceData, dispatch]);

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

  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.events || loading.leads || loading.tasks || loading.accounts || loading.opportunities;
  const hasError = errors.events || errors.leads || errors.tasks || errors.accounts || errors.opportunities;

  // Tab configuration with counts from API
  const tabs = [
    { 
      key: 'events', 
      label: 'Events', 
      icon: 'calendar', 
      count: counts?.events || events.length 
    },
    { 
      key: 'leads', 
      label: 'Leads', 
      icon: 'account-heart', 
      count: counts?.leads || leads.length 
    },
    { 
      key: 'tasks', 
      label: 'Tasks', 
      icon: 'check-circle', 
      count: counts?.tasks || tasks.length 
    },
    { 
      key: 'accounts', 
      label: 'Accounts', 
      icon: 'domain', 
      count: counts?.accounts || accounts.length 
    },
    { 
      key: 'opportunities', 
      label: 'Opportunities', 
      icon: 'handshake', 
      count: counts?.opportunities || opportunities.length 
    },
  ] as const;

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

    switch (selectedTab) {
      case 'events':
        return (
          <FlatList
            data={events}
            renderItem={({ item }) => (
              <EventCard
                event={item}
                onPress={() => handleCardPress(item, 'Event')}
              />
            )}
            keyExtractor={(item) => `event-${item.Id}`}
            onEndReached={() => loadMoreData('events')}
            onEndReachedThreshold={0.1}
            ListFooterComponent={() => renderFooter('events')}
            {...commonFlatListProps}
          />
        );
      case 'leads':
        return (
          <FlatList
            data={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={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 'accounts':
        return (
          <FlatList
            data={accounts}
            renderItem={({ item }) => (
              <AccountCard
                account={item}
                onPress={() => handleCardPress(item, 'Account')}
              />
            )}
            keyExtractor={(item) => `account-${item.Id}`}
            onEndReached={() => loadMoreData('accounts')}
            onEndReachedThreshold={0.1}
            ListFooterComponent={() => renderFooter('accounts')}
            {...commonFlatListProps}
          />
        );
      case 'opportunities':
        return (
          <FlatList
            data={opportunities}
            renderItem={({ item }) => (
              <OpportunityCard
                opportunity={item}
                onPress={() => handleCardPress(item, 'Opportunity')}
              />
            )}
            keyExtractor={(item) => `opportunity-${item.Id}`}
            onEndReached={() => loadMoreData('opportunities')}
            onEndReachedThreshold={0.1}
            ListFooterComponent={() => renderFooter('opportunities')}
            {...commonFlatListProps}
          />
        );
      default:
        return null;
    }
  }, [selectedTab, events, leads, tasks, accounts, opportunities, handleCardPress, loadMoreData, renderFooter, refreshing, handleRefresh]);

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

  if (hasError && !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 }]}>
          Salesforce 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 SalesforceDataScreen;

