import React, { useEffect } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, RefreshControl, ScrollView } 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 { fetchAllCrmData } from '../store/crmSlice';
import { 
  selectDashboardData, 
  selectIsAnyLoading, 
  selectHasAnyError,
  selectCrmStats
} 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 dashboardData = useSelector(selectDashboardData);
  const crmStats = useSelector(selectCrmStats);
  const isLoading = useSelector(selectIsAnyLoading);
  const hasError = useSelector(selectHasAnyError);

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

  // Handle refresh
  const handleRefresh = () => {
    dispatch(fetchAllCrmData());
  };
  return (
    <Container>
      <ScrollView 
        style={[styles.wrap, { backgroundColor: colors.background }]}
        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>

        {/* Error State */}
        {hasError && (
          <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 CRM data. Pull to refresh.
            </Text>
          </View>
        )}

        {/* KPIs */}
        <View style={styles.kpiGrid}>
          <Kpi 
            label="Total Leads" 
            value={String(crmStats.leads.total)} 
            color={colors.text} 
            fonts={fonts} 
            accent="#3AA0FF" 
          />
          <Kpi 
            label="Active Tasks" 
            value={String(crmStats.tasks.total - crmStats.tasks.completed)} 
            color={colors.text} 
            fonts={fonts} 
            accent="#6366F1" 
          />
          <Kpi 
            label="Won Deals" 
            value={String(crmStats.deals.won)} 
            color={colors.text} 
            fonts={fonts} 
            accent="#10B981" 
          />
          <Kpi 
            label="Pipeline Value" 
            value={formatCurrency(crmStats.deals.pipelineValue)} 
            color={colors.text} 
            fonts={fonts} 
            accent="#F59E0B" 
          />
        </View>

        {/* Additional Stats Row */}
        <View style={styles.kpiGrid}>
          <Kpi 
            label="New Leads" 
            value={String(crmStats.leads.new)} 
            color={colors.text} 
            fonts={fonts} 
            accent="#22C55E" 
          />
          <Kpi 
            label="Overdue Tasks" 
            value={String(crmStats.tasks.overdue)} 
            color={colors.text} 
            fonts={fonts} 
            accent="#EF4444" 
          />
          <Kpi 
            label="Active Contacts" 
            value={String(crmStats.contacts.active)} 
            color={colors.text} 
            fonts={fonts} 
            accent="#8B5CF6" 
          />
          <Kpi 
            label="Avg Deal Size" 
            value={formatCurrency(crmStats.deals.averageDealSize)} 
            color={colors.text} 
            fonts={fonts} 
            accent="#06B6D4" 
          />
        </View>

        {/* Sales Orders & Purchase Orders Row */}
        <View style={styles.kpiGrid}>
          <Kpi 
            label="Sales Orders" 
            value={String(crmStats.salesOrders.total)} 
            color={colors.text} 
            fonts={fonts} 
            accent="#3B82F6" 
          />
          <Kpi 
            label="Sales Value" 
            value={formatCurrency(crmStats.salesOrders.totalValue)} 
            color={colors.text} 
            fonts={fonts} 
            accent="#10B981" 
          />
          <Kpi 
            label="Purchase Orders" 
            value={String(crmStats.purchaseOrders.total)} 
            color={colors.text} 
            fonts={fonts} 
            accent="#F59E0B" 
          />
          <Kpi 
            label="Purchase Value" 
            value={formatCurrency(crmStats.purchaseOrders.totalValue)} 
            color={colors.text} 
            fonts={fonts} 
            accent="#EF4444" 
          />
        </View>

        {/* Invoices Row */}
        <View style={styles.kpiGrid}>
          <Kpi 
            label="Total Invoices" 
            value={String(crmStats.invoices.total)} 
            color={colors.text} 
            fonts={fonts} 
            accent="#8B5CF6" 
          />
          <Kpi 
            label="Invoice Value" 
            value={formatCurrency(crmStats.invoices.totalValue)} 
            color={colors.text} 
            fonts={fonts} 
            accent="#06B6D4" 
          />
          <Kpi 
            label="Overdue Invoices" 
            value={String(crmStats.invoices.overdue)} 
            color={colors.text} 
            fonts={fonts} 
            accent="#EF4444" 
          />
          <Kpi 
            label="Paid Invoices" 
            value={String(crmStats.invoices.paid)} 
            color={colors.text} 
            fonts={fonts} 
            accent="#22C55E" 
          />
        </View>

        {/* Customer & Sales KPIs Row 1 */}
        <View style={styles.kpiGrid}>
          <Kpi 
            label="Sales Cycle (Days)" 
            value={String(crmStats.customerKPIs.salesCycleLength)} 
            color={colors.text} 
            fonts={fonts} 
            accent="#3B82F6" 
          />
          <Kpi 
            label="Avg Revenue/Account" 
            value={formatCurrency(crmStats.customerKPIs.averageRevenuePerAccount)} 
            color={colors.text} 
            fonts={fonts} 
            accent="#10B981" 
          />
          <Kpi 
            label="Churn Rate" 
            value={`${crmStats.customerKPIs.churnRate}%`} 
            color={colors.text} 
            fonts={fonts} 
            accent="#EF4444" 
          />
          <Kpi 
            label="Customer LTV" 
            value={formatCurrency(crmStats.customerKPIs.customerLifetimeValue)} 
            color={colors.text} 
            fonts={fonts} 
            accent="#8B5CF6" 
          />
        </View>

        {/* Customer & Sales KPIs Row 2 */}
        <View style={styles.kpiGrid}>
          <Kpi 
            label="LTV/CAC Ratio" 
            value={String(crmStats.customerKPIs.ltvToCacRatio)} 
            color={colors.text} 
            fonts={fonts} 
            accent="#F59E0B" 
          />
          <Kpi 
            label="Retention Rate" 
            value={`${crmStats.customerKPIs.customerRetentionRate}%`} 
            color={colors.text} 
            fonts={fonts} 
            accent="#22C55E" 
          />
          <Kpi 
            label="Conversion Rate" 
            value={`${crmStats.customerKPIs.conversionRate}%`} 
            color={colors.text} 
            fonts={fonts} 
            accent="#06B6D4" 
          />
          <Kpi 
            label="Win Rate" 
            value={`${crmStats.customerKPIs.winRate}%`} 
            color={colors.text} 
            fonts={fonts} 
            accent="#10B981" 
          />
        </View>

        {/* Lead Status Distribution - Pie Chart */}
        <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={Object.entries(crmStats.leads.byStatus).map(([status, count]) => ({
                label: status,
                value: count,
                color: getStatusColor(status)
              }))}
              colors={colors}
              fonts={fonts}
              size={140}
            />
            
            {/* Legend */}
            <View style={styles.pieLegend}>
              {Object.entries(crmStats.leads.byStatus).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} ({count})
                  </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={dashboardData.pipeline.map(stage => ({
              label: stage.label,
              value: stage.value,
              color: stage.color
            }))}
            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={dashboardData.sourceDist.map(source => ({
                label: source.label,
                value: source.value,
                color: source.color
              }))}
              colors={colors}
              fonts={fonts}
              size={140}
            />
            
            {/* Legend */}
            <View style={styles.pieLegend}>
              {dashboardData.sourceDist.map(source => (
                <View key={source.label} style={styles.legendItem}>
                  <View style={[styles.legendDot, { backgroundColor: source.color }]} />
                  <Text style={[styles.legendText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                    {source.label} ({source.value})
                  </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 Priority</Text>
          
          <View style={styles.chartContainer}>
            <StackedBarChart 
              data={Object.entries(crmStats.tasks.byPriority).map(([priority, count]) => ({
                label: priority,
                value: count,
                color: getPriorityColor(priority)
              }))}
              colors={colors}
              fonts={fonts}
              height={120}
            />
            
            {/* Legend */}
            <View style={styles.barLegend}>
              {Object.entries(crmStats.tasks.byPriority).map(([priority, count]) => (
                <View key={priority} style={styles.legendItem}>
                  <View style={[styles.legendDot, { backgroundColor: getPriorityColor(priority) }]} />
                  <Text style={[styles.legendText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                    {priority} ({count})
                  </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(crmStats.salesOrders.byStatus).map(([status, count]) => ({
                label: status,
                value: count,
                color: getStatusColor(status)
              }))}
              colors={colors}
              fonts={fonts}
              size={140}
            />
            
            {/* Legend */}
            <View style={styles.pieLegend}>
              {Object.entries(crmStats.salesOrders.byStatus).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} ({count})
                  </Text>
                </View>
              ))}
            </View>
          </View>
        </View>

        {/* Purchase Orders by Vendor - 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 Vendor</Text>
          
          <View style={styles.chartContainer}>
            <PieChart 
              data={Object.entries(crmStats.purchaseOrders.byVendor).map(([vendor, count]) => ({
                label: vendor,
                value: count,
                color: getStatusColor(vendor)
              }))}
              colors={colors}
              fonts={fonts}
              size={140}
            />
            
            {/* Legend */}
            <View style={styles.pieLegend}>
              {Object.entries(crmStats.purchaseOrders.byVendor).map(([vendor, count]) => (
                <View key={vendor} style={styles.legendItem}>
                  <View style={[styles.legendDot, { backgroundColor: getStatusColor(vendor) }]} />
                  <Text style={[styles.legendText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                    {vendor} ({count})
                  </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(crmStats.invoices.byStatus).map(([status, count]) => ({
                label: status,
                value: count,
                color: getStatusColor(status)
              }))}
              colors={colors}
              fonts={fonts}
              height={120}
            />
            
            {/* Legend */}
            <View style={styles.barLegend}>
              {Object.entries(crmStats.invoices.byStatus).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} ({count})
                  </Text>
                </View>
              ))}
            </View>
          </View>
        </View>

        {/* Customer & Sales KPIs Summary */}
        <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Customer & Sales KPIs Summary</Text>
          
          <View style={styles.kpiSummaryGrid}>
            <View style={styles.kpiSummaryItem}>
              <Text style={[styles.kpiSummaryLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Sales Cycle Length</Text>
              <Text style={[styles.kpiSummaryValue, { color: colors.text, fontFamily: fonts.bold }]}>
                {crmStats.customerKPIs.salesCycleLength} days
              </Text>
              <Text style={[styles.kpiSummaryDesc, { color: colors.textLight, fontFamily: fonts.regular }]}>
                Avg. time from first touch to close
              </Text>
            </View>
            
            <View style={styles.kpiSummaryItem}>
              <Text style={[styles.kpiSummaryLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Customer LTV</Text>
              <Text style={[styles.kpiSummaryValue, { color: colors.primary, fontFamily: fonts.bold }]}>
                {formatCurrency(crmStats.customerKPIs.customerLifetimeValue)}
              </Text>
              <Text style={[styles.kpiSummaryDesc, { color: colors.textLight, fontFamily: fonts.regular }]}>
                Average lifetime value per customer
              </Text>
            </View>
            
            <View style={styles.kpiSummaryItem}>
              <Text style={[styles.kpiSummaryLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>LTV/CAC Ratio</Text>
              <Text style={[styles.kpiSummaryValue, { color: crmStats.customerKPIs.ltvToCacRatio >= 3 ? '#22C55E' : '#EF4444', fontFamily: fonts.bold }]}>
                {crmStats.customerKPIs.ltvToCacRatio}x
              </Text>
              <Text style={[styles.kpiSummaryDesc, { color: colors.textLight, fontFamily: fonts.regular }]}>
                {crmStats.customerKPIs.ltvToCacRatio >= 3 ? 'Healthy ratio' : 'Needs improvement'}
              </Text>
            </View>
            
            <View style={styles.kpiSummaryItem}>
              <Text style={[styles.kpiSummaryLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>Churn Rate</Text>
              <Text style={[styles.kpiSummaryValue, { color: crmStats.customerKPIs.churnRate <= 5 ? '#22C55E' : '#EF4444', fontFamily: fonts.bold }]}>
                {crmStats.customerKPIs.churnRate}%
              </Text>
              <Text style={[styles.kpiSummaryDesc, { color: colors.textLight, fontFamily: fonts.regular }]}>
                {crmStats.customerKPIs.churnRate <= 5 ? 'Low churn' : 'High churn risk'}
              </Text>
            </View>
          </View>
        </View>

        {/* Lists */}
        <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 Opportunities</Text>
            {dashboardData.topOpps.length > 0 ? dashboardData.topOpps.map(o => (
              <View key={o.name} style={styles.listRow}>
                <Text style={[styles.listPrimary, { color: colors.text, fontFamily: fonts.regular }]} numberOfLines={1}>
                  {o.name}
                </Text>
                <Text style={[styles.listSecondary, { color: colors.primary, fontFamily: fonts.bold }]}>
                  {formatCurrency(o.value)}
                </Text>
              </View>
            )) : (
              <Text style={[styles.emptyText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                No opportunities found
              </Text>
            )}
          </View>
          <View style={[styles.card, styles.col, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Recent Activity</Text>
            {dashboardData.recent.length > 0 ? dashboardData.recent.map(r => (
              <View key={`${r.who}-${r.when}`} style={styles.listRow}>
                <Text style={[styles.listPrimary, { color: colors.text, fontFamily: fonts.regular }]} numberOfLines={1}>
                  {r.who}
                </Text>
                <Text style={[styles.listSecondary, { color: colors.textLight, fontFamily: fonts.regular }]} numberOfLines={1}>
                  {r.what} · {r.when}
                </Text>
              </View>
            )) : (
              <Text style={[styles.emptyText, { color: colors.textLight, fontFamily: fonts.regular }]}>
                No recent activity
              </Text>
            )}
          </View>
        </View>
      </ScrollView>
    </Container>
  );
};

const styles = StyleSheet.create({
  wrap: { flex: 1, padding: 16 },
  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,
  },
  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,
  },
});

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


