import React, { useEffect, useMemo } from 'react';
import { 
  View, 
  Text, 
  StyleSheet, 
  ScrollView, 
  RefreshControl, 
  TouchableOpacity,
  Dimensions 
} from 'react-native';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigation } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import { Container, LoadingSpinner, ErrorState } from '@/shared/components/ui';
import { fetchZohoPeopleData } from '../store/hrSlice';
import { 
  selectZohoPeopleState,
  selectAttendanceAnalytics,
  selectEmployeeAnalytics,
  selectLeaveAnalytics,
  selectHolidayAnalytics
} from '../store/selectors';
import { useTheme } from '@/shared/styles/useTheme';
import type { RootState } from '@/store/store';

const { width } = Dimensions.get('window');

const ZohoPeopleDashboardScreen: React.FC = () => {
  const dispatch = useDispatch();
  const navigation = useNavigation();
  const { colors, fonts, spacing, shadows } = useTheme();
  
  const zohoPeopleState = useSelector(selectZohoPeopleState);
  const { loading = false, error = null } = zohoPeopleState || {};
  const attendanceAnalytics = useSelector(selectAttendanceAnalytics);
  const employeeAnalytics = useSelector(selectEmployeeAnalytics);
  const leaveAnalytics = useSelector(selectLeaveAnalytics);
  const holidayAnalytics = useSelector(selectHolidayAnalytics);


  useEffect(() => {
    dispatch(fetchZohoPeopleData() as any);
  }, [dispatch]);

  const handleRefresh = async () => {
    try {
      await (dispatch(fetchZohoPeopleData() as any) as any).unwrap();
    } catch (error) {
      console.error('Error refreshing data:', error);
    }
  };

  if (loading && !attendanceAnalytics && !employeeAnalytics) {
    return <LoadingSpinner />;
  }

  if (error) {
    return <ErrorState message={error} onRetry={() => dispatch(fetchZohoPeopleData() as any)} />;
  }

  return (
    <Container>
      <ScrollView
        style={styles.container}
        refreshControl={
          <RefreshControl refreshing={loading} onRefresh={handleRefresh} />
        }
        showsVerticalScrollIndicator={false}
      >
        {/* Header */}
        <View style={[styles.header, { backgroundColor: colors.surface, ...shadows.light }]}>
          <View style={styles.headerContent}>
            <View style={styles.headerLeft}>
              <Icon name="people" size={28} color={colors.primary} />
              <Text style={[styles.headerTitle, { color: colors.text, fontFamily: fonts.bold }]}>
                Zoho People Dashboard
              </Text>
            </View>
            <View style={styles.headerRight}>
              <TouchableOpacity 
                style={[styles.dataButton, { backgroundColor: '#3B82F6', marginRight: 8 }]}
                onPress={() => navigation.navigate('ZohoPeopleData' as never)}
              >
                <Icon name="list" size={20} color={colors.surface} />
              </TouchableOpacity>
              <TouchableOpacity 
                style={[styles.refreshButton, { backgroundColor: colors.primary }]}
                onPress={handleRefresh}
              >
                <Icon name="refresh" size={20} color={colors.surface} />
              </TouchableOpacity>
            </View>
          </View>
        </View>

        <View style={[styles.content, { padding: spacing.md }]}>
          {/* KPI Cards Row 1 */}
          <View style={styles.kpiRow}>
            <KPICard
              title="Total Employees"
              value={employeeAnalytics?.totalEmployees?.toString() || '0'}
              subtitle="Active"
              icon="people"
              color={colors.primary}
              colors={colors}
              fonts={fonts}
              shadows={shadows}
            />
            <KPICard
              title="Present Today"
              value={attendanceAnalytics?.presentToday?.toString() || '0'}
              subtitle={`${attendanceAnalytics?.attendanceRate?.toFixed(1) || '0'}% attendance`}
              icon="check-circle"
              color="#10B981"
              colors={colors}
              fonts={fonts}
              shadows={shadows}
            />
          </View>

          {/* KPI Cards Row 2 */}
          <View style={styles.kpiRow}>
            <KPICard
              title="Leave Balance"
              value={leaveAnalytics?.totalLeaveBalance?.toString() || '0'}
              subtitle="Total days"
              icon="event-available"
              color="#3B82F6"
              colors={colors}
              fonts={fonts}
              shadows={shadows}
            />
            <KPICard
              title="Upcoming Holidays"
              value={holidayAnalytics?.upcomingHolidays?.length?.toString() || '0'}
              subtitle="Next 30 days"
              icon="event"
              color="#F59E0B"
              colors={colors}
              fonts={fonts}
              shadows={shadows}
            />
          </View>

          {/* Attendance Overview */}
          {attendanceAnalytics && (
            <View style={[styles.card, { backgroundColor: colors.surface, ...shadows.medium }]}>
              <View style={styles.cardHeader}>
                <Icon name="schedule" size={20} color={colors.primary} />
                <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>
                  Attendance Overview
                </Text>
              </View>
              
              <View style={styles.attendanceGrid}>
                <AttendanceItem
                  label="Present"
                  count={attendanceAnalytics.presentToday}
                  total={attendanceAnalytics.totalEmployees}
                  color="#10B981"
                  colors={colors}
                  fonts={fonts}
                />
                <AttendanceItem
                  label="Absent"
                  count={attendanceAnalytics.absentToday}
                  total={attendanceAnalytics.totalEmployees}
                  color="#EF4444"
                  colors={colors}
                  fonts={fonts}
                />
                <AttendanceItem
                  label="Weekend"
                  count={attendanceAnalytics.weekendToday}
                  total={attendanceAnalytics.totalEmployees}
                  color="#6B7280"
                  colors={colors}
                  fonts={fonts}
                />
              </View>

              <View style={styles.workingHoursContainer}>
                <Text style={[styles.workingHoursLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>
                  Average Working Hours
                </Text>
                <Text style={[styles.workingHoursValue, { color: colors.text, fontFamily: fonts.bold }]}>
                  {attendanceAnalytics.averageWorkingHours.toFixed(1)} hrs
                </Text>
              </View>
            </View>
          )}

          {/* Department Distribution */}
          {employeeAnalytics && (
            <View style={[styles.card, { backgroundColor: colors.surface, ...shadows.medium }]}>
              <View style={styles.cardHeader}>
                <Icon name="business" size={20} color={colors.primary} />
                <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>
                  Department Distribution
                </Text>
              </View>
              
              <View style={styles.departmentList}>
                {Object.entries(employeeAnalytics.departmentDistribution).map(([dept, count]) => (
                  <DepartmentItem
                    key={dept}
                    department={dept}
                    count={count}
                    total={employeeAnalytics.totalEmployees}
                    colors={colors}
                    fonts={fonts}
                  />
                ))}
              </View>
            </View>
          )}

          {/* Leave Analytics */}
          {leaveAnalytics && (
            <View style={[styles.card, { backgroundColor: colors.surface, ...shadows.medium }]}>
              <View style={styles.cardHeader}>
                <Icon name="event-available" size={20} color={colors.primary} />
                <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>
                  Leave Analytics
                </Text>
              </View>
              
              <View style={styles.leaveStats}>
                <LeaveStatItem
                  label="Paid Leave"
                  value={leaveAnalytics.paidLeaveBalance}
                  color="#3B82F6"
                  colors={colors}
                  fonts={fonts}
                />
                <LeaveStatItem
                  label="Unpaid Leave"
                  value={leaveAnalytics.unpaidLeaveBalance}
                  color="#6B7280"
                  colors={colors}
                  fonts={fonts}
                />
                <LeaveStatItem
                  label="Utilization"
                  value={`${leaveAnalytics.leaveUtilizationRate.toFixed(1)}%`}
                  color="#10B981"
                  colors={colors}
                  fonts={fonts}
                />
              </View>

              {leaveAnalytics.upcomingLeaves.length > 0 && (
                <View style={styles.upcomingLeaves}>
                  <Text style={[styles.upcomingLeavesTitle, { color: colors.text, fontFamily: fonts.medium }]}>
                    Upcoming Leaves
                  </Text>
                  {leaveAnalytics.upcomingLeaves.slice(0, 3).map((leave, index) => (
                    <View key={index} style={styles.leaveItem}>
                      <Text style={[styles.leaveEmployee, { color: colors.text, fontFamily: fonts.regular }]}>
                        {leave.Employee_ID}
                      </Text>
                      <Text style={[styles.leaveDates, { color: colors.textLight, fontFamily: fonts.regular }]}>
                        {leave.From} - {leave.To}
                      </Text>
                    </View>
                  ))}
                </View>
              )}
            </View>
          )}

          {/* Upcoming Holidays */}
          {holidayAnalytics && holidayAnalytics.upcomingHolidays.length > 0 && (
            <View style={[styles.card, { backgroundColor: colors.surface, ...shadows.medium }]}>
              <View style={styles.cardHeader}>
                <Icon name="event" size={20} color={colors.primary} />
                <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>
                  Upcoming Holidays
                </Text>
              </View>
              
              <View style={styles.holidaysList}>
                {holidayAnalytics.upcomingHolidays.slice(0, 5).map((holiday, index) => (
                  <HolidayItem
                    key={holiday.Id}
                    holiday={holiday}
                    colors={colors}
                    fonts={fonts}
                  />
                ))}
              </View>
            </View>
          )}
        </View>
      </ScrollView>
    </Container>
  );
};

// KPI Card Component
const KPICard: React.FC<{
  title: string;
  value: string;
  subtitle: string;
  icon: string;
  color: string;
  colors: any;
  fonts: any;
  shadows: any;
}> = ({ title, value, subtitle, icon, color, colors, fonts, shadows }) => (
  <View style={[styles.kpiCard, { backgroundColor: colors.surface, ...shadows.medium }]}>
    <View style={styles.kpiHeader}>
      <Icon name={icon} size={24} color={color} />
      <Text style={[styles.kpiTitle, { color: colors.textLight, fontFamily: fonts.regular }]}>
        {title}
      </Text>
    </View>
    <Text style={[styles.kpiValue, { color: colors.text, fontFamily: fonts.bold }]}>
      {value}
    </Text>
    <Text style={[styles.kpiSubtitle, { color: colors.textLight, fontFamily: fonts.regular }]}>
      {subtitle}
    </Text>
  </View>
);

// Attendance Item Component
const AttendanceItem: React.FC<{
  label: string;
  count: number;
  total: number;
  color: string;
  colors: any;
  fonts: any;
}> = ({ label, count, total, color, colors, fonts }) => {
  const percentage = total > 0 ? (count / total) * 100 : 0;
  
  return (
    <View style={styles.attendanceItem}>
      <View style={styles.attendanceItemHeader}>
        <View style={[styles.attendanceDot, { backgroundColor: color }]} />
        <Text style={[styles.attendanceLabel, { color: colors.text, fontFamily: fonts.regular }]}>
          {label}
        </Text>
      </View>
      <Text style={[styles.attendanceCount, { color: colors.text, fontFamily: fonts.bold }]}>
        {count}
      </Text>
      <Text style={[styles.attendancePercentage, { color: colors.textLight, fontFamily: fonts.regular }]}>
        {percentage.toFixed(1)}%
      </Text>
    </View>
  );
};

// Department Item Component
const DepartmentItem: React.FC<{
  department: string;
  count: number;
  total: number;
  colors: any;
  fonts: any;
}> = ({ department, count, total, colors, fonts }) => {
  const percentage = total > 0 ? (count / total) * 100 : 0;
  
  return (
    <View style={styles.departmentItem}>
      <View style={styles.departmentItemHeader}>
        <Text style={[styles.departmentName, { color: colors.text, fontFamily: fonts.regular }]}>
          {department}
        </Text>
        <Text style={[styles.departmentCount, { color: colors.text, fontFamily: fonts.bold }]}>
          {count}
        </Text>
      </View>
      <View style={[styles.departmentBar, { backgroundColor: colors.background }]}>
        <View 
          style={[
            styles.departmentBarFill, 
            { 
              backgroundColor: colors.primary, 
              width: `${percentage}%` 
            }
          ]} 
        />
      </View>
    </View>
  );
};

// Leave Stat Item Component
const LeaveStatItem: React.FC<{
  label: string;
  value: string | number;
  color: string;
  colors: any;
  fonts: any;
}> = ({ label, value, color, colors, fonts }) => (
  <View style={styles.leaveStatItem}>
    <Text style={[styles.leaveStatLabel, { color: colors.textLight, fontFamily: fonts.regular }]}>
      {label}
    </Text>
    <Text style={[styles.leaveStatValue, { color, fontFamily: fonts.bold }]}>
      {value}
    </Text>
  </View>
);

// Holiday Item Component
const HolidayItem: React.FC<{
  holiday: any;
  colors: any;
  fonts: any;
}> = ({ holiday, colors, fonts }) => (
  <View style={styles.holidayItem}>
    <View style={styles.holidayItemLeft}>
      <Icon 
        name={holiday.isHalfday ? "schedule" : "event"} 
        size={16} 
        color={holiday.isRestrictedHoliday ? "#F59E0B" : colors.primary} 
      />
      <Text style={[styles.holidayName, { color: colors.text, fontFamily: fonts.regular }]}>
        {holiday.Name}
      </Text>
    </View>
    <Text style={[styles.holidayDate, { color: colors.textLight, fontFamily: fonts.regular }]}>
      {holiday.Date}
    </Text>
  </View>
);

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#E5E7EB',
  },
  headerContent: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  headerLeft: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  headerTitle: {
    fontSize: 20,
    marginLeft: 8,
  },
  headerRight: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  refreshButton: {
    width: 36,
    height: 36,
    borderRadius: 18,
    justifyContent: 'center',
    alignItems: 'center',
  },
  dataButton: {
    width: 36,
    height: 36,
    borderRadius: 18,
    justifyContent: 'center',
    alignItems: 'center',
  },
  content: {
    flex: 1,
  },
  kpiRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 16,
  },
  kpiCard: {
    flex: 1,
    marginHorizontal: 4,
    padding: 16,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: '#E5E7EB',
  },
  kpiHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 8,
  },
  kpiTitle: {
    fontSize: 12,
    marginLeft: 6,
  },
  kpiValue: {
    fontSize: 24,
    marginBottom: 4,
  },
  kpiSubtitle: {
    fontSize: 11,
  },
  card: {
    marginBottom: 16,
    padding: 16,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: '#E5E7EB',
  },
  cardHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 16,
  },
  cardTitle: {
    fontSize: 16,
    marginLeft: 8,
  },
  attendanceGrid: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginBottom: 16,
  },
  attendanceItem: {
    alignItems: 'center',
  },
  attendanceItemHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 8,
  },
  attendanceDot: {
    width: 8,
    height: 8,
    borderRadius: 4,
    marginRight: 6,
  },
  attendanceLabel: {
    fontSize: 12,
  },
  attendanceCount: {
    fontSize: 20,
    marginBottom: 4,
  },
  attendancePercentage: {
    fontSize: 11,
  },
  workingHoursContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingTop: 16,
    borderTopWidth: 1,
    borderTopColor: '#E5E7EB',
  },
  workingHoursLabel: {
    fontSize: 14,
  },
  workingHoursValue: {
    fontSize: 16,
  },
  departmentList: {
    marginTop: 8,
  },
  departmentItem: {
    marginBottom: 12,
  },
  departmentItemHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 6,
  },
  departmentName: {
    fontSize: 14,
    flex: 1,
  },
  departmentCount: {
    fontSize: 14,
  },
  departmentBar: {
    height: 6,
    borderRadius: 3,
    overflow: 'hidden',
  },
  departmentBarFill: {
    height: '100%',
    borderRadius: 3,
  },
  leaveStats: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginBottom: 16,
  },
  leaveStatItem: {
    alignItems: 'center',
  },
  leaveStatLabel: {
    fontSize: 12,
    marginBottom: 4,
  },
  leaveStatValue: {
    fontSize: 18,
  },
  upcomingLeaves: {
    marginTop: 16,
    paddingTop: 16,
    borderTopWidth: 1,
    borderTopColor: '#E5E7EB',
  },
  upcomingLeavesTitle: {
    fontSize: 14,
    marginBottom: 12,
  },
  leaveItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 8,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: '#E5E7EB',
  },
  leaveEmployee: {
    fontSize: 14,
    flex: 1,
  },
  leaveDates: {
    fontSize: 12,
  },
  holidaysList: {
    marginTop: 8,
  },
  holidayItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 12,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: '#E5E7EB',
  },
  holidayItemLeft: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
  },
  holidayName: {
    fontSize: 14,
    marginLeft: 8,
    flex: 1,
  },
  holidayDate: {
    fontSize: 12,
  },
});

export default ZohoPeopleDashboardScreen;
