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 { Container } from '@/shared/components/ui';
import { PieChart, DonutChart, FunnelChart, StackedBarChart, PipelineFlow, PipelineCards, CompactPipeline } from '@/shared/components/charts';
import { useTheme } from '@/shared/styles/useTheme';
import { useNavigation } from '@react-navigation/native';
import { fetchCrmKPIs } from '../store/crmSlice';
import { 
  selectCrmKPIs
} from '../store/selectors';
import type { RootState } from '@/store/store';
import type { AppDispatch } from '@/store/store';

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

  // Redux selectors
  const crmKPIs = useSelector(selectCrmKPIs);
  const [isLoading, setIsLoading] = useState(false);
  const [hasError, setHasError] = useState(false);

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

  // Debug log to check KPIs data
  useEffect(() => {
    // console.log('CRM KPIs Data:', crmKPIs);
  }, [crmKPIs]);

  // Fetch KPIs data
  const fetchKPIsData = async () => {
    try {
      setIsLoading(true);
      setHasError(false);
      await dispatch(fetchCrmKPIs()).unwrap();
    } catch (error) {
      console.error('Failed to fetch KPIs data:', error);
      setHasError(true);
    } finally {
      setIsLoading(false);
    }
  };

  // Handle refresh
  const handleRefresh = () => {
    fetchKPIsData();
  };
  return (
      <ScrollView 
        style={[styles.wrap, { backgroundColor: colors.background }]}
        contentContainerStyle={styles.scrollContent}
        refreshControl={
          <RefreshControl refreshing={isLoading} onRefresh={handleRefresh} />
        }
      > 
        <View style={styles.header}>
          <Text style={[styles.title, { color: colors.text, fontFamily: fonts.bold }]}>CRM & Sales</Text>
          <TouchableOpacity 
            style={[styles.dataButton, { backgroundColor: colors.primary }]}
            onPress={() => navigation.navigate('ZohoCrmData' 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 && !crmKPIs && (
          <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 comprehensive KPIs data...
            </Text>
          </View>
        )}

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

        {/* No Data State */}
        {!crmKPIs && !isLoading && !hasError && (
          <View style={[styles.errorCard, { borderColor: colors.textLight, backgroundColor: colors.surface, marginBottom: 20 }]}>
            <Icon name="information" size={20} color={colors.textLight} />
            <Text style={[styles.errorText, { color: colors.textLight, fontFamily: fonts.medium }]}>
              No KPIs data available. Pull to refresh.
            </Text>
          </View>
        )}

        {/* Refresh Indicator */}
        {isLoading && crmKPIs && (
          <View style={[styles.refreshIndicator, { backgroundColor: colors.surface, borderColor: colors.border }]}>
            <ActivityIndicator size="small" color={colors.primary} />
            <Text style={[styles.refreshText, { color: colors.textLight, fontFamily: fonts.regular }]}>
              Refreshing data...
            </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 }]}>
              {crmKPIs?.businessOverview?.moduleCounts?.leads || 0}
            </Text>
            <Text style={[styles.heroCardSubtitle, { color: colors.textLight, fontFamily: fonts.regular }]}>
              Total Leads
            </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 }]}>Deals</Text>
            </View>
            <Text style={[styles.heroCardValue, { color: colors.text, fontFamily: fonts.bold }]}>
              {crmKPIs?.businessOverview?.moduleCounts?.deals || 0}
            </Text>
            <Text style={[styles.heroCardSubtitle, { color: colors.textLight, fontFamily: fonts.regular }]}>
              Total Deals
            </Text>
          </View>
        </View>

        {/* Revenue Overview - Large Card */}
        <View style={[styles.revenueCard, { backgroundColor: colors.surface, borderColor: colors.border }]}>
          <View style={styles.revenueHeader}>
            <Icon name="trending-up" size={28} color="#10B981" />
            <Text style={[styles.revenueTitle, { color: colors.text, fontFamily: fonts.bold }]}>Revenue Overview</Text>
          </View>
          <View style={styles.revenueStats}>
            <View style={styles.revenueItem}>
              <Text style={[styles.revenueLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Total Revenue</Text>
              <Text style={[styles.revenueValue, { color: colors.text, fontFamily: fonts.bold }]}>
                {formatCurrency(crmKPIs?.businessOverview?.revenueMetrics?.totalRevenue || 0)}
              </Text>
            </View>
            <View style={styles.revenueItem}>
              <Text style={[styles.revenueLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Pipeline Value</Text>
              <Text style={[styles.revenueValue, { color: colors.primary, fontFamily: fonts.bold }]}>
                {formatCurrency(crmKPIs?.salesPipeline?.totalPipelineValue || 0)}
              </Text>
            </View>
            <View style={styles.revenueItem}>
              <Text style={[styles.revenueLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Avg Invoice</Text>
              <Text style={[styles.revenueValue, { color: colors.text, fontFamily: fonts.bold }]}>
                {formatCurrency(crmKPIs?.businessOverview?.revenueMetrics?.averageInvoiceValue || 0)}
              </Text>
            </View>
          </View>
        </View>

        {/* Module Counts - Compact Grid */}
        <View style={styles.compactGrid}>
          <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 }]}>
              {crmKPIs?.businessOverview?.moduleCounts?.tasks || 0}
            </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="account-group" size={20} color="#8B5CF6" />
            <Text style={[styles.compactValue, { color: colors.text, fontFamily: fonts.bold }]}>
              {crmKPIs?.businessOverview?.moduleCounts?.contacts || 0}
            </Text>
            <Text style={[styles.compactLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Contacts</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 }]}>
              {crmKPIs?.businessOverview?.moduleCounts?.accounts || 0}
            </Text>
            <Text style={[styles.compactLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Accounts</Text>
          </View>
          
          <View style={[styles.compactCard, { backgroundColor: colors.surface, borderColor: colors.border }]}>
            <Icon name="receipt" size={20} color="#22C55E" />
            <Text style={[styles.compactValue, { color: colors.text, fontFamily: fonts.bold }]}>
              {crmKPIs?.businessOverview?.moduleCounts?.invoices || 0}
            </Text>
            <Text style={[styles.compactLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Invoices</Text>
          </View>
          
          <View style={[styles.compactCard, { backgroundColor: colors.surface, borderColor: colors.border }]}>
            <Icon name="shopping" size={20} color="#06B6D4" />
            <Text style={[styles.compactValue, { color: colors.text, fontFamily: fonts.bold }]}>
              {crmKPIs?.businessOverview?.moduleCounts?.salesOrders || 0}
            </Text>
            <Text style={[styles.compactLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Sales Orders</Text>
          </View>
          
          <View style={[styles.compactCard, { backgroundColor: colors.surface, borderColor: colors.border }]}>
            <Icon name="cart" size={20} color="#8B5CF6" />
            <Text style={[styles.compactValue, { color: colors.text, fontFamily: fonts.bold }]}>
              {crmKPIs?.businessOverview?.moduleCounts?.purchaseOrders || 0}
            </Text>
            <Text style={[styles.compactLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Purchase Orders</Text>
          </View>
        </View>

        {/* Sales Pipeline Progress - Progress Bars */}
        <View style={[styles.progressCard, { backgroundColor: colors.surface, borderColor: colors.border }]}>
          <Text style={[styles.progressTitle, { color: colors.text, fontFamily: fonts.bold }]}>Sales Pipeline Progress</Text>
          
          <View style={styles.progressItem}>
            <View style={styles.progressHeader}>
              <Text style={[styles.progressLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Qualified Leads</Text>
              <Text style={[styles.progressValue, { color: colors.text, fontFamily: fonts.bold }]}>
                {crmKPIs?.salesPipeline?.qualifiedLeads || 0}
              </Text>
            </View>
            <View style={[styles.progressBar, { backgroundColor: colors.background }]}>
              <View style={[styles.progressFill, { 
                backgroundColor: '#22C55E', 
                width: `${Math.min(100, ((crmKPIs?.salesPipeline?.qualifiedLeads || 0) / Math.max(1, crmKPIs?.salesPipeline?.totalLeads || 1)) * 100)}%` 
              }]} />
            </View>
          </View>
          
          <View style={styles.progressItem}>
            <View style={styles.progressHeader}>
              <Text style={[styles.progressLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Converted Leads</Text>
              <Text style={[styles.progressValue, { color: colors.text, fontFamily: fonts.bold }]}>
                {crmKPIs?.salesPipeline?.convertedLeads || 0}
              </Text>
            </View>
            <View style={[styles.progressBar, { backgroundColor: colors.background }]}>
              <View style={[styles.progressFill, { 
                backgroundColor: '#3B82F6', 
                width: `${Math.min(100, ((crmKPIs?.salesPipeline?.convertedLeads || 0) / Math.max(1, crmKPIs?.salesPipeline?.totalLeads || 1)) * 100)}%` 
              }]} />
            </View>
          </View>
          
          <View style={styles.progressItem}>
            <View style={styles.progressHeader}>
              <Text style={[styles.progressLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Closed Won Deals</Text>
              <Text style={[styles.progressValue, { color: colors.text, fontFamily: fonts.bold }]}>
                {crmKPIs?.salesPipeline?.closedWonDeals || 0}
              </Text>
            </View>
            <View style={[styles.progressBar, { backgroundColor: colors.background }]}>
              <View style={[styles.progressFill, { 
                backgroundColor: '#10B981', 
                width: `${Math.min(100, ((crmKPIs?.salesPipeline?.closedWonDeals || 0) / Math.max(1, crmKPIs?.salesPipeline?.totalDeals || 1)) * 100)}%` 
              }]} />
            </View>
          </View>
        </View>

        {/* Task Performance - Circular Progress */}
        <View style={[styles.taskCard, { backgroundColor: colors.surface, borderColor: colors.border }]}>
          <Text style={[styles.taskTitle, { color: colors.text, fontFamily: fonts.bold }]}>Task Performance</Text>
          
          <View style={styles.taskStats}>
            <View style={styles.taskStatItem}>
              <View style={[styles.circularProgress, { borderColor: '#10B981' }]}>
                <Text style={[styles.circularValue, { color: colors.text, fontFamily: fonts.bold }]}>
                  {crmKPIs?.operationalEfficiency?.taskCompletionRate || "0%"}
                </Text>
              </View>
              <Text style={[styles.circularLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Completion Rate</Text>
            </View>
            
            <View style={styles.taskStatItem}>
              <View style={[styles.circularProgress, { borderColor: '#EF4444' }]}>
                <Text style={[styles.circularValue, { color: colors.text, fontFamily: fonts.bold }]}>
                  {crmKPIs?.operationalEfficiency?.overdueRate || "0%"}
                </Text>
              </View>
              <Text style={[styles.circularLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Overdue Rate</Text>
            </View>
          </View>
          
          <View style={styles.taskNumbers}>
            <View style={styles.taskNumberItem}>
              <Text style={[styles.taskNumberValue, { color: colors.text, fontFamily: fonts.bold }]}>
                {crmKPIs?.operationalEfficiency?.totalTasks || 0}
              </Text>
              <Text style={[styles.taskNumberLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Total Tasks</Text>
            </View>
            <View style={styles.taskNumberItem}>
              <Text style={[styles.taskNumberValue, { color: colors.text, fontFamily: fonts.bold }]}>
                {crmKPIs?.operationalEfficiency?.completedTasks || 0}
              </Text>
              <Text style={[styles.taskNumberLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Completed</Text>
            </View>
            <View style={styles.taskNumberItem}>
              <Text style={[styles.taskNumberValue, { color: '#EF4444', fontFamily: fonts.bold }]}>
                {crmKPIs?.operationalEfficiency?.overdueTasks || 0}
              </Text>
              <Text style={[styles.taskNumberLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Overdue</Text>
            </View>
          </View>
        </View>

        {/* Key Metrics - Side by Side */}
        <View style={styles.metricsRow}>
          <View style={[styles.metricCard, { backgroundColor: colors.surface, borderColor: colors.border }]}>
            <Icon name="target" size={24} color="#F59E0B" />
            <Text style={[styles.metricValue, { color: colors.text, fontFamily: fonts.bold }]}>
              {crmKPIs?.salesPipeline?.conversionRate || "0%"}
            </Text>
            <Text style={[styles.metricLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Conversion Rate</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 }]}>
              {crmKPIs?.salesPipeline?.winRate || "0%"}
            </Text>
            <Text style={[styles.metricLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Win Rate</Text>
          </View>
        </View>





        {/* Conversion Funnel */}
        <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Sales Conversion Funnel</Text>
          
          <View style={styles.funnelContainer}>
            <View style={styles.funnelStage}>
              <Text style={[styles.funnelStageLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Leads</Text>
              <Text style={[styles.funnelStageValue, { color: colors.text, fontFamily: fonts.bold }]}>
                {crmKPIs?.salesPipeline?.conversionFunnel?.leads?.count || 0}
              </Text>
              <Text style={[styles.funnelStagePercent, { color: colors.textLight, fontFamily: fonts.regular }]}>
                {crmKPIs?.salesPipeline?.conversionFunnel?.leads?.percentage || "0"}%
              </Text>
            </View>
            
            <View style={styles.funnelArrow}>
              <Text style={[styles.funnelArrowText, { color: colors.textLight }]}>→</Text>
            </View>
            
            <View style={styles.funnelStage}>
              <Text style={[styles.funnelStageLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Qualified</Text>
              <Text style={[styles.funnelStageValue, { color: colors.text, fontFamily: fonts.bold }]}>
                {crmKPIs?.salesPipeline?.conversionFunnel?.qualified?.count || 0}
              </Text>
              <Text style={[styles.funnelStagePercent, { color: colors.textLight, fontFamily: fonts.regular }]}>
                {crmKPIs?.salesPipeline?.conversionFunnel?.qualified?.percentage || "0"}%
              </Text>
            </View>
            
            <View style={styles.funnelArrow}>
              <Text style={[styles.funnelArrowText, { color: colors.textLight }]}>→</Text>
            </View>
            
            <View style={styles.funnelStage}>
              <Text style={[styles.funnelStageLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Converted</Text>
              <Text style={[styles.funnelStageValue, { color: colors.text, fontFamily: fonts.bold }]}>
                {crmKPIs?.salesPipeline?.conversionFunnel?.converted?.count || 0}
              </Text>
              <Text style={[styles.funnelStagePercent, { color: colors.textLight, fontFamily: fonts.regular }]}>
                {crmKPIs?.salesPipeline?.conversionFunnel?.converted?.percentage || "0"}%
              </Text>
            </View>
            
            <View style={styles.funnelArrow}>
              <Text style={[styles.funnelArrowText, { color: colors.textLight }]}>→</Text>
            </View>
            
            <View style={styles.funnelStage}>
              <Text style={[styles.funnelStageLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Closed Won</Text>
              <Text style={[styles.funnelStageValue, { color: colors.text, fontFamily: fonts.bold }]}>
                {crmKPIs?.salesPipeline?.conversionFunnel?.closedWon?.count || 0}
              </Text>
              <Text style={[styles.funnelStagePercent, { color: colors.textLight, fontFamily: fonts.regular }]}>
                {crmKPIs?.salesPipeline?.conversionFunnel?.closedWon?.percentage || "0"}%
              </Text>
            </View>
          </View>
        </View>

        {/* Lead Sources Distribution */}
        <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Lead Sources Distribution</Text>
          
          <View style={styles.chartContainer}>
            <PieChart 
              data={Object.entries(crmKPIs?.salesPipeline?.leadSources || {}).map(([source, count]) => ({
                label: source,
                value: Number(count) || 0,
                color: getStatusColor(source)
              }))}
              colors={colors}
              fonts={fonts}
              size={140}
            />
            
            {/* Legend */}
            <View style={styles.pieLegend}>
              {Object.entries(crmKPIs?.salesPipeline?.leadSources || {}).map(([source, count]) => (
                <View key={source} style={styles.legendItem}>
                  <View style={[styles.legendDot, { backgroundColor: getStatusColor(source) }]} />
                  <Text style={[styles.legendText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                    {source} ({Number(count) || 0})
                  </Text>
                </View>
              ))}
            </View>
          </View>
        </View>

        {/* Deal Pipeline Stages - Compact View */}
        <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Deal Pipeline Stages</Text>
          
          <CompactPipeline 
            data={Object.entries(crmKPIs?.salesPipeline?.dealStages || {}).map(([stage, count]) => ({
              label: stage,
              value: Number(count) || 0,
              color: getStatusColor(stage)
            }))}
            colors={colors}
            fonts={fonts}
          />
        </View>

        {/* Leads by Source - Donut Chart */}
        <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Leads by Source</Text>
          
          <View style={styles.chartContainer}>
            <DonutChart 
              data={Object.entries(crmKPIs?.salesPipeline?.leadSources || {}).map(([source, count]) => ({
                label: source,
                value: Number(count) || 0,
                color: getStatusColor(source)
              }))}
              colors={colors}
              fonts={fonts}
              size={140}
            />
            
            {/* Legend */}
            <View style={styles.pieLegend}>
              {Object.entries(crmKPIs?.salesPipeline?.leadSources || {}).map(([source, count]) => (
                <View key={source} style={styles.legendItem}>
                  <View style={[styles.legendDot, { backgroundColor: getStatusColor(source) }]} />
                  <Text style={[styles.legendText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                    {source} ({Number(count) || 0})
                  </Text>
                </View>
              ))}
            </View>
          </View>
        </View>

        {/* Tasks by Priority - Stacked Bar Chart */}
        <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Tasks by Status</Text>
          
          <View style={styles.chartContainer}>
            <StackedBarChart 
              data={Object.entries(crmKPIs?.operationalEfficiency?.taskStatus || {}).map(([status, count]) => ({
                label: status,
                value: Number(count) || 0,
                color: getPriorityColor(status)
              }))}
              colors={colors}
              fonts={fonts}
              height={120}
            />
            
            {/* Legend */}
            <View style={styles.barLegend}>
              {Object.entries(crmKPIs?.operationalEfficiency?.taskStatus || {}).map(([status, count]) => (
                <View key={status} style={styles.legendItem}>
                  <View style={[styles.legendDot, { backgroundColor: getPriorityColor(status) }]} />
                  <Text style={[styles.legendText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                    {status} ({Number(count) || 0})
                  </Text>
                </View>
              ))}
            </View>
          </View>
        </View>

        {/* Sales Orders by Status - Donut Chart */}
        <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Sales Orders by Status</Text>
          
          <View style={styles.chartContainer}>
            <DonutChart 
              data={Object.entries(crmKPIs?.operationalEfficiency?.orderStatus?.salesOrders || {}).map(([status, count]) => ({
                label: status,
                value: Number(count) || 0,
                color: getStatusColor(status)
              }))}
              colors={colors}
              fonts={fonts}
              size={140}
            />
            
            {/* Legend */}
            <View style={styles.pieLegend}>
              {Object.entries(crmKPIs?.operationalEfficiency?.orderStatus?.salesOrders || {}).map(([status, count]) => (
                <View key={status} style={styles.legendItem}>
                  <View style={[styles.legendDot, { backgroundColor: getStatusColor(status) }]} />
                  <Text style={[styles.legendText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                    {status} ({Number(count) || 0})
                  </Text>
                </View>
              ))}
            </View>
          </View>
        </View>

        {/* Purchase Orders by Status - Pie Chart */}
        <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Purchase Orders by Status</Text>
          
          <View style={styles.chartContainer}>
            <PieChart 
              data={Object.entries(crmKPIs?.operationalEfficiency?.orderStatus?.purchaseOrders || {}).map(([status, count]) => ({
                label: status,
                value: Number(count) || 0,
                color: getStatusColor(status)
              }))}
              colors={colors}
              fonts={fonts}
              size={140}
            />
            
            {/* Legend */}
            <View style={styles.pieLegend}>
              {Object.entries(crmKPIs?.operationalEfficiency?.orderStatus?.purchaseOrders || {}).map(([status, count]) => (
                <View key={status} style={styles.legendItem}>
                  <View style={[styles.legendDot, { backgroundColor: getStatusColor(status) }]} />
                  <Text style={[styles.legendText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                    {status} ({Number(count) || 0})
                  </Text>
                </View>
              ))}
            </View>
          </View>
        </View>

        {/* Invoices by Status - Stacked Bar Chart */}
        <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Invoices by Status</Text>
          
          <View style={styles.chartContainer}>
            <StackedBarChart 
              data={Object.entries(crmKPIs?.operationalEfficiency?.invoiceStatus || {}).map(([status, count]) => ({
                label: status,
                value: Number(count) || 0,
                color: getStatusColor(status)
              }))}
              colors={colors}
              fonts={fonts}
              height={120}
            />
            
            {/* Legend */}
            <View style={styles.barLegend}>
              {Object.entries(crmKPIs?.operationalEfficiency?.invoiceStatus || {}).map(([status, count]) => (
                <View key={status} style={styles.legendItem}>
                  <View style={[styles.legendDot, { backgroundColor: getStatusColor(status) }]} />
                  <Text style={[styles.legendText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                    {status} ({Number(count) || 0})
                  </Text>
                </View>
              ))}
            </View>
          </View>
        </View>

        {/* Advanced Financial KPIs */}
        <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Advanced Financial KPIs</Text>
          
          <View style={styles.financialKPIsGrid}>
            <View style={styles.financialKPIItem}>
              <Text style={[styles.financialKPILabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Revenue Growth Rate</Text>
              <Text style={[styles.financialKPIValue, { color: colors.text, fontFamily: fonts.bold }]}>
                {crmKPIs?.advancedFinancialKPIs?.revenueGrowthRate?.percentage || "0%"}
              </Text>
              <Text style={[styles.financialKPIDesc, { color: colors.textLight, fontFamily: fonts.regular }]}>
                {crmKPIs?.advancedFinancialKPIs?.revenueGrowthRate?.trend || "stable"} trend
              </Text>
            </View>
            
            <View style={styles.financialKPIItem}>
              <Text style={[styles.financialKPILabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Gross Margin</Text>
              <Text style={[styles.financialKPIValue, { color: colors.primary, fontFamily: fonts.bold }]}>
                {crmKPIs?.advancedFinancialKPIs?.grossMargin?.percentage || "0%"}
              </Text>
              <Text style={[styles.financialKPIDesc, { color: colors.textLight, fontFamily: fonts.regular }]}>
                {formatCurrency(crmKPIs?.advancedFinancialKPIs?.grossMargin?.grossProfit || 0)} profit
              </Text>
            </View>
            
            <View style={styles.financialKPIItem}>
              <Text style={[styles.financialKPILabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Net Profit Margin</Text>
              <Text style={[styles.financialKPIValue, { color: '#22C55E', fontFamily: fonts.bold }]}>
                {crmKPIs?.advancedFinancialKPIs?.netProfitMargin?.percentage || "0%"}
              </Text>
              <Text style={[styles.financialKPIDesc, { color: colors.textLight, fontFamily: fonts.regular }]}>
                {formatCurrency(crmKPIs?.advancedFinancialKPIs?.netProfitMargin?.netProfit || 0)} net profit
              </Text>
            </View>
            
            <View style={styles.financialKPIItem}>
              <Text style={[styles.financialKPILabel, { color: colors.textLight, fontFamily: fonts.regular }]}>EBITDA</Text>
              <Text style={[styles.financialKPIValue, { color: '#10B981', fontFamily: fonts.bold }]}>
                {formatCurrency(crmKPIs?.advancedFinancialKPIs?.ebitda?.value || 0)}
              </Text>
              <Text style={[styles.financialKPIDesc, { color: colors.textLight, fontFamily: fonts.regular }]}>
                {crmKPIs?.advancedFinancialKPIs?.ebitda?.margin || "0%"} margin
              </Text>
            </View>
            
            <View style={styles.financialKPIItem}>
              <Text style={[styles.financialKPILabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Cash Runway</Text>
              <Text style={[styles.financialKPIValue, { color: crmKPIs?.advancedFinancialKPIs?.cashRunway?.status === 'critical' ? '#EF4444' : '#22C55E', fontFamily: fonts.bold }]}>
                {crmKPIs?.advancedFinancialKPIs?.cashRunway?.months || "0"} months
              </Text>
              <Text style={[styles.financialKPIDesc, { color: colors.textLight, fontFamily: fonts.regular }]}>
                {crmKPIs?.advancedFinancialKPIs?.cashRunway?.status || "unknown"} status
              </Text>
            </View>
            
            <View style={styles.financialKPIItem}>
              <Text style={[styles.financialKPILabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Days Sales Outstanding</Text>
              <Text style={[styles.financialKPIValue, { color: crmKPIs?.advancedFinancialKPIs?.daysSalesOutstanding?.status === 'needs_attention' ? '#EF4444' : '#22C55E', fontFamily: fonts.bold }]}>
                {crmKPIs?.advancedFinancialKPIs?.daysSalesOutstanding?.days || 0} days
              </Text>
              <Text style={[styles.financialKPIDesc, { color: colors.textLight, fontFamily: fonts.regular }]}>
                {crmKPIs?.advancedFinancialKPIs?.daysSalesOutstanding?.status || "unknown"} status
              </Text>
            </View>
          </View>
        </View>

        {/* Business Health Score */}
        {crmKPIs?.businessInsights?.businessHealth && (
          <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Business Health Score</Text>
            
            <View style={styles.healthScoreContainer}>
              <View style={styles.healthScoreMain}>
                <Text style={[styles.healthScoreValue, { color: colors.primary, fontFamily: fonts.bold }]}>
                  {crmKPIs.businessInsights.businessHealth.overallScore}/100
                </Text>
                <Text style={[styles.healthScoreLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>
                  Overall Score
                </Text>
              </View>
              
              <View style={styles.healthScoreBreakdown}>
                <View style={styles.healthScoreItem}>
                  <Text style={[styles.healthScoreItemLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Lead Generation</Text>
                  <Text style={[styles.healthScoreItemValue, { color: colors.text, fontFamily: fonts.bold }]}>
                    {crmKPIs.businessInsights.businessHealth.leadGeneration}%
                  </Text>
                </View>
                <View style={styles.healthScoreItem}>
                  <Text style={[styles.healthScoreItemLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Process Efficiency</Text>
                  <Text style={[styles.healthScoreItemValue, { color: colors.text, fontFamily: fonts.bold }]}>
                    {crmKPIs.businessInsights.businessHealth.processEfficiency}%
                  </Text>
                </View>
                <View style={styles.healthScoreItem}>
                  <Text style={[styles.healthScoreItemLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Quality Metrics</Text>
                  <Text style={[styles.healthScoreItemValue, { color: colors.text, fontFamily: fonts.bold }]}>
                    {crmKPIs.businessInsights.businessHealth.qualityMetrics}%
                  </Text>
                </View>
              </View>
            </View>
          </View>
        )}

        {/* Industry Distribution */}
        {crmKPIs?.customerRelationships?.industryDistribution && (
          <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Industry Distribution</Text>
            
            <View style={styles.chartContainer}>
              <DonutChart 
                data={Object.entries(crmKPIs.customerRelationships.industryDistribution).map(([industry, count]) => ({
                  label: industry,
                  value: Number(count) || 0,
                  color: getStatusColor(industry)
                }))}
                colors={colors}
                fonts={fonts}
                size={140}
              />
              
              {/* Legend */}
              <View style={styles.pieLegend}>
                {Object.entries(crmKPIs.customerRelationships.industryDistribution).map(([industry, count]) => (
                  <View key={industry} style={styles.legendItem}>
                    <View style={[styles.legendDot, { backgroundColor: getStatusColor(industry) }]} />
                    <Text style={[styles.legendText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                      {industry} ({Number(count) || 0})
                    </Text>
                  </View>
                ))}
              </View>
            </View>
          </View>
        )}

        {/* Revenue Trends - Only show months with revenue */}
        {crmKPIs?.businessOverview?.revenueMetrics?.revenueByMonth && (
          <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Revenue Trends</Text>
            
            <View style={styles.revenueTrendsContainer}>
              {crmKPIs.businessOverview.revenueMetrics.revenueByMonth
                .filter((month: any) => month.revenue > 0)
                .slice(-6)
                .map((month: any, index: number) => (
                <View key={month.month} style={styles.revenueTrendItem}>
                  <Text style={[styles.revenueTrendMonth, { color: colors.textLight, fontFamily: fonts.regular }]}>
                    {new Date(month.month).toLocaleDateString('en-US', { month: 'short', year: '2-digit' })}
                  </Text>
                  <Text style={[styles.revenueTrendValue, { color: colors.text, fontFamily: fonts.bold }]}>
                    {formatCurrency(month.revenue)}
                  </Text>
                </View>
              ))}
              {crmKPIs.businessOverview.revenueMetrics.revenueByMonth.filter((month: any) => month.revenue > 0).length === 0 && (
                <Text style={[styles.emptyText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                  No revenue data available for the selected period
                </Text>
              )}
            </View>
          </View>
        )}

        {/* Top Revenue Accounts */}
        <View style={styles.row}> 
          <View style={[styles.card, styles.col, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Top Revenue Accounts</Text>
            {crmKPIs?.businessOverview?.revenueMetrics?.topRevenueAccounts?.length > 0 ? crmKPIs.businessOverview.revenueMetrics.topRevenueAccounts.slice(0, 5).map((account: any, index: number) => (
              <View key={account.account} style={styles.listRow}>
                <Text style={[styles.listPrimary, { color: colors.text, fontFamily: fonts.regular }]} numberOfLines={1}>
                  {account.account}
                </Text>
                <Text style={[styles.listSecondary, { color: colors.primary, fontFamily: fonts.bold }]}>
                  {formatCurrency(account.revenue)}
                </Text>
              </View>
            )) : (
              <Text style={[styles.emptyText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                No revenue data available
              </Text>
            )}
          </View>
          <View style={[styles.card, styles.col, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Top Performing Sources</Text>
            {crmKPIs?.businessInsights?.topPerformingSources?.length > 0 ? crmKPIs.businessInsights.topPerformingSources.slice(0, 5).map((source: any, index: number) => (
              <View key={source.source} style={styles.listRow}>
                <Text style={[styles.listPrimary, { color: colors.text, fontFamily: fonts.regular }]} numberOfLines={1}>
                  {source.source}
                </Text>
                <Text style={[styles.listSecondary, { color: colors.textLight, fontFamily: fonts.regular }]} numberOfLines={1}>
                  {source.totalLeads} leads · {source.avgQuality}% quality
                </Text>
              </View>
            )) : (
              <Text style={[styles.emptyText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                No source data available
              </Text>
            )}
          </View>
        </View>

        {/* Recommendations */}
        {crmKPIs?.businessInsights?.recommendations && crmKPIs.businessInsights.recommendations.length > 0 && (
          <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Business Recommendations</Text>
            
            {crmKPIs.businessInsights.recommendations.map((recommendation: any, index: number) => (
              <View key={index} style={styles.recommendationItem}>
                <View style={styles.recommendationHeader}>
                  <Text style={[styles.recommendationTitle, { color: colors.text, fontFamily: fonts.bold }]}>
                    {recommendation.title}
                  </Text>
                  <View style={[
                    styles.recommendationPriority, 
                    { backgroundColor: recommendation.priority === 'High' ? colors.error : recommendation.priority === 'Medium' ? '#F59E0B' : '#22C55E' }
                  ]}>
                    <Text style={[styles.recommendationPriorityText, { color: colors.surface, fontFamily: fonts.medium }]}>
                      {recommendation.priority}
                    </Text>
                  </View>
                </View>
                <Text style={[styles.recommendationDescription, { color: colors.textLight, fontFamily: fonts.regular }]}>
                  {recommendation.description}
                </Text>
                <Text style={[styles.recommendationAction, { color: colors.primary, fontFamily: fonts.medium }]}>
                  Action: {recommendation.action}
                </Text>
              </View>
            ))}
          </View>
        )}
      </ScrollView>
  );
};

const styles = StyleSheet.create({
  wrap: { flex: 1, padding: 16 },
  scrollContent: { paddingBottom: 20 },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 8,
  },
  title: { fontSize: 18 },
  dataButton: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 20,
  },
  dataButtonText: {
    marginLeft: 6,
    fontSize: 14,
  },
  errorCard: {
    borderRadius: 12,
    borderWidth: 1,
    padding: 12,
    marginTop: 12,
    flexDirection: 'row',
    alignItems: 'center',
  },
  errorText: {
    marginLeft: 8,
    fontSize: 14,
    flex: 1,
  },
  loadingCard: {
    borderRadius: 12,
    borderWidth: 1,
    padding: 20,
    marginTop: 12,
    alignItems: 'center',
    justifyContent: 'center',
  },
  loadingText: {
    marginTop: 12,
    fontSize: 14,
    textAlign: 'center',
  },
  refreshIndicator: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 12,
    marginBottom: 16,
    borderRadius: 8,
    borderWidth: 1,
  },
  refreshText: {
    marginLeft: 8,
    fontSize: 14,
  },
  kpiGrid: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-between' },
  kpiCard: { width: '48%', borderRadius: 12, borderWidth: 1, borderColor: '#E2E8F0', backgroundColor: '#FFFFFF', padding: 12, marginBottom: 12 },
  kpiLabel: { fontSize: 12, opacity: 0.8 },
  kpiValueRow: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginTop: 8 },
  card: { borderRadius: 12, borderWidth: 1, padding: 12, marginTop: 12 },
  cardTitle: { fontSize: 16, marginBottom: 8 },
  bars: { flexDirection: 'row', alignItems: 'flex-end' },
  bar: { flex: 1, marginRight: 6, borderTopLeftRadius: 4, borderTopRightRadius: 4 },
  legendRow: { flexDirection: 'row', flexWrap: 'wrap', marginTop: 8 },
  legendItem: { flexDirection: 'row', alignItems: 'center', marginRight: 12, marginTop: 6 },
  legendDot: { width: 8, height: 8, borderRadius: 4, marginRight: 6 },
  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,
  },
  legendText: {
    fontSize: 12,
  },
  row: {  marginTop: 12 },
  col: { flex: 1, marginRight: 8 },
  listRow: { flexDirection: 'row', justifyContent: 'space-between', paddingVertical: 10, borderBottomWidth: StyleSheet.hairlineWidth, borderColor: '#E5E7EB' },
  listPrimary: { fontSize: 14, flex: 1, paddingRight: 8 },
  listSecondary: { fontSize: 12 },
  emptyText: { 
    fontSize: 14, 
    textAlign: 'center', 
    paddingVertical: 20,
    fontStyle: 'italic'
  },
  kpiSummaryGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
    marginTop: 8,
  },
  kpiSummaryItem: {
    width: '48%',
    marginBottom: 16,
    padding: 12,
    backgroundColor: '#F8F9FA',
    borderRadius: 8,
  },
  kpiSummaryLabel: {
    fontSize: 12,
    marginBottom: 4,
  },
  kpiSummaryValue: {
    fontSize: 18,
    marginBottom: 4,
  },
  kpiSummaryDesc: {
    fontSize: 11,
    lineHeight: 14,
  },
  healthScoreContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 8,
  },
  healthScoreMain: {
    alignItems: 'center',
    marginRight: 24,
  },
  healthScoreValue: {
    fontSize: 32,
    marginBottom: 4,
  },
  healthScoreLabel: {
    fontSize: 12,
  },
  healthScoreBreakdown: {
    flex: 1,
  },
  healthScoreItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 8,
  },
  healthScoreItemLabel: {
    fontSize: 12,
    flex: 1,
  },
  healthScoreItemValue: {
    fontSize: 14,
  },
  revenueTrendsContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginTop: 8,
  },
  revenueTrendItem: {
    width: '33%',
    alignItems: 'center',
    marginBottom: 12,
  },
  revenueTrendMonth: {
    fontSize: 12,
    marginBottom: 4,
  },
  revenueTrendValue: {
    fontSize: 14,
  },
  recommendationItem: {
    marginBottom: 16,
    paddingBottom: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#E5E7EB',
  },
  recommendationHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 8,
  },
  recommendationTitle: {
    fontSize: 14,
    flex: 1,
    marginRight: 8,
  },
  recommendationPriority: {
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 12,
  },
  recommendationPriorityText: {
    fontSize: 10,
  },
  recommendationDescription: {
    fontSize: 12,
    marginBottom: 8,
    lineHeight: 16,
  },
  recommendationAction: {
    fontSize: 12,
    fontStyle: 'italic',
  },
  funnelContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginTop: 8,
    paddingHorizontal: 8,
  },
  funnelStage: {
    alignItems: 'center',
    flex: 1,
  },
  funnelStageLabel: {
    fontSize: 12,
    marginBottom: 4,
  },
  funnelStageValue: {
    fontSize: 18,
    marginBottom: 2,
  },
  funnelStagePercent: {
    fontSize: 10,
  },
  funnelArrow: {
    marginHorizontal: 8,
    alignItems: 'center',
    justifyContent: 'center',
  },
  funnelArrowText: {
    fontSize: 16,
  },
  financialKPIsGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
    marginTop: 8,
  },
  financialKPIItem: {
    width: '48%',
    marginBottom: 16,
    padding: 12,
    backgroundColor: '#F8F9FA',
    borderRadius: 8,
  },
  financialKPILabel: {
    fontSize: 12,
    marginBottom: 4,
  },
  financialKPIValue: {
    fontSize: 16,
    marginBottom: 4,
  },
  financialKPIDesc: {
    fontSize: 10,
    lineHeight: 12,
  },
  dealStagesGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
    marginTop: 8,
  },
  dealStageItem: {
    width: '48%',
    marginBottom: 12,
    padding: 8,
    backgroundColor: '#F8F9FA',
    borderRadius: 6,
  },
  dealStageLabel: {
    fontSize: 12,
    marginBottom: 4,
  },
  dealStageValue: {
    fontSize: 16,
  },
  leadSourcesGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
    marginTop: 8,
  },
  leadSourceItem: {
    width: '48%',
    marginBottom: 12,
    padding: 8,
    backgroundColor: '#F8F9FA',
    borderRadius: 6,
  },
  leadSourceLabel: {
    fontSize: 12,
    marginBottom: 4,
  },
  leadSourceValue: {
    fontSize: 16,
  },
  // Hero Stats Styles
  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,
  },
  // Revenue Card Styles
  revenueCard: {
    padding: 20,
    borderRadius: 16,
    borderWidth: 1,
    marginBottom: 16,
  },
  revenueHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 16,
  },
  revenueTitle: {
    fontSize: 20,
    marginLeft: 12,
  },
  revenueStats: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  revenueItem: {
    flex: 1,
    alignItems: 'center',
  },
  revenueLabel: {
    fontSize: 12,
    marginBottom: 4,
  },
  revenueValue: {
    fontSize: 18,
  },
  // Compact Grid Styles
  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',
  },
  // Progress Card Styles
  progressCard: {
    padding: 16,
    borderRadius: 12,
    borderWidth: 1,
    marginBottom: 16,
  },
  progressTitle: {
    fontSize: 16,
    marginBottom: 16,
  },
  progressItem: {
    marginBottom: 12,
  },
  progressHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 6,
  },
  progressLabel: {
    fontSize: 14,
  },
  progressValue: {
    fontSize: 14,
  },
  progressBar: {
    height: 8,
    borderRadius: 4,
    overflow: 'hidden',
  },
  progressFill: {
    height: '100%',
    borderRadius: 4,
  },
  // Task Card Styles
  taskCard: {
    padding: 16,
    borderRadius: 12,
    borderWidth: 1,
    marginBottom: 16,
  },
  taskTitle: {
    fontSize: 16,
    marginBottom: 16,
  },
  taskStats: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginBottom: 16,
  },
  taskStatItem: {
    alignItems: 'center',
  },
  circularProgress: {
    width: 60,
    height: 60,
    borderRadius: 30,
    borderWidth: 4,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 8,
  },
  circularValue: {
    fontSize: 12,
  },
  circularLabel: {
    fontSize: 10,
    textAlign: 'center',
  },
  taskNumbers: {
    flexDirection: 'row',
    justifyContent: 'space-around',
  },
  taskNumberItem: {
    alignItems: 'center',
  },
  taskNumberValue: {
    fontSize: 18,
    marginBottom: 4,
  },
  taskNumberLabel: {
    fontSize: 12,
  },
  // Metrics Row Styles
  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',
  },
});

// Helper functions for color coding
const getStatusColor = (status: string): string => {
  // Define a comprehensive color palette with distinct colors
  const colorPalette = [
    '#3B82F6', // Bright Blue
    '#8B5CF6', // Purple
    '#06B6D4', // Cyan
    '#F59E0B', // Amber
    '#10B981', // Emerald
    '#F97316', // Orange
    '#22C55E', // Green
    '#84CC16', // Lime
    '#14B8A6', // Teal
    '#059669', // Dark Green
    '#EF4444', // Red
    '#DC2626', // Dark Red
    '#991B1B', // Darker Red
    '#9CA3AF', // Gray
    '#EC4899', // Pink
    '#8B5A2B', // Brown
    '#B91C1C', // Lost Red
    '#16A34A', // Success Green
    '#6366F1', // Indigo
    '#7C3AED', // Violet
    '#0891B2', // Sky Blue
    '#CA8A04', // Gold
    '#1F2937', // Dark Gray
    '#BE185D', // Rose
    '#0D9488', // Emerald Dark
    '#7C2D12', // Brown Dark
    '#1E40AF', // Blue Dark
    '#C2410C', // Orange Dark
    '#9333EA', // Purple Dark
    '#059669', // Green Dark
  ];

  // Create a consistent hash from the status string
  let hash = 0;
  const normalizedStatus = status.toLowerCase().trim();
  for (let i = 0; i < normalizedStatus.length; i++) {
    const char = normalizedStatus.charCodeAt(i);
    hash = ((hash << 5) - hash) + char;
    hash = hash & hash; // Convert to 32-bit integer
  }
  
  // Ensure positive index and get color from palette
  const colorIndex = Math.abs(hash) % colorPalette.length;
  return colorPalette[colorIndex];
};

const getPriorityColor = (priority: string): string => {
  // Define a comprehensive color palette with distinct colors for priorities
  const colorPalette = [
    '#DC2626', // Dark Red
    '#B91C1C', // Urgent Red
    '#991B1B', // Critical Dark Red
    '#F59E0B', // Amber
    '#10B981', // Emerald
    '#059669', // Dark Green
    '#16A34A', // Success Green
    '#9CA3AF', // Gray
    '#6B7280', // Light Gray
    '#6366F1', // Indigo
    '#EF4444', // Red
    '#8B5CF6', // Purple
    '#06B6D4', // Cyan
    '#F97316', // Orange
    '#22C55E', // Green
    '#84CC16', // Lime
    '#14B8A6', // Teal
    '#EC4899', // Pink
    '#8B5A2B', // Brown
    '#7C3AED', // Violet
    '#0891B2', // Sky Blue
    '#CA8A04', // Gold
    '#1F2937', // Dark Gray
    '#BE185D', // Rose
    '#0D9488', // Emerald Dark
    '#7C2D12', // Brown Dark
    '#1E40AF', // Blue Dark
    '#C2410C', // Orange Dark
    '#9333EA', // Purple Dark
    '#3B82F6', // Info Blue
    '#0077B5', // LinkedIn Blue
  ];

  // Create a consistent hash from the priority string
  let hash = 0;
  const normalizedPriority = priority.toLowerCase().trim();
  for (let i = 0; i < normalizedPriority.length; i++) {
    const char = normalizedPriority.charCodeAt(i);
    hash = ((hash << 5) - hash) + char;
    hash = hash & hash; // Convert to 32-bit integer
  }
  
  // Ensure positive index and get color from palette
  const colorIndex = Math.abs(hash) % colorPalette.length;
  return colorPalette[colorIndex];
};

// Helper function to format currency values safely
const formatCurrency = (value: number | undefined | null): string => {
  if (value === undefined || value === null || isNaN(value)) {
    return '$0';
  }
  
  if (value >= 1000000) {
    return `$${(value / 1000000).toFixed(1)}M`;
  } else if (value >= 1000) {
    return `$${Math.round(value / 1000)}K`;
  } else {
    return `$${Math.round(value)}`;
  }
};

export default CrmDashboardScreen;

// UI helpers
const Kpi: React.FC<{ label: string; value: string; color: string; fonts: any; accent: string }> = ({ label, value, color, fonts, accent }) => (
  <View style={styles.kpiCard}>
    <Text style={[styles.kpiLabel, { color, fontFamily: fonts.regular }]}>{label}</Text>
    <View style={styles.kpiValueRow}>
      <Text style={{ color, fontSize: 20, fontFamily: fonts.bold }}>{value}</Text>
      <View style={{ width: 10, height: 10, borderRadius: 5, backgroundColor: accent }} />
    </View>
  </View>
);

const Bars: React.FC<{ data: number[]; max: number; color: string }> = ({ data, max, color }) => (
  <View style={styles.bars}>
    {data.map((v, i) => (
      <View key={i} style={[styles.bar, { height: Math.max(6, (v / Math.max(1, max)) * 64), backgroundColor: color }]} />
    ))}
  </View>
);

const Stacked: React.FC<{ segments: { label: string; value: number; color: string }[]; total: number }> = ({ segments, total }) => (
  <View style={{ height: 12, borderRadius: 8, backgroundColor: '#E5E7EB', overflow: 'hidden', flexDirection: 'row', marginTop: 8 }}>
    {segments.map(s => (
      <View key={s.label} style={{ width: `${(s.value / Math.max(1, total)) * 100}%`, backgroundColor: s.color }} />
    ))}
  </View>
);


