import { useMemo } from 'react';
import { Modal, View, Text, Pressable, StyleSheet, ScrollView, ActivityIndicator } from 'react-native';
import Ionicons from '@expo/vector-icons/Ionicons';
import { MealPlanItem } from '../../../api/mealPlanning';
import { useMoveItemToDate } from '../hooks/useMealPlanning';
import { addDaysIso, dayInfo, todayIso } from '../utils/weekDates';
import { colors, spacing, radii, typography } from '../../../theme';
import { showAlert } from '../../../utils/alert';

// Fenêtre de jours proposés au report — une semaine dans le passé (au cas où) jusqu'à 6
// mois dans le futur. Volontairement une liste bornée (pas d'infinite scroll ici comme
// dans MealPlanningScreen.tsx) : ~190 lignes simples suffisent largement pour ce choix
// ponctuel et évitent de dupliquer toute la mécanique de chargement infini.
const DAYS_BEFORE = 7;
const DAYS_AFTER = 180;

type Props = {
  visible: boolean;
  item: MealPlanItem | null;
  onClose: () => void;
};

export function MoveMealModal({ visible, item, onClose }: Props) {
  const moveItemToDate = useMoveItemToDate();
  const anchor = useMemo(() => todayIso(), []);

  const days = useMemo(
    () => Array.from({ length: DAYS_BEFORE + DAYS_AFTER }, (_, idx) => addDaysIso(anchor, idx - DAYS_BEFORE)),
    [anchor],
  );

  if (!item) return null;

  function choose(iso: string) {
    if (!item) return;
    moveItemToDate.mutate(
      { id: item.id, plannedDate: iso },
      {
        onSuccess: onClose,
        onError: (err) => showAlert('Erreur', err instanceof Error ? err.message : 'Une erreur est survenue.'),
      },
    );
  }

  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}>Déplacer</Text>
              <Text style={styles.subtitle} numberOfLines={1}>{item.title}</Text>
            </View>
            <Pressable onPress={onClose} hitSlop={8} style={styles.closeBtn}>
              <Ionicons name="close" size={16} color={colors.textMuted} />
            </Pressable>
          </View>

          {moveItemToDate.isPending ? (
            <ActivityIndicator color={colors.primary} style={{ paddingVertical: spacing.lg }} />
          ) : (
            <ScrollView style={styles.list} keyboardShouldPersistTaps="handled">
              {days.map((iso) => {
                const { weekday, short } = dayInfo(iso);
                const isCurrent = iso === item.plannedDate;
                return (
                  <Pressable
                    key={iso}
                    style={[styles.dayRow, isCurrent && styles.dayRowCurrent]}
                    onPress={() => choose(iso)}
                    disabled={isCurrent}
                  >
                    <Text style={[styles.dayText, isCurrent && styles.dayTextCurrent]}>{weekday} {short}</Text>
                    {isCurrent ? <Text style={styles.currentTag}>Jour actuel</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.md },
  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' },
  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: { backgroundColor: colors.background, borderColor: colors.border },
  dayText: { ...typography.body, fontSize: 14, fontWeight: '600', color: colors.text },
  dayTextCurrent: { color: colors.textMuted },
  currentTag: { ...typography.caption, fontSize: 11, fontWeight: '700', color: colors.textMuted },
});
