import { useEffect, useMemo, useState } from 'react';
import { Modal, View, Text, Pressable, StyleSheet, ScrollView } from 'react-native';
import Ionicons from '@expo/vector-icons/Ionicons';
import { addDaysIso, dayInfo, todayIso } from '../../meal-planning/utils/weekDates';
import { colors, spacing, radii, typography } from '../../../theme';
import { useCustomRanges, useRemoveCustomRange, useSaveCustomRange } from '../hooks/useShoppingList';

// Fenêtre de jours proposés — deux semaines dans le passé (courses déjà en retard) jusqu'à
// un an dans le futur (cas exceptionnel : absence prolongée, voyage…). Même principe que
// MoveMealModal.tsx (liste bornée simple plutôt qu'un vrai calendrier).
const DAYS_BEFORE = 14;
const DAYS_AFTER = 365;

type Props = {
  visible: boolean;
  onApply: (start: string, end: string) => void;
  onClose: () => void;
};

// Sélection en 2 temps (premier jour puis dernier jour) pour l'encadrement de dates
// personnalisé de la liste de courses (ShoppingListScreen.tsx) — remplace ponctuellement
// la navigation par semaine de 7 jours quand elle ne convient pas (ex. partir 10 jours,
// grouper les courses de plusieurs semaines avant une absence).
export function CustomRangeModal({ visible, onApply, onClose }: Props) {
  const anchor = useMemo(() => todayIso(), []);
  const days = useMemo(
    () => Array.from({ length: DAYS_BEFORE + DAYS_AFTER }, (_, idx) => addDaysIso(anchor, idx - DAYS_BEFORE)),
    [anchor],
  );
  const [step, setStep] = useState<'start' | 'end'>('start');
  const [start, setStart] = useState<string | null>(null);

  // Créneaux déjà enregistrés (mémorisation demandée : pas besoin de repasser par la
  // sélection jour par jour à chaque fois) — expirés (date de fin passée) déjà exclus côté
  // backend (ShoppingListService::activeCustomRanges()), rien à filtrer ici.
  const { data: savedRanges } = useCustomRanges();
  const saveCustomRange = useSaveCustomRange();
  const removeCustomRange = useRemoveCustomRange();

  // Repart toujours de zéro à l'ouverture — usage ponctuel, pas besoin de mémoriser une
  // sélection précédente entre deux ouvertures.
  useEffect(() => {
    if (!visible) return;
    setStep('start');
    setStart(null);
  }, [visible]);

  // Sert aussi bien à une sélection fraîche (jour par jour) qu'à la réutilisation d'un
  // créneau enregistré (chip) — dans les deux cas on (ré)enregistre : ça bascule le
  // créneau réutilisé en tête de liste (`createdAt` mis à jour, voir saveCustomRange()
  // côté backend), sans dupliquer d'entrée.
  function apply(rangeStart: string, rangeEnd: string) {
    saveCustomRange.mutate({ start: rangeStart, end: rangeEnd });
    onApply(rangeStart, rangeEnd);
  }

  function chooseStart(iso: string) {
    setStart(iso);
    setStep('end');
  }

  function chooseEnd(iso: string) {
    if (!start) return;
    apply(start, iso);
  }

  const visibleDays = step === 'end' && start ? days.filter((d) => d >= start) : days;

  return (
    <Modal visible={visible} transparent animationType="slide" onRequestClose={onClose}>
      <Pressable style={styles.backdrop} onPress={onClose}>
        <Pressable style={styles.sheet} onPress={(e) => e.stopPropagation()}>
          <View style={styles.header}>
            <View style={{ flex: 1 }}>
              <Text style={styles.title}>Période personnalisée</Text>
              <Text style={styles.subtitle}>
                {step === 'start' || !start
                  ? 'Choisissez le premier jour'
                  : `Choisissez le dernier jour (à partir du ${dayInfo(start).short})`}
              </Text>
            </View>
            <Pressable onPress={onClose} hitSlop={8} style={styles.closeBtn}>
              <Ionicons name="close" size={16} color={colors.textMuted} />
            </Pressable>
          </View>

          {step === 'start' && savedRanges && savedRanges.ranges.length > 0 ? (
            <View style={styles.savedSection}>
              <Text style={styles.savedLabel}>Vos périodes enregistrées</Text>
              <View style={styles.savedList}>
                {savedRanges.ranges.map((range) => (
                  <View key={range.id} style={styles.savedChip}>
                    <Pressable onPress={() => apply(range.start, range.end)} style={styles.savedChipMain}>
                      <Text style={styles.savedChipText}>{dayInfo(range.start).short} – {dayInfo(range.end).short}</Text>
                    </Pressable>
                    <Pressable onPress={() => removeCustomRange.mutate(range.id)} hitSlop={6} style={styles.savedChipRemove}>
                      <Ionicons name="close" size={12} color={colors.textMuted} />
                    </Pressable>
                  </View>
                ))}
              </View>
            </View>
          ) : null}

          {step === 'end' ? (
            <Pressable style={styles.backLink} onPress={() => setStep('start')} hitSlop={6}>
              <Ionicons name="chevron-back" size={14} color={colors.primary} />
              <Text style={styles.backLinkText}>Changer le premier jour</Text>
            </Pressable>
          ) : null}

          <ScrollView style={styles.list} keyboardShouldPersistTaps="handled">
            {visibleDays.map((iso) => {
              const { weekday, short } = dayInfo(iso);
              const isStart = step === 'end' && iso === start;
              return (
                <Pressable
                  key={iso}
                  style={[styles.dayRow, isStart && styles.dayRowCurrent]}
                  onPress={() => (step === 'start' ? chooseStart(iso) : chooseEnd(iso))}
                >
                  <Text style={[styles.dayText, isStart && styles.dayTextCurrent]}>{weekday} {short}</Text>
                  {isStart ? <Text style={styles.currentTag}>Premier jour</Text> : null}
                </Pressable>
              );
            })}
          </ScrollView>
        </Pressable>
      </Pressable>
    </Modal>
  );
}

const styles = StyleSheet.create({
  backdrop: { flex: 1, backgroundColor: 'rgba(20, 20, 26, 0.4)', justifyContent: 'flex-end' },
  sheet: { backgroundColor: colors.card, borderTopLeftRadius: radii.xl, borderTopRightRadius: radii.xl, padding: spacing.lg, maxHeight: '80%' },
  header: { flexDirection: 'row', alignItems: 'flex-start', marginBottom: spacing.sm },
  title: { ...typography.title, fontSize: 18, color: colors.text },
  subtitle: { ...typography.caption, color: colors.textMuted, marginTop: 2 },
  closeBtn: { width: 30, height: 30, borderRadius: radii.pill, backgroundColor: colors.background, alignItems: 'center', justifyContent: 'center' },
  backLink: { flexDirection: 'row', alignItems: 'center', gap: 2, alignSelf: 'flex-start', marginBottom: spacing.sm },
  backLinkText: { ...typography.caption, fontSize: 12.5, fontWeight: '700', color: colors.primary },
  savedSection: { marginBottom: spacing.md },
  savedLabel: { ...typography.caption, fontSize: 12, fontWeight: '700', color: colors.textMuted, marginBottom: 6 },
  savedList: { flexDirection: 'row', flexWrap: 'wrap', gap: 6 },
  savedChip: {
    flexDirection: 'row', alignItems: 'center', gap: 6,
    borderRadius: radii.pill, borderWidth: 1, borderColor: colors.primary,
    backgroundColor: `${colors.primary}0f`, paddingLeft: 10, paddingRight: 6, paddingVertical: 6,
  },
  savedChipMain: {},
  savedChipText: { ...typography.caption, fontSize: 12.5, fontWeight: '700', color: colors.primary },
  savedChipRemove: { width: 16, height: 16, borderRadius: 8, alignItems: 'center', justifyContent: 'center' },
  list: { maxHeight: 420 },
  dayRow: {
    flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between',
    paddingVertical: 12, paddingHorizontal: spacing.sm, borderRadius: radii.sm,
    borderWidth: 1, borderColor: colors.border, marginBottom: 6,
  },
  dayRowCurrent: { borderColor: colors.primary, backgroundColor: `${colors.primary}0f` },
  dayText: { ...typography.body, fontSize: 14, color: colors.text },
  dayTextCurrent: { fontWeight: '700', color: colors.primary },
  currentTag: { ...typography.caption, fontSize: 11, fontWeight: '700', color: colors.primary },
});
