import { useState } from 'react';
import { Modal, View, Text, Pressable, StyleSheet, ActivityIndicator } from 'react-native';
import Ionicons from '@expo/vector-icons/Ionicons';
import { CalendarDay } from '../../../api/tracking';
import { useTrackingCalendar } from '../hooks/useTrackingSummary';
import { colors, spacing, radii, typography } from '../../../theme';

const DOW = ['L', 'M', 'M', 'J', 'V', 'S', 'D'];

// Mêmes couleurs que `.tk-cal-cell` (assets/styles/tracking.css), traduites en RN.
const STATUS_COLORS: Record<CalendarDay['status'], { bg: string; text: string }> = {
  empty: { bg: '#e9eaf1', text: '#8a8fa3' },
  under: { bg: '#dcfce7', text: '#16803c' },
  over: { bg: '#fde0e0', text: '#b91c1c' },
  logged: { bg: '#dbeafe', text: '#1d4ed8' },
  future: { bg: 'transparent', text: '#cbd5e1' },
};

type Props = {
  visible: boolean;
  onClose: () => void;
  viewedDate: string;
  onSelectDate: (date: string) => void;
};

export function TrackingCalendarModal({ visible, onClose, viewedDate, onSelectDate }: Props) {
  const [month, setMonth] = useState<string | undefined>(undefined);
  const { data, isLoading } = useTrackingCalendar(viewedDate, month);

  function selectDay(date: string) {
    onSelectDate(date);
    setMonth(undefined);
    onClose();
  }

  function close() {
    setMonth(undefined);
    onClose();
  }

  return (
    <Modal visible={visible} transparent animationType="fade" onRequestClose={close}>
      <Pressable style={styles.overlay} onPress={close}>
        <Pressable style={styles.card} onPress={(e) => e.stopPropagation()}>
          {isLoading || !data ? (
            <ActivityIndicator color={colors.primary} style={styles.loading} />
          ) : (
            <>
              <View style={styles.head}>
                <Pressable onPress={() => setMonth(data.prevMonthValue)} hitSlop={8}>
                  <Ionicons name="chevron-back" size={18} color={colors.textMuted} />
                </Pressable>
                <Text style={styles.monthLabel}>{data.monthLabel}</Text>
                {data.isCurrentMonth ? (
                  <View style={styles.navSpacer} />
                ) : (
                  <Pressable onPress={() => setMonth(data.nextMonthValue)} hitSlop={8}>
                    <Ionicons name="chevron-forward" size={18} color={colors.textMuted} />
                  </Pressable>
                )}
              </View>

              <View style={styles.weekRow}>
                {DOW.map((d, i) => (
                  <Text key={i} style={styles.dowText}>{d}</Text>
                ))}
              </View>

              {data.weeks.map((week, wi) => (
                <View key={wi} style={styles.weekRow}>
                  {week.map((cell, ci) => (
                    <CalendarCell key={ci} cell={cell} onSelect={selectDay} />
                  ))}
                </View>
              ))}

              <View style={styles.legend}>
                <LegendItem color="#22c55e" label="Sous l'objectif" />
                <LegendItem color="#ef4444" label="Au-dessus" />
                <LegendItem color="#3b82f6" label="Calories comptées" />
                <LegendItem color="#b8bccb" label="Pas assez saisi" />
              </View>
            </>
          )}
        </Pressable>
      </Pressable>
    </Modal>
  );
}

function CalendarCell({ cell, onSelect }: { cell: CalendarDay | null; onSelect: (date: string) => void }) {
  if (!cell) {
    return <View style={styles.cell} />;
  }

  const colorsForStatus = STATUS_COLORS[cell.status];

  if (cell.status === 'future') {
    return (
      <View style={styles.cell}>
        <Text style={[styles.cellText, { color: colorsForStatus.text }]}>{cell.day}</Text>
      </View>
    );
  }

  return (
    <Pressable
      style={[
        styles.cell,
        styles.cellFilled,
        { backgroundColor: colorsForStatus.bg },
        cell.isToday && styles.cellToday,
        cell.isViewed && styles.cellViewed,
      ]}
      onPress={() => onSelect(cell.date)}
    >
      <Text style={[styles.cellText, { color: colorsForStatus.text }, cell.isViewed && styles.cellTextViewed]}>{cell.day}</Text>
    </Pressable>
  );
}

function LegendItem({ color, label }: { color: string; label: string }) {
  return (
    <View style={styles.legendItem}>
      <View style={[styles.legendDot, { backgroundColor: color }]} />
      <Text style={styles.legendText}>{label}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  overlay: { flex: 1, backgroundColor: 'rgba(0,0,0,0.3)', alignItems: 'center', justifyContent: 'center' },
  card: { width: 320, maxWidth: '90%', backgroundColor: colors.card, borderRadius: radii.lg, padding: spacing.md },
  loading: { paddingVertical: spacing.xl },
  head: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginBottom: spacing.sm },
  navSpacer: { width: 18 },
  monthLabel: { ...typography.body, fontWeight: '700', color: colors.text, textTransform: 'capitalize' },
  weekRow: { flexDirection: 'row', gap: 4, marginBottom: 4 },
  dowText: { flex: 1, textAlign: 'center', fontSize: 11, fontWeight: '700', color: colors.textMuted, paddingBottom: 4 },
  cell: { flex: 1, aspectRatio: 1, alignItems: 'center', justifyContent: 'center', borderRadius: 8 },
  cellFilled: { backgroundColor: '#f5f5fa' },
  cellToday: { borderWidth: 2, borderColor: colors.primary },
  cellViewed: { borderWidth: 2, borderColor: '#4338ca' },
  cellText: { fontSize: 12.5, fontWeight: '700', color: '#41465c' },
  cellTextViewed: { fontWeight: '800' },
  legend: { flexDirection: 'row', flexWrap: 'wrap', gap: 11, marginTop: spacing.sm, paddingTop: spacing.sm, borderTopWidth: 1, borderTopColor: colors.border },
  legendItem: { flexDirection: 'row', alignItems: 'center', gap: 5 },
  legendDot: { width: 9, height: 9, borderRadius: 3 },
  legendText: { fontSize: 10.5, fontWeight: '700', color: colors.textMuted },
});
