import React, { useState, useEffect, useMemo } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  RefreshControl,
  FlatList,
  Alert,
} 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
} from '../store/selectors';
import { fetchAllCrmData } 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);

  // 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 = 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);
    }
  };

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

  const handleRefresh = () => {
    fetchCrmData(true);
  };

  const handleRetry = () => {
    fetchCrmData();
  };

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

  // 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
  const tabs = [
    { key: 'leads', label: 'Leads', icon: 'account-heart', count: crmData.leads.length },
    { key: 'tasks', label: 'Tasks', icon: 'check-circle', count: crmData.tasks.length },
    { key: 'contacts', label: 'Contacts', icon: 'account-group', count: crmData.contacts.length },
    { key: 'deals', label: 'Deals', icon: 'handshake', count: crmData.deals.length },
    { key: 'salesOrders', label: 'Sales Orders', icon: 'shopping', count: crmData.salesOrders.length },
    { key: 'purchaseOrders', label: 'Purchase Orders', icon: 'cart', count: crmData.purchaseOrders.length },
    { key: 'invoices', label: 'Invoices', icon: 'receipt', count: crmData.invoices.length },
  ] as const;

  if (isLoading && !crmData.leads.length) {
    return <LoadingSpinner />;
  }

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


  const renderTabContent = () => {
    switch (selectedTab) {
      case 'leads':
        return (
          <FlatList
            data={crmData.leads}
            renderItem={({ item }) => (
              <LeadCard
                lead={item}
                onPress={() => handleCardPress(item, 'Lead')}
              />
            )}
            keyExtractor={(item) => item.id}
            numColumns={1}
            showsVerticalScrollIndicator={false}
            contentContainerStyle={styles.listContainer}
          />
        );
      case 'tasks':
        return (
          <FlatList
            data={crmData.tasks}
            renderItem={({ item }) => (
              <TaskCard
                task={item}
                onPress={() => handleCardPress(item, 'Task')}
              />
            )}
            keyExtractor={(item) => item.id}
            numColumns={1}
            showsVerticalScrollIndicator={false}
            contentContainerStyle={styles.listContainer}
          />
        );
      case 'contacts':
        return (
          <FlatList
            data={crmData.contacts}
            renderItem={({ item }) => (
              <ContactCard
                contact={item}
                onPress={() => handleCardPress(item, 'Contact')}
              />
            )}
            keyExtractor={(item) => item.id}
            numColumns={1}
            showsVerticalScrollIndicator={false}
            contentContainerStyle={styles.listContainer}
          />
        );
      case 'deals':
        return (
          <FlatList
            data={crmData.deals}
            renderItem={({ item }) => (
              <DealCard
                deal={item}
                onPress={() => handleCardPress(item, 'Deal')}
              />
            )}
            keyExtractor={(item) => item.id}
            numColumns={1}
            showsVerticalScrollIndicator={false}
            contentContainerStyle={styles.listContainer}
          />
        );
      case 'salesOrders':
        return (
          <FlatList
            data={crmData.salesOrders}
            renderItem={({ item }) => (
              <SalesOrderCard
                salesOrder={item}
                onPress={() => handleCardPress(item, 'Sales Order')}
              />
            )}
            keyExtractor={(item) => item.id}
            numColumns={1}
            showsVerticalScrollIndicator={false}
            contentContainerStyle={styles.listContainer}
          />
        );
      case 'purchaseOrders':
        return (
          <FlatList
            data={crmData.purchaseOrders}
            renderItem={({ item }) => (
              <PurchaseOrderCard
                purchaseOrder={item}
                onPress={() => handleCardPress(item, 'Purchase Order')}
              />
            )}
            keyExtractor={(item) => item.id}
            numColumns={1}
            showsVerticalScrollIndicator={false}
            contentContainerStyle={styles.listContainer}
          />
        );
      case 'invoices':
        return (
          <FlatList
            data={crmData.invoices}
            renderItem={({ item }) => (
              <InvoiceCard
                invoice={item}
                onPress={() => handleCardPress(item, 'Invoice')}
              />
            )}
            keyExtractor={(item) => item.id}
            numColumns={1}
            showsVerticalScrollIndicator={false}
            contentContainerStyle={styles.listContainer}
          />
        );
      default:
        return null;
    }
  };

  return (
    <Container>
      <ScrollView
        style={[styles.container, { backgroundColor: colors.background }]}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />
        }
      >
        {/* 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>

        {/* Tabs */}
        <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.tabsContainer}>
          <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>

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

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 12,
  },
  title: {
    fontSize: 24,
  },
  tabsContainer: {
    marginBottom: 16,
  },
  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,
    paddingHorizontal: 16,
  },
  listContainer: {
    paddingBottom: 20,
  },
});

export default ZohoCrmDataScreen;
