import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, RefreshControl, ScrollView, ActivityIndicator } from 'react-native';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { useSelector, useDispatch } from 'react-redux';
import { useTheme } from '@/shared/styles/useTheme';
import { useNavigation } from '@react-navigation/native';
import { fetchAllSalesforceCrmData, fetchSalesforceCrmCounts } from '../store/salesforceCrmSlice';
import { 
  selectDashboardData,
  selectIsAnyLoading,
  selectHasAnyError
} from '../store/selectors';
import type { AppDispatch } from '@/store/store';
import { PieChart, DonutChart, StackedBarChart } from '@/shared/components/charts';

const SalesforceCrmDashboardScreen: React.FC = () => {
  const { colors, fonts } = useTheme();
  const navigation = useNavigation();
  const dispatch = useDispatch<AppDispatch>();

  // Redux selectors
  const dashboardData = useSelector(selectDashboardData);
  const isLoading = useSelector(selectIsAnyLoading);
  const hasError = useSelector(selectHasAnyError);
  const [refreshing, setRefreshing] = useState(false);

  // Fetch data on component mount
  useEffect(() => {
    fetchData();
  }, [dispatch]);

  // Fetch all Salesforce CRM data
  const fetchData = async () => {
    try {
      await dispatch(fetchAllSalesforceCrmData()).unwrap();
      await dispatch(fetchSalesforceCrmCounts()).unwrap();
    } catch (error) {
      console.error('Failed to fetch Salesforce CRM data:', error);
    }
  };

  // Handle refresh
  const handleRefresh = async () => {
    setRefreshing(true);
    await fetchData();
    setRefreshing(false);
  };

  return (
    <ScrollView 
      style={[styles.container, { backgroundColor: colors.background }]}
      contentContainerStyle={styles.scrollContent}
      refreshControl={
        <RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />
      }
    > 
      <View style={styles.header}>
        <Text style={[styles.title, { color: colors.text, fontFamily: fonts.bold }]}>Salesforce CRM</Text>
        <TouchableOpacity 
          style={[styles.dataButton, { backgroundColor: colors.primary }]}
          onPress={() => navigation.navigate('SalesforceData' as never)}
        >
          <Icon name="database" size={20} color={colors.surface} />
          <Text style={[styles.dataButtonText, { color: colors.surface, fontFamily: fonts.medium }]}>
            View Data
          </Text>
        </TouchableOpacity>
      </View>

      {/* Loading State */}
      {isLoading && !dashboardData.events.length && (
        <View style={[styles.loadingCard, { borderColor: colors.primary, backgroundColor: colors.surface }]}>
          <ActivityIndicator size="large" color={colors.primary} />
          <Text style={[styles.loadingText, { color: colors.primary, fontFamily: fonts.medium }]}>
            Loading Salesforce CRM data...
          </Text>
        </View>
      )}

      {/* Error State */}
      {hasError && !dashboardData.events.length && (
        <View style={[styles.errorCard, { borderColor: colors.error, backgroundColor: colors.surface }]}>
          <Icon name="alert-circle" size={20} color={colors.error} />
          <Text style={[styles.errorText, { color: colors.error, fontFamily: fonts.medium }]}>
            Failed to load data. Pull to refresh.
          </Text>
        </View>
      )}

      {/* Hero Stats - Large Cards */}
      <View style={styles.heroStatsContainer}>
        <View style={[styles.heroCard, { backgroundColor: colors.surface, borderColor: colors.border }]}>
          <View style={styles.heroCardHeader}>
            <Icon name="account-heart" size={24} color="#3B82F6" />
            <Text style={[styles.heroCardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Leads</Text>
          </View>
          <Text style={[styles.heroCardValue, { color: colors.text, fontFamily: fonts.bold }]}>
            {dashboardData.counts?.leads || dashboardData.summary.totalLeads}
          </Text>
          <Text style={[styles.heroCardSubtitle, { color: colors.textLight, fontFamily: fonts.regular }]}>
            {dashboardData.summary.newLeads} New · {dashboardData.summary.qualifiedLeads} Qualified
          </Text>
        </View>

        <View style={[styles.heroCard, { backgroundColor: colors.surface, borderColor: colors.border }]}>
          <View style={styles.heroCardHeader}>
            <Icon name="handshake" size={24} color="#10B981" />
            <Text style={[styles.heroCardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Opportunities</Text>
          </View>
          <Text style={[styles.heroCardValue, { color: colors.text, fontFamily: fonts.bold }]}>
            {dashboardData.counts?.opportunities || dashboardData.summary.totalOpportunities}
          </Text>
          <Text style={[styles.heroCardSubtitle, { color: colors.textLight, fontFamily: fonts.regular }]}>
            {dashboardData.summary.openOpportunities} Open · {dashboardData.summary.wonOpportunities} Won
          </Text>
        </View>
      </View>

      {/* Pipeline Value Card */}
      <View style={[styles.pipelineCard, { backgroundColor: colors.surface, borderColor: colors.border }]}>
        <View style={styles.pipelineHeader}>
          <Icon name="trending-up" size={28} color="#10B981" />
          <Text style={[styles.pipelineTitle, { color: colors.text, fontFamily: fonts.bold }]}>Pipeline Overview</Text>
        </View>
        <View style={styles.pipelineStats}>
          <View style={styles.pipelineItem}>
            <Text style={[styles.pipelineLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Total Pipeline</Text>
            <Text style={[styles.pipelineValue, { color: colors.text, fontFamily: fonts.bold }]}>
              ${(dashboardData.summary.totalPipelineValue / 1000).toFixed(1)}K
            </Text>
          </View>
          <View style={styles.pipelineItem}>
            <Text style={[styles.pipelineLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Avg Deal Size</Text>
            <Text style={[styles.pipelineValue, { color: colors.primary, fontFamily: fonts.bold }]}>
              ${(dashboardData.summary.averageDealSize / 1000).toFixed(1)}K
            </Text>
          </View>
          <View style={styles.pipelineItem}>
            <Text style={[styles.pipelineLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Open Deals</Text>
            <Text style={[styles.pipelineValue, { color: colors.text, fontFamily: fonts.bold }]}>
              {dashboardData.summary.openOpportunities}
            </Text>
          </View>
        </View>
      </View>

      {/* Module Counts - Compact Grid */}
      <View style={styles.compactGrid}>
        <View style={[styles.compactCard, { backgroundColor: colors.surface, borderColor: colors.border }]}>
          <Icon name="calendar" size={20} color="#8B5CF6" />
          <Text style={[styles.compactValue, { color: colors.text, fontFamily: fonts.bold }]}>
            {dashboardData.counts?.events || dashboardData.summary.totalEvents}
          </Text>
          <Text style={[styles.compactLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Events</Text>
        </View>
        
        <View style={[styles.compactCard, { backgroundColor: colors.surface, borderColor: colors.border }]}>
          <Icon name="check-circle" size={20} color="#10B981" />
          <Text style={[styles.compactValue, { color: colors.text, fontFamily: fonts.bold }]}>
            {dashboardData.counts?.tasks || dashboardData.summary.totalTasks}
          </Text>
          <Text style={[styles.compactLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Tasks</Text>
        </View>
        
        <View style={[styles.compactCard, { backgroundColor: colors.surface, borderColor: colors.border }]}>
          <Icon name="domain" size={20} color="#F59E0B" />
          <Text style={[styles.compactValue, { color: colors.text, fontFamily: fonts.bold }]}>
            {dashboardData.counts?.accounts || dashboardData.summary.totalAccounts}
          </Text>
          <Text style={[styles.compactLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Accounts</Text>
        </View>
      </View>

      {/* Lead Status Distribution */}
      <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
        <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Lead Status Distribution</Text>
        
        <View style={styles.chartContainer}>
          <PieChart 
            data={[
              { label: 'New', value: dashboardData.summary.newLeads, color: '#3AA0FF' },
              { label: 'Working', value: dashboardData.summary.workingLeads, color: '#F59E0B' },
              { label: 'Qualified', value: dashboardData.summary.qualifiedLeads, color: '#22C55E' },
            ].filter(item => item.value > 0)}
            colors={colors}
            fonts={fonts}
            size={140}
          />
          
          {/* Legend */}
          <View style={styles.pieLegend}>
            {[
              { label: 'New', value: dashboardData.summary.newLeads, color: '#3AA0FF' },
              { label: 'Working', value: dashboardData.summary.workingLeads, color: '#F59E0B' },
              { label: 'Qualified', value: dashboardData.summary.qualifiedLeads, color: '#22C55E' },
            ].filter(item => item.value > 0).map((item) => (
              <View key={item.label} style={styles.legendItem}>
                <View style={[styles.legendDot, { backgroundColor: item.color }]} />
                <Text style={[styles.legendText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                  {item.label} ({item.value})
                </Text>
              </View>
            ))}
          </View>
        </View>
      </View>

      {/* Task Status */}
      <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
        <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Task Status</Text>
        
        <View style={styles.chartContainer}>
          <StackedBarChart 
            data={[
              { label: 'Open', value: dashboardData.summary.openTasks, color: '#3AA0FF' },
              { label: 'Completed', value: dashboardData.summary.completedTasks, color: '#22C55E' },
              { label: 'High Priority', value: dashboardData.summary.highPriorityTasks, color: '#EF4444' },
            ].filter(item => item.value > 0)}
            colors={colors}
            fonts={fonts}
            height={120}
          />
          
          {/* Legend */}
          <View style={styles.barLegend}>
            {[
              { label: 'Open', value: dashboardData.summary.openTasks, color: '#3AA0FF' },
              { label: 'Completed', value: dashboardData.summary.completedTasks, color: '#22C55E' },
              { label: 'High Priority', value: dashboardData.summary.highPriorityTasks, color: '#EF4444' },
            ].filter(item => item.value > 0).map((item) => (
              <View key={item.label} style={styles.legendItem}>
                <View style={[styles.legendDot, { backgroundColor: item.color }]} />
                <Text style={[styles.legendText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                  {item.label} ({item.value})
                </Text>
              </View>
            ))}
          </View>
        </View>
      </View>

      {/* Key Metrics */}
      <View style={styles.metricsRow}>
        <View style={[styles.metricCard, { backgroundColor: colors.surface, borderColor: colors.border }]}>
          <Icon name="calendar-clock" size={24} color="#F59E0B" />
          <Text style={[styles.metricValue, { color: colors.text, fontFamily: fonts.bold }]}>
            {dashboardData.summary.upcomingEvents}
          </Text>
          <Text style={[styles.metricLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Upcoming Events</Text>
        </View>
        
        <View style={[styles.metricCard, { backgroundColor: colors.surface, borderColor: colors.border }]}>
          <Icon name="trophy" size={24} color="#22C55E" />
          <Text style={[styles.metricValue, { color: colors.text, fontFamily: fonts.bold }]}>
            {dashboardData.summary.wonOpportunities}
          </Text>
          <Text style={[styles.metricLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Won Deals</Text>
        </View>
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
  },
  scrollContent: {
    paddingBottom: 20,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 16,
  },
  title: {
    fontSize: 24,
  },
  dataButton: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 20,
  },
  dataButtonText: {
    marginLeft: 6,
    fontSize: 14,
  },
  loadingCard: {
    borderRadius: 12,
    borderWidth: 1,
    padding: 20,
    marginBottom: 16,
    alignItems: 'center',
    justifyContent: 'center',
  },
  loadingText: {
    marginTop: 12,
    fontSize: 14,
    textAlign: 'center',
  },
  errorCard: {
    borderRadius: 12,
    borderWidth: 1,
    padding: 12,
    marginBottom: 16,
    flexDirection: 'row',
    alignItems: 'center',
  },
  errorText: {
    marginLeft: 8,
    fontSize: 14,
    flex: 1,
  },
  heroStatsContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 16,
  },
  heroCard: {
    flex: 1,
    marginHorizontal: 4,
    padding: 20,
    borderRadius: 16,
    borderWidth: 1,
    alignItems: 'center',
  },
  heroCardHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 12,
  },
  heroCardTitle: {
    fontSize: 16,
    marginLeft: 8,
  },
  heroCardValue: {
    fontSize: 32,
    marginBottom: 4,
  },
  heroCardSubtitle: {
    fontSize: 12,
    textAlign: 'center',
  },
  pipelineCard: {
    padding: 20,
    borderRadius: 16,
    borderWidth: 1,
    marginBottom: 16,
  },
  pipelineHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 16,
  },
  pipelineTitle: {
    fontSize: 20,
    marginLeft: 12,
  },
  pipelineStats: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  pipelineItem: {
    flex: 1,
    alignItems: 'center',
  },
  pipelineLabel: {
    fontSize: 12,
    marginBottom: 4,
  },
  pipelineValue: {
    fontSize: 18,
  },
  compactGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
    marginBottom: 16,
  },
  compactCard: {
    width: '30%',
    padding: 12,
    borderRadius: 12,
    borderWidth: 1,
    alignItems: 'center',
    marginBottom: 8,
  },
  compactValue: {
    fontSize: 18,
    marginVertical: 4,
  },
  compactLabel: {
    fontSize: 10,
    textAlign: 'center',
  },
  card: {
    borderRadius: 12,
    borderWidth: 1,
    padding: 16,
    marginBottom: 16,
  },
  cardTitle: {
    fontSize: 16,
    marginBottom: 12,
  },
  chartContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 10,
  },
  pieLegend: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'center',
    marginTop: 12,
    gap: 8,
  },
  barLegend: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'center',
    marginTop: 8,
    gap: 6,
  },
  legendItem: {
    flexDirection: 'row',
    alignItems: 'center',
    marginRight: 12,
    marginTop: 6,
  },
  legendDot: {
    width: 8,
    height: 8,
    borderRadius: 4,
    marginRight: 6,
  },
  legendText: {
    fontSize: 12,
  },
  metricsRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 16,
  },
  metricCard: {
    flex: 1,
    marginHorizontal: 4,
    padding: 16,
    borderRadius: 12,
    borderWidth: 1,
    alignItems: 'center',
  },
  metricValue: {
    fontSize: 20,
    marginVertical: 8,
  },
  metricLabel: {
    fontSize: 12,
    textAlign: 'center',
  },
});

export default SalesforceCrmDashboardScreen;

