import { useEffect, useRef, useState } from 'react';
import { View, Text, StyleSheet, ScrollView, ActivityIndicator, Pressable, Switch, Alert } from 'react-native';
import {
  usePlanningPreference,
  useUpdatePlanningPreference,
  useSetAnchor,
  useToggleAnchor,
  useRemoveAnchor,
} from '../hooks/usePlanningPreference';
import { MealPlanningPreference, ProfileRule } from '../../../api/planningPreference';
import { colors, spacing, radii, typography } from '../../../theme';
import { PillGroup } from '../components/PillGroup';
import { MultiPillGroup } from '../components/MultiPillGroup';
import { SegmentedButtons } from '../components/SegmentedButtons';
import { DayRhythmRow } from '../components/DayRhythmRow';
import { ExcludedIngredientsField } from '../components/ExcludedIngredientsField';
import { AnchorFoodSearchField, AnchorFoodSelection } from '../components/AnchorFoodSearchField';

const VARIETY_OPTIONS = [
  { value: '0', label: 'Off' },
  { value: '1', label: '1 sem.' },
  { value: '2', label: '2 sem.' },
  { value: '4', label: '4 sem.' },
];

function emptyRule(): ProfileRule {
  return { time: '', register: '' };
}

export function PlanningPreferenceScreen() {
  const { data, isLoading, error } = usePlanningPreference();
  const updatePreference = useUpdatePlanningPreference();
  const setAnchor = useSetAnchor();
  const toggleAnchor = useToggleAnchor();
  const removeAnchor = useRemoveAnchor();

  const [form, setForm] = useState<MealPlanningPreference | null>(null);
  const initialized = useRef(false);

  const [activeProfileTab, setActiveProfileTab] = useState<string | null>(null);
  const [addingAnchor, setAddingAnchor] = useState(false);
  const [anchorDay, setAnchorDay] = useState<string | null>(null);
  const [anchorCategory, setAnchorCategory] = useState<string | null>(null);
  const [anchorFood, setAnchorFood] = useState<AnchorFoodSelection | null>(null);

  useEffect(() => {
    if (data && !initialized.current) {
      initialized.current = true;
      setForm(data.preference);
      setActiveProfileTab(data.meta.dayProfiles[0]?.value ?? null);
    }
  }, [data]);

  function reportError(err: unknown) {
    Alert.alert('Erreur', err instanceof Error ? err.message : 'Une erreur est survenue.');
  }

  if (isLoading || !form) {
    return (
      <View style={styles.center}>
        <ActivityIndicator color={colors.primary} />
      </View>
    );
  }

  if (error || !data) {
    return (
      <View style={styles.center}>
        <Text style={typography.body}>Impossible de charger les préférences.</Text>
      </View>
    );
  }

  function cycleDayProfile(day: string) {
    const values = data!.meta.dayProfiles.map((p) => p.value);
    const current = form!.dayProfiles[day] ?? values[0];
    const next = values[(values.indexOf(current) + 1) % values.length];
    setForm({ ...form!, dayProfiles: { ...form!.dayProfiles, [day]: next } });
  }

  function toggleDayCategory(day: string, category: string) {
    const dayGrid = form!.dayGrid[day] ?? {};
    setForm({ ...form!, dayGrid: { ...form!.dayGrid, [day]: { ...dayGrid, [category]: !dayGrid[category] } } });
  }

  function toggleDietTag(value: string) {
    const tags = form!.preferredDietTags;
    setForm({
      ...form!,
      preferredDietTags: tags.includes(value) ? tags.filter((t) => t !== value) : [...tags, value],
    });
  }

  function setProfileRuleField(profile: string, category: string, field: keyof ProfileRule, value: string) {
    const profileRules = form!.profileRules[profile] ?? {};
    const rule = profileRules[category] ?? emptyRule();
    setForm({
      ...form!,
      profileRules: { ...form!.profileRules, [profile]: { ...profileRules, [category]: { ...rule, [field]: value } } },
    });
  }

  function save() {
    updatePreference.mutate(form!, { onError: reportError });
  }

  function submitAnchor() {
    if (!anchorDay || !anchorCategory || !anchorFood) return;
    setAnchor.mutate(
      { day: anchorDay, category: anchorCategory, recipeId: anchorFood.recipeId, ciqualName: anchorFood.ciqualName },
      {
        onSuccess: () => {
          setAddingAnchor(false);
          setAnchorDay(null);
          setAnchorCategory(null);
          setAnchorFood(null);
        },
        onError: reportError,
      },
    );
  }

  function confirmRemoveAnchor(id: number, label: string) {
    Alert.alert(`Supprimer "${label}" ?`, undefined, [
      { text: 'Annuler', style: 'cancel' },
      { text: 'Supprimer', style: 'destructive', onPress: () => removeAnchor.mutate(id, { onError: reportError }) },
    ]);
  }

  const activeProfile = data.meta.dayProfiles.find((p) => p.value === activeProfileTab) ?? data.meta.dayProfiles[0];
  const activeProfileRules = form.profileRules[activeProfile.value] ?? {};

  return (
    <ScrollView style={styles.container} contentContainerStyle={styles.content}>
      <View>
        <Text style={styles.title}>Préférences</Text>
        <Text style={styles.subtitle}>
          Votre rythme et vos règles. « Suggérer » et « Remplir automatiquement » s'appuient dessus.
        </Text>
      </View>

      <View style={styles.kpis}>
        <View style={styles.kpi}>
          <Text style={styles.kpiValue}>{data.plannedCount}</Text>
          <Text style={styles.kpiLabel}>créneaux / sem.</Text>
        </View>
        <View style={styles.kpi}>
          <Text style={styles.kpiValue}>{data.activeAnchorsCount}</Text>
          <Text style={styles.kpiLabel}>repas fixes</Text>
        </View>
        <View style={styles.kpi}>
          <Text style={styles.kpiValue}>{form.preferredDietTags.length > 0 ? form.preferredDietTags.length : '—'}</Text>
          <Text style={styles.kpiLabel}>régimes</Text>
        </View>
      </View>

      {/* Bloc 1 : rythme hebdomadaire */}
      <View style={styles.card}>
        <Text style={styles.cardTitle}>Rythme hebdomadaire</Text>
        <Text style={styles.cardSubtitle}>Créneaux à planifier par jour</Text>
        <View style={styles.dayList}>
          {data.meta.days.map((day) => (
            <DayRhythmRow
              key={day.value}
              dayLabel={day.label}
              categories={data.meta.categories}
              checkedCategories={form.dayGrid[day.value] ?? {}}
              currentProfile={
                data.meta.dayProfiles.find((p) => p.value === (form.dayProfiles[day.value] ?? 'travail')) ?? data.meta.dayProfiles[0]
              }
              onCycleProfile={() => cycleDayProfile(day.value)}
              onToggleCategory={(category) => toggleDayCategory(day.value, category)}
            />
          ))}
        </View>
      </View>

      {/* Bloc 2 : réglages par profil de jour */}
      <View style={styles.card}>
        <Text style={styles.cardTitle}>Réglages par profil</Text>
        <Text style={styles.cardSubtitle}>Temps & registre par créneau</Text>

        <View style={styles.tabs}>
          {data.meta.dayProfiles.map((profile) => {
            const active = profile.value === activeProfile.value;
            return (
              <Pressable
                key={profile.value}
                style={[styles.tab, active && { borderColor: profile.color, backgroundColor: `${profile.color}1a` }]}
                onPress={() => setActiveProfileTab(profile.value)}
              >
                <Text style={[styles.tabText, active && { color: profile.color }]}>{profile.label}</Text>
              </Pressable>
            );
          })}
        </View>

        <View style={styles.rules}>
          {data.meta.categories.map((category) => {
            const rule = activeProfileRules[category.value] ?? emptyRule();
            return (
              <View key={category.value} style={styles.rule}>
                <View style={styles.ruleHeader}>
                  <View style={[styles.ruleDot, { backgroundColor: category.gradient[1] }]} />
                  <Text style={styles.ruleTitle}>{category.label}</Text>
                </View>
                <Text style={styles.ruleFieldLabel}>Temps</Text>
                <SegmentedButtons
                  options={data.meta.timeBuckets}
                  value={rule.time}
                  onChange={(value) => setProfileRuleField(activeProfile.value, category.value, 'time', value)}
                />
                <Text style={styles.ruleFieldLabel}>Registre</Text>
                <SegmentedButtons
                  options={data.meta.registers}
                  value={rule.register}
                  onChange={(value) => setProfileRuleField(activeProfile.value, category.value, 'register', value)}
                />
              </View>
            );
          })}
        </View>
      </View>

      {/* Bloc 3 : profil alimentaire */}
      <View style={styles.card}>
        <Text style={styles.cardTitle}>Profil alimentaire</Text>
        <Text style={styles.cardSubtitle}>Appliqué à toutes les semaines</Text>

        <Text style={styles.fieldLabel}>Régimes préférés</Text>
        <MultiPillGroup options={data.meta.dietTags} values={form.preferredDietTags} onToggle={toggleDietTag} />

        <Text style={styles.fieldLabel}>Anti-répétition</Text>
        <SegmentedButtons
          options={VARIETY_OPTIONS}
          value={String(form.varietyWindowWeeks)}
          onChange={(value) => setForm({ ...form, varietyWindowWeeks: Number(value) })}
        />

        <View style={styles.switchRow}>
          <Text style={styles.switchLabel}>Prioriser mes recettes</Text>
          <Switch
            value={form.prioritizeOwnRecipes}
            onValueChange={(value) => setForm({ ...form, prioritizeOwnRecipes: value })}
            trackColor={{ false: colors.border, true: colors.primary }}
          />
        </View>

        <Text style={styles.fieldLabel}>Ingrédients à exclure</Text>
        <ExcludedIngredientsField
          values={form.excludedIngredientNames}
          onChange={(values) => setForm({ ...form, excludedIngredientNames: values })}
        />
      </View>

      <Pressable style={styles.saveButton} onPress={save} disabled={updatePreference.isPending}>
        <Text style={styles.saveButtonText}>
          {updatePreference.isPending ? 'Enregistrement…' : 'Enregistrer les préférences'}
        </Text>
      </Pressable>

      {/* Bloc 4 : repas fixes */}
      <View style={styles.card}>
        <Text style={styles.cardTitle}>Mes repas fixes</Text>
        <Text style={styles.cardSubtitle}>Ancres reproduites chaque semaine</Text>

        {data.anchors.length === 0 ? <Text style={styles.hint}>Aucun repas fixe.</Text> : null}

        <View style={styles.anchors}>
          {data.anchors.map((anchor) => (
            <View key={anchor.id} style={[styles.anchor, !anchor.active && styles.anchorOff]}>
              <View style={styles.anchorInfo}>
                <Text style={styles.anchorWhen}>
                  {anchor.dayLabel} · {anchor.categoryLabel}
                </Text>
                <Text style={styles.anchorName}>{anchor.displayName}</Text>
              </View>
              <View style={styles.anchorActions}>
                <Pressable
                  style={[styles.anchorStatus, anchor.active && styles.anchorStatusOn]}
                  onPress={() => toggleAnchor.mutate(anchor.id, { onError: reportError })}
                >
                  <Text style={[styles.anchorStatusText, anchor.active && styles.anchorStatusTextOn]}>
                    {anchor.active ? 'Actif' : 'Pause'}
                  </Text>
                </Pressable>
                <Pressable style={styles.anchorRemove} onPress={() => confirmRemoveAnchor(anchor.id, anchor.displayName)}>
                  <Text style={styles.anchorRemoveText}>Suppr.</Text>
                </Pressable>
              </View>
            </View>
          ))}
        </View>

        {addingAnchor ? (
          <View style={styles.anchorForm}>
            <Text style={styles.fieldLabel}>Jour</Text>
            <PillGroup options={data.meta.days} value={anchorDay} onChange={setAnchorDay} />
            <Text style={styles.fieldLabel}>Créneau</Text>
            <PillGroup options={data.meta.categories} value={anchorCategory} onChange={setAnchorCategory} />
            <Text style={styles.fieldLabel}>Recette ou aliment</Text>
            <AnchorFoodSearchField value={anchorFood} onChange={setAnchorFood} />
            <Pressable
              style={[styles.saveButton, (!anchorDay || !anchorCategory || !anchorFood) && styles.saveButtonDisabled]}
              onPress={submitAnchor}
              disabled={!anchorDay || !anchorCategory || !anchorFood || setAnchor.isPending}
            >
              <Text style={styles.saveButtonText}>Ajouter</Text>
            </Pressable>
          </View>
        ) : (
          <Pressable style={styles.addAnchorButton} onPress={() => setAddingAnchor(true)}>
            <Text style={styles.addAnchorButtonText}>+ Ajouter un repas fixe</Text>
          </Pressable>
        )}
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: colors.background },
  content: { padding: spacing.lg, gap: spacing.md },
  center: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: colors.background },
  title: { ...typography.title, color: colors.text },
  subtitle: { ...typography.caption, color: colors.textMuted, marginTop: spacing.xs },
  kpis: { flexDirection: 'row', gap: spacing.sm },
  kpi: { flex: 1, backgroundColor: colors.card, borderRadius: radii.lg, padding: spacing.sm, alignItems: 'center', gap: 2 },
  kpiValue: { fontSize: 20, fontWeight: '700', color: colors.text },
  kpiLabel: { ...typography.caption, fontSize: 11, color: colors.textMuted },
  card: { backgroundColor: colors.card, borderRadius: radii.lg, padding: spacing.md, gap: spacing.sm },
  cardTitle: { ...typography.body, fontWeight: '700', color: colors.text },
  cardSubtitle: { ...typography.caption, color: colors.textMuted, marginTop: -spacing.xs },
  dayList: { gap: spacing.md, marginTop: spacing.xs },
  tabs: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.xs },
  tab: { paddingHorizontal: spacing.md, paddingVertical: spacing.sm, borderRadius: radii.pill, borderWidth: 1, borderColor: colors.border },
  tabText: { fontSize: 13, fontWeight: '700', color: colors.text },
  rules: { gap: spacing.sm, marginTop: spacing.xs },
  rule: { borderWidth: 1, borderColor: colors.border, borderRadius: radii.md, padding: spacing.sm, gap: 6 },
  ruleHeader: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs },
  ruleDot: { width: 8, height: 8, borderRadius: 4 },
  ruleTitle: { ...typography.body, fontSize: 14, fontWeight: '700', color: colors.text },
  ruleFieldLabel: { ...typography.caption, fontSize: 12, fontWeight: '700', color: colors.textMuted, marginTop: 4 },
  fieldLabel: { ...typography.body, fontWeight: '700', color: colors.text, marginTop: spacing.xs },
  switchRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginTop: spacing.xs },
  switchLabel: { ...typography.body, fontSize: 14, color: colors.text },
  saveButton: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: spacing.md,
    borderRadius: radii.md,
    backgroundColor: colors.primary,
  },
  saveButtonDisabled: { opacity: 0.5 },
  saveButtonText: { color: '#fff', fontWeight: '700', fontSize: 15 },
  hint: { ...typography.caption, color: colors.textMuted },
  anchors: { gap: spacing.sm },
  anchor: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    gap: spacing.sm,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.md,
    padding: spacing.sm,
  },
  anchorOff: { opacity: 0.5 },
  anchorInfo: { flex: 1, gap: 2 },
  anchorWhen: { ...typography.caption, fontSize: 12, color: colors.textMuted },
  anchorName: { ...typography.body, fontSize: 14, fontWeight: '700', color: colors.text },
  anchorActions: { flexDirection: 'row', gap: spacing.xs },
  anchorStatus: { paddingHorizontal: spacing.sm, paddingVertical: 6, borderRadius: radii.sm, borderWidth: 1, borderColor: colors.border },
  anchorStatusOn: { backgroundColor: colors.primary, borderColor: colors.primary },
  anchorStatusText: { fontSize: 12, fontWeight: '700', color: colors.text },
  anchorStatusTextOn: { color: '#fff' },
  anchorRemove: { paddingHorizontal: spacing.sm, paddingVertical: 6, borderRadius: radii.sm, borderWidth: 1, borderColor: colors.danger },
  anchorRemoveText: { fontSize: 12, fontWeight: '700', color: colors.danger },
  anchorForm: { gap: spacing.sm, marginTop: spacing.xs },
  addAnchorButton: { alignItems: 'center', paddingVertical: spacing.sm, borderRadius: radii.md, borderWidth: 1, borderColor: colors.border },
  addAnchorButtonText: { ...typography.body, fontSize: 14, fontWeight: '700', color: colors.primary },
});
