import React, { useEffect, useMemo } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { useDispatch, useSelector } from 'react-redux';
import { Container, LoadingSpinner, ErrorState } from '@/shared/components/ui';
import { fetchHRMetrics } from '@/modules/hr/store/hrSlice';
import type { RootState } from '@/store/store';
import { useTheme } from '@/shared/styles/useTheme';

const HRDashboardScreen: React.FC = () => {
  const dispatch = useDispatch();
  const { colors, fonts } = useTheme();
  const { metrics, loading, error } = useSelector((s: RootState) => s.hr);

  // Mock HR analytics (UI only)
  const mock = useMemo(() => {
    const headcount = 148;
    const newHires30d = 9;
    const attritionPct = 6; // lower is better
    const attendancePct = 93;
    const engagementPct = 78;
    const hiresTrend = [2, 1, 3, 1, 2, 0];
    const exitsTrend = [1, 0, 1, 0, 1, 1];
    const deptDist = [
      { label: 'Engineering', value: 62, color: '#3AA0FF' },
      { label: 'Sales', value: 34, color: '#F59E0B' },
      { label: 'HR', value: 12, color: '#10B981' },
      { label: 'Ops', value: 28, color: '#6366F1' },
      { label: 'Finance', value: 12, color: '#EF4444' },
    ];
    const holidays = [
      { date: '2025-09-10', name: 'Ganesh Chaturthi' },
      { date: '2025-10-02', name: 'Gandhi Jayanti' },
      { date: '2025-10-31', name: 'Diwali' },
    ];
    const topPerformers = [
      { name: 'Aarti N.', score: 96 },
      { name: 'Rahul K.', score: 94 },
      { name: 'Meera S.', score: 92 },
    ];
    return { headcount, newHires30d, attritionPct, attendancePct, engagementPct, hiresTrend, exitsTrend, deptDist, holidays, topPerformers };
  }, []);

  useEffect(() => {
    // @ts-ignore
    dispatch(fetchHRMetrics());
  }, [dispatch]);

  if (loading && metrics.length === 0) {
    return <LoadingSpinner />;
  }
  if (error) {
    return <ErrorState message={error} onRetry={() => dispatch(fetchHRMetrics() as any)} />;
  }
  return (
    <Container>
      <View style={styles.header}>
        <Text style={[styles.title, { color: colors.text, fontFamily: fonts.bold }]}>HR Dashboard</Text>
      </View>
      <View style={styles.content}>
        {/* KPI Cards */}
        <View style={styles.kpiGrid}>
          <Kpi label="Headcount" value={String(mock.headcount)} color={colors.text} fonts={fonts} accent="#3AA0FF" />
          <Kpi label="New hires (30d)" value={String(mock.newHires30d)} color={colors.text} fonts={fonts} accent="#10B981" />
          <Kpi label="Attrition" value={`${mock.attritionPct}%`} color={colors.text} fonts={fonts} accent="#EF4444" />
          <Kpi label="Attendance" value={`${mock.attendancePct}%`} color={colors.text} fonts={fonts} accent="#6366F1" />
        </View>

        {/* Trends: Hires vs Exits */}
        <View style={[styles.card, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Workforce Movements</Text>
          <DualBars data={mock.hiresTrend.map((h, i) => ({ in: h, out: mock.exitsTrend[i] }))} max={Math.max(...mock.hiresTrend.map((h, i) => Math.max(h, mock.exitsTrend[i])))} colorA="#10B981" colorB="#EF4444" />
          <View style={styles.legendRow}>
            <View style={styles.legendItem}><View style={[styles.legendDot, { backgroundColor: '#10B981' }]} /><Text style={{ fontSize: 12, color: colors.text, fontFamily: fonts.regular }}>Hires</Text></View>
            <View style={styles.legendItem}><View style={[styles.legendDot, { backgroundColor: '#EF4444' }]} /><Text style={{ fontSize: 12, color: colors.text, fontFamily: fonts.regular }}>Exits</Text></View>
          </View>
        </View>

        {/* People Health */}
        <View style={[styles.card, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>People Health</Text>
          <Progress label="Attendance" value={mock.attendancePct} color="#3AA0FF" fonts={fonts} />
          <Progress label="Engagement" value={mock.engagementPct} color="#6366F1" fonts={fonts} />
          <Progress label="Attrition (inverse)" value={100 - mock.attritionPct} color="#10B981" fonts={fonts} />
        </View>

        {/* Department Distribution */}
        <View style={[styles.card, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Department Distribution</Text>
          <Stacked segments={mock.deptDist} total={mock.deptDist.reduce((a, b) => a + b.value, 0)} />
          <View style={styles.legendRow}>
            {mock.deptDist.map(s => (
              <View key={s.label} style={styles.legendItem}>
                <View style={[styles.legendDot, { backgroundColor: s.color }]} />
                <Text style={{ color: colors.text, fontFamily: fonts.regular }}>{s.label}</Text>
              </View>
            ))}
          </View>
        </View>

        {/* Lists: Holidays and Top Performers */}
        <View style={styles.row}> 
          <View style={[styles.card, styles.col, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Upcoming Holidays</Text>
            {mock.holidays.map(h => (
              <View key={h.date} style={styles.listRow}>
                <Text style={[styles.listPrimary, { color: colors.text, fontFamily: fonts.regular }]}>{h.name}</Text>
                <Text style={[styles.listSecondary, { color: colors.text, fontFamily: fonts.medium }]}>{h.date}</Text>
              </View>
            ))}
          </View>
          <View style={[styles.card, styles.col, { borderColor: '#E2E8F0', backgroundColor: '#FFFFFF' }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Top Performers</Text>
            {mock.topPerformers.map(p => (
              <View key={p.name} style={styles.listRow}>
                <Text style={[styles.listPrimary, { color: colors.text, fontFamily: fonts.regular }]}>{p.name}</Text>
                <Text style={[styles.listSecondary, { color: colors.text, fontFamily: fonts.medium }]}>{p.score}</Text>
              </View>
            ))}
          </View>
        </View>
      </View>
    </Container>
  );
};

const styles = StyleSheet.create({
  header: {
    padding: 16,
    backgroundColor: '#FFFFFF',
  },
  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 },
  dualBarsRow: { flexDirection: 'row', alignItems: 'flex-end' },
  dualBarWrap: { flex: 1, marginRight: 8 },
  dualBarA: { borderTopLeftRadius: 4, borderTopRightRadius: 4 },
  dualBarB: { borderTopLeftRadius: 4, borderTopRightRadius: 4, marginTop: 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 },
  row: { flexDirection: '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 },
});

export default HRDashboardScreen;

// UI helpers (no external deps)
const Kpi: React.FC<{ label: string; value: string; color: string; fonts: any; accent: string }> = ({ label, value, color, fonts, accent }) => {
  return (
    <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 DualBars: React.FC<{ data: { in: number; out: number }[]; max: number; colorA: string; colorB: string }> = ({ data, max, colorA, colorB }) => {
  return (
    <View style={styles.dualBarsRow}>
      {data.map((d, i) => (
        <View key={i} style={styles.dualBarWrap}>
          <View style={[styles.dualBarA, { height: Math.max(6, (d.in / Math.max(1, max)) * 64), backgroundColor: colorA }]} />
          <View style={[styles.dualBarB, { height: Math.max(6, (d.out / Math.max(1, max)) * 64), backgroundColor: colorB }]} />
        </View>
      ))}
    </View>
  );
};

const Progress: React.FC<{ label: string; value: number; color: string; fonts: any }> = ({ label, value, color, fonts }) => {
  return (
    <View style={{ marginTop: 8 }}>
      <View style={{ flexDirection: 'row', justifyContent: 'space-between', marginBottom: 6 }}>
        <Text style={{ fontSize: 12, fontFamily: fonts.regular }}>{label}</Text>
        <Text style={{ fontSize: 12, fontFamily: fonts.medium }}>{value}%</Text>
      </View>
      <View style={{ height: 8, borderRadius: 6, backgroundColor: '#E5E7EB', overflow: 'hidden' }}>
        <View style={{ height: '100%', width: `${value}%`, backgroundColor: color }} />
      </View>
    </View>
  );
};

const Stacked: React.FC<{ segments: { label: string; value: number; color: string }[]; total: number }> = ({ segments, total }) => {
  return (
    <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>
  );
};


