import React, { useEffect, useState } from 'react';
import { View, Text, ScrollView, RefreshControl, StyleSheet, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigation } from '@react-navigation/native';

import { Container, LoadingSpinner, ErrorState } from '@/shared/components/ui';
import { useTheme } from '@/shared/styles/useTheme';
import { fetchAllZohoProjectsData } from '@/modules/zohoProjects/store/zohoProjectsSlice';
import {
  selectZohoProjectsStats,
  selectDashboardData,
  selectIsAnyLoading,
  selectHasAnyError,
  getTimeAgo,
  getStatusColor,
} from '@/modules/zohoProjects/store/selectors';
import {
  PieChart,
  DonutChart,
  StackedBarChart,
  CompactPipeline,
} from '@/shared/components/charts';
import type { RootState } from '@/store/store';

const ZohoProjectsDashboardScreen: React.FC = () => {
  const { colors, fonts } = useTheme();
  const dispatch = useDispatch();
  const navigation = useNavigation();
  const [refreshing, setRefreshing] = useState(false);

  // Redux state
  const stats = useSelector(selectZohoProjectsStats);
  const dashboardData = useSelector(selectDashboardData);
  const isLoading = useSelector(selectIsAnyLoading);
  const hasError = useSelector(selectHasAnyError);

  useEffect(() => {
    // Fetch all data on mount
    dispatch(fetchAllZohoProjectsData({}) as any);
  }, [dispatch]);

  const handleRefresh = async () => {
    setRefreshing(true);
    await dispatch(fetchAllZohoProjectsData({ refresh: true }) as any);
    setRefreshing(false);
  };

  const handleNavigateToData = () => {
    navigation.navigate('ZohoProjectsData' as never);
  };

  // Loading state
  if (isLoading && stats.totalProjects === 0) {
    return <LoadingSpinner />;
  }

  // Error state
  if (hasError) {
    return <ErrorState onRetry={() => dispatch(fetchAllZohoProjectsData({}) as any)} />;
  }

  // Prepare chart data
  const projectStatusChartData = Object.entries(dashboardData.projectStatusDistribution).map(([label, value]) => ({
    label,
    value,
    color: getStatusColor(label),
  }));

  const taskStatusChartData = Object.entries(dashboardData.taskStatusDistribution).map(([label, value]) => ({
    label,
    value,
    color: getStatusColor(label),
  }));

  const projectTypesChartData = Object.entries(dashboardData.projectTypesDistribution).map(([label, value]) => ({
    label,
    value,
    color: getStatusColor(label),
  }));

  const taskPriorityChartData = Object.entries(dashboardData.taskPriorityDistribution).map(([label, value]) => ({
    label,
    value,
    color: getStatusColor(label),
  }));

  // Pipeline stages data (using project status distribution)
  const pipelineStages = Object.entries(dashboardData.projectStatusDistribution).map(([label, value]) => ({
    label,
    value,
    color: getStatusColor(label),
  }));

  // Issue charts data
  const issueStatusChartData = Object.entries(dashboardData.issueStatusDistribution).map(([label, value]) => ({
    label,
    value,
    color: getStatusColor(label),
  }));

  const issueSeverityChartData = Object.entries(dashboardData.issueSeverityDistribution).map(([label, value]) => ({
    label,
    value,
    color: getStatusColor(label),
  }));

  // Phase charts data
  const phaseStatusChartData = Object.entries(dashboardData.phaseStatusDistribution).map(([label, value]) => ({
    label,
    value,
    color: getStatusColor(label),
  }));

  return (
    <Container>
      <ScrollView
        style={styles.container}
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />}
      >
        <View style={styles.header}>
          <Text style={[styles.title, { color: colors.text, fontFamily: fonts.bold }]}>Zoho Projects</Text>
          <View style={styles.headerActions}>
            <TouchableOpacity 
              onPress={handleNavigateToData}
              style={styles.dataButton}
              activeOpacity={0.8}
            >
              <Icon name="list" size={24} color={colors.primary} />
            </TouchableOpacity>
          </View>
        </View>

        <View style={styles.content}>
          {/* Projects Overview Header */}
          <View style={[styles.card, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF', marginBottom: 16 }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Projects Overview</Text>
            <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
              <View>
                <Text style={{ fontSize: 14, color: colors.text, fontFamily: fonts.bold }}>Total Projects: {stats.totalProjects}</Text>
                <Text style={{ fontSize: 12, color: colors.text, fontFamily: fonts.regular, opacity: 0.8 }}>Team Members: {stats.totalTeamMembers}</Text>
              </View>
              <Chip label="Completion" value={stats.averageCompletionRate} dot="#10B981" />
            </View>
          </View>

          {/* KPI Cards */}
          <View style={styles.kpiGrid}>
            <KpiCard label="Active Projects" value={stats.activeProjects} color={colors.text} accent="#3AA0FF" />
            <KpiCard label="Completed Tasks" value={stats.closedTasks} color={colors.text} accent="#10B981" />
            <KpiCard label="High Priority" value={stats.highPriorityTasks} color={colors.text} accent="#F59E0B" />
            <KpiCard label="Overdue Tasks" value={stats.overdueTasks} color={colors.text} accent="#EF4444" />
          </View>

          {/* Project Status Distribution & Task Status */}
          <View style={styles.twoCol}> 
            <View style={[styles.card, styles.col, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
              <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Project Status Distribution</Text>
              <PieChart 
                data={projectStatusChartData}
                size={120}
                colors={colors}
                fonts={fonts}
              />
            </View>
            <View style={[styles.card, styles.col, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
              <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Task Status Distribution</Text>
              <DonutChart 
                data={taskStatusChartData}
                size={120}
                colors={colors}
                fonts={fonts}
              />
            </View>
          </View>

          {/* Project Types & Task Priority */}
          <View style={styles.twoCol}> 
            <View style={[styles.card, styles.col, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
              <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Project Types</Text>
              <StackedBarChart 
                data={projectTypesChartData}
                height={80}
                colors={colors}
                fonts={fonts}
              />
            </View>
            <View style={[styles.card, styles.col, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
              <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Task Priority</Text>
              <StackedBarChart 
                data={taskPriorityChartData}
                height={80}
                colors={colors}
                fonts={fonts}
              />
            </View>
          </View>

          {/* Project Pipeline & Milestones */}
          <View style={styles.twoCol}> 
            <View style={[styles.card, styles.col, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
              <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Project Pipeline Stages</Text>
              <CompactPipeline 
                data={pipelineStages}
                colors={colors}
                fonts={fonts}
              />
            </View>
            <View style={[styles.card, styles.col, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
              <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Milestones Overview</Text>
              <View style={styles.statsGrid}>
                <View style={styles.statItem}>
                  <Text style={[styles.statValue, { color: colors.text, fontFamily: fonts.bold }]}>{stats.totalMilestones}</Text>
                  <Text style={[styles.statLabel, { color: colors.text, fontFamily: fonts.regular }]}>Total</Text>
                </View>
                <View style={styles.statItem}>
                  <Text style={[styles.statValue, { color: colors.text, fontFamily: fonts.bold }]}>{stats.openMilestones}</Text>
                  <Text style={[styles.statLabel, { color: colors.text, fontFamily: fonts.regular }]}>Open</Text>
                </View>
                <View style={styles.statItem}>
                  <Text style={[styles.statValue, { color: colors.text, fontFamily: fonts.bold }]}>{stats.closedMilestones}</Text>
                  <Text style={[styles.statLabel, { color: colors.text, fontFamily: fonts.regular }]}>Closed</Text>
                </View>
              </View>
            </View>
          </View>

          {/* Issues Overview */}
          <View style={[styles.card, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Issues Overview</Text>
            <View style={styles.badgeRow}>
              <Chip label="Total Issues" value={stats.totalIssues} dot="#6366F1" />
              <Chip label="Open Issues" value={stats.openIssues} dot="#EF4444" />
              <Chip label="Closed Issues" value={stats.closedIssues} dot="#10B981" />
            </View>
          </View>

          {/* Issues Distribution & Severity */}
          <View style={styles.twoCol}> 
            <View style={[styles.card, styles.col, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
              <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Issue Status Distribution</Text>
              <PieChart 
                data={issueStatusChartData}
                size={120}
                colors={colors}
                fonts={fonts}
              />
            </View>
            <View style={[styles.card, styles.col, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
              <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Issue Severity Distribution</Text>
              <DonutChart 
                data={issueSeverityChartData}
                size={120}
                colors={colors}
                fonts={fonts}
              />
            </View>
          </View>

          {/* Tasks Overview */}
          <View style={[styles.card, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Tasks Overview</Text>
            <View style={styles.badgeRow}>
              <Chip label="Total Tasks" value={stats.totalTasks} dot="#3B82F6" />
              <Chip label="Open Tasks" value={stats.openTasks} dot="#F59E0B" />
              <Chip label="Closed Tasks" value={stats.closedTasks} dot="#10B981" />
            </View>
          </View>

          {/* Phases Overview */}
          <View style={[styles.card, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Phases Overview</Text>
            <View style={styles.badgeRow}>
              <Chip label="Total Phases" value={stats.totalPhases} dot="#8B5CF6" />
              <Chip label="Active Phases" value={stats.activePhases} dot="#3B82F6" />
              <Chip label="Completed Phases" value={stats.completedPhases} dot="#10B981" />
            </View>
          </View>

          {/* Phase Status Distribution */}
          <View style={[styles.card, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Phase Status Distribution</Text>
            <StackedBarChart 
              data={phaseStatusChartData}
              height={80}
              colors={colors}
              fonts={fonts}
            />
          </View>

          {/* Work Hours & Task Completion */}
          <View style={styles.twoCol}> 
            <View style={[styles.card, styles.col, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
              <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Work Hours</Text>
              <View style={styles.statsGrid}>
                <View style={styles.statItem}>
                  <Text style={[styles.statValue, { color: colors.text, fontFamily: fonts.bold }]}>{Math.round(stats.totalWorkHours)}h</Text>
                  <Text style={[styles.statLabel, { color: colors.text, fontFamily: fonts.regular }]}>Total Work</Text>
                </View>
                <View style={styles.statItem}>
                  <Text style={[styles.statValue, { color: colors.text, fontFamily: fonts.bold }]}>{Math.round(stats.billableHours)}h</Text>
                  <Text style={[styles.statLabel, { color: colors.text, fontFamily: fonts.regular }]}>Billable</Text>
                </View>
                <View style={styles.statItem}>
                  <Text style={[styles.statValue, { color: colors.text, fontFamily: fonts.bold }]}>{Math.round(stats.nonBillableHours)}h</Text>
                  <Text style={[styles.statLabel, { color: colors.text, fontFamily: fonts.regular }]}>Non-Billable</Text>
                </View>
              </View>
            </View>
            <View style={[styles.card, styles.col, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
              <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Task Completion</Text>
              <View style={styles.statsGrid}>
                <View style={styles.statItem}>
                  <Text style={[styles.statValue, { color: colors.text, fontFamily: fonts.bold }]}>{stats.averageTaskCompletion}%</Text>
                  <Text style={[styles.statLabel, { color: colors.text, fontFamily: fonts.regular }]}>Avg Completion</Text>
                </View>
                <View style={styles.statItem}>
                  <Text style={[styles.statValue, { color: colors.text, fontFamily: fonts.bold }]}>{stats.highPriorityTasks}</Text>
                  <Text style={[styles.statLabel, { color: colors.text, fontFamily: fonts.regular }]}>High Priority</Text>
                </View>
                <View style={styles.statItem}>
                  <Text style={[styles.statValue, { color: colors.text, fontFamily: fonts.bold }]}>{stats.overdueTasks}</Text>
                  <Text style={[styles.statLabel, { color: colors.text, fontFamily: fonts.regular }]}>Overdue</Text>
                </View>
              </View>
            </View>
          </View>

          {/* Top Projects & Recent Projects */}
          <View style={styles.twoCol}> 
            <View style={[styles.card, styles.col, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
              <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Top Projects by Completion</Text>
              {dashboardData.topProjectsByCompletion.map(project => (
                <View key={project.id} style={styles.listRow}>
                  <Text style={[styles.listPrimary, { color: colors.text, fontFamily: fonts.regular }]}>{project.name}</Text>
                  <Text style={[styles.listSecondary, { color: colors.text, fontFamily: fonts.regular }]}>{project.completion}%</Text>
                </View>
              ))}
            </View>
            <View style={[styles.card, styles.col, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
              <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Recent Projects</Text>
              {dashboardData.recentProjects.map(project => (
                <View key={project.id} style={styles.listRow}>
                  <Text style={[styles.listPrimary, { color: colors.text, fontFamily: fonts.regular }]}>{project.name}</Text>
                  <Text style={[styles.listSecondary, { color: colors.text, fontFamily: fonts.regular }]}>{getTimeAgo(project.createdTime)}</Text>
                </View>
              ))}
            </View>
          </View>

          {/* Top Issues & Recent Phases */}
          <View style={styles.twoCol}> 
            <View style={[styles.card, styles.col, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
              <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Top Issues by Severity</Text>
              {dashboardData.topIssuesBySeverity.map(issue => (
                <View key={issue.id} style={styles.listRow}>
                  <Text style={[styles.listPrimary, { color: colors.text, fontFamily: fonts.regular }]}>{issue.name}</Text>
                  <Text style={[styles.listSecondary, { color: colors.text, fontFamily: fonts.regular }]}>{issue.severity}</Text>
                </View>
              ))}
            </View>
            <View style={[styles.card, styles.col, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
              <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Recent Phases</Text>
              {dashboardData.recentPhases.map(phase => (
                <View key={phase.id} style={styles.listRow}>
                  <Text style={[styles.listPrimary, { color: colors.text, fontFamily: fonts.regular }]}>{phase.name}</Text>
                  <Text style={[styles.listSecondary, { color: colors.text, fontFamily: fonts.regular }]}>{getTimeAgo(phase.createdTime)}</Text>
                </View>
              ))}
            </View>
          </View>

          {/* Project Owners Distribution */}
          <View style={[styles.card, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Project Owners Distribution</Text>
            {Object.entries(dashboardData.projectOwnersDistribution).map(([owner, count]) => (
              <ProgressRow key={owner} label={owner} value={Math.round((count / stats.totalProjects) * 100)} color="#3B82F6" />
            ))}
          </View>

          {/* Team Overview */}
          <View style={[styles.card, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Team Overview</Text>
            <View style={styles.statsGrid}>
              <View style={styles.statItem}>
                <Text style={[styles.statValue, { color: colors.text, fontFamily: fonts.bold }]}>{stats.totalTeamMembers}</Text>
                <Text style={[styles.statLabel, { color: colors.text, fontFamily: fonts.regular }]}>Team Members</Text>
              </View>
              <View style={styles.statItem}>
                <Text style={[styles.statValue, { color: colors.text, fontFamily: fonts.bold }]}>{stats.averageCompletionRate}%</Text>
                <Text style={[styles.statLabel, { color: colors.text, fontFamily: fonts.regular }]}>Avg Completion</Text>
              </View>
              <View style={styles.statItem}>
                <Text style={[styles.statValue, { color: colors.text, fontFamily: fonts.bold }]}>{stats.totalProjects}</Text>
                <Text style={[styles.statLabel, { color: colors.text, fontFamily: fonts.regular }]}>Total Projects</Text>
              </View>
            </View>
          </View>
        </View>
      </ScrollView>
    </Container>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 16,
    backgroundColor: '#FFFFFF',
  },
  headerActions: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 12,
  },
  dataButton: {
    padding: 8,
    borderRadius: 8,
    backgroundColor: '#F3F4F6',
  },
  title: {
    fontSize: 24,
  },
  content: {
    padding: 16,
  },
  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,
  },
  progressRow: {
    marginTop: 8,
  },
  progressLabelWrap: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 6,
  },
  progressTrack: {
    height: 8,
    borderRadius: 6,
    backgroundColor: '#E5E7EB',
    overflow: 'hidden',
  },
  progressFill: {
    height: '100%',
    borderRadius: 6,
  },
  twoCol: {
    marginTop: 12,
  },
  badgeRow: {
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  chip: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#F3F4F6',
    paddingVertical: 6,
    paddingHorizontal: 10,
    borderRadius: 16,
    marginRight: 8,
    marginTop: 8,
  },
  chipDot: { width: 8, height: 8, borderRadius: 4, marginRight: 6 },
  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,
    opacity: 0.8,
  },
  statsGrid: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginTop: 12,
  },
  statItem: {
    alignItems: 'center',
  },
  statValue: {
    fontSize: 20,
    marginBottom: 4,
  },
  statLabel: {
    fontSize: 12,
    opacity: 0.8,
  },
});

export default ZohoProjectsDashboardScreen;

// UI subcomponents (no external deps)
const KpiCard: React.FC<{ label: string; value: number | string; color: string; accent: string }> = ({ label, value, color, accent }) => {
  const { fonts } = useTheme();
  return (
    <View style={styles.kpiCard}>
      <Text style={[styles.kpiLabel, { color, fontFamily: fonts.regular }]}>{label}</Text>
      <View style={styles.kpiValueRow}>
        <Text style={{ color, fontSize: 22, fontFamily: fonts.bold }}>{value}</Text>
        <View style={{ width: 10, height: 10, borderRadius: 5, backgroundColor: accent }} />
      </View>
    </View>
  );
};


const ProgressRow: React.FC<{ label: string; value: number; color: string }> = ({ label, value, color }) => {
  const { fonts } = useTheme();
  return (
    <View style={styles.progressRow}>
      <View style={styles.progressLabelWrap}>
        <Text style={{ fontSize: 12, fontFamily: fonts.regular }}>{label}</Text>
        <Text style={{ fontSize: 12, fontFamily: fonts.medium }}>{value}%</Text>
      </View>
      <View style={styles.progressTrack}>
        <View style={[styles.progressFill, { width: `${value}%`, backgroundColor: color }]} />
      </View>
    </View>
  );
};


const Chip: React.FC<{ label: string; value: number | string; dot: string }> = ({ label, value, dot }) => {
  const { fonts, colors } = useTheme();
  return (
    <View style={styles.chip}>
      <View style={[styles.chipDot, { backgroundColor: dot }]} />
      <Text style={{ fontSize: 12, fontFamily: fonts.regular, color: colors.text }}>{label}: </Text>
      <Text style={{ fontSize: 12, fontFamily: fonts.medium, color: colors.text }}>{value}</Text>
    </View>
  );
};


