import { useEffect, useState } from 'react';
import { View, Text, StyleSheet, ScrollView, ActivityIndicator, Pressable, Switch } from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import Ionicons from '@expo/vector-icons/Ionicons';
import { useFastingOverview, useSetFastingEnabled, useSetFastingGoal, useSetFastingWindowStart } from '../hooks/useFasting';
import { colors, spacing, radii, typography } from '../../../theme';
import { FAST_HERO_GRADIENT, buildFastHeroView } from '../utils/fasting';

export function FastingScreen() {
  const { data, isLoading, error } = useFastingOverview();
  const setEnabled = useSetFastingEnabled();
  const setGoal = useSetFastingGoal();
  const setWindowStart = useSetFastingWindowStart();

  // Compteur ticking côté client (même choix que fasting-tracking.js : éviter un
  // aller-retour serveur chaque seconde), un seul `setInterval` pour toute la durée
  // de vie de l'écran plutôt que dépendant de `data` (sinon redémarré à chaque refetch).
  const [now, setNow] = useState(() => new Date());
  useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(id);
  }, []);

  if (isLoading) {
    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 le suivi du jeûne.</Text>
      </View>
    );
  }

  const { overview } = data;
  const view = buildFastHeroView(overview, now);

  return (
    <ScrollView style={styles.container} contentContainerStyle={styles.content}>
      <Text style={styles.title}>Jeûne intermittent</Text>

      <View style={styles.card}>
        <View style={styles.toggleRow}>
          <View style={styles.toggleText}>
            <Text style={styles.toggleTitle}>Activer le suivi du jeûne</Text>
            <Text style={styles.hint}>
              Fonctionnalité optionnelle : un compteur basé sur vos repas déjà enregistrés dans « Mon suivi », désactivé
              par défaut.
            </Text>
          </View>
          <Switch
            value={overview.enabled}
            onValueChange={(value) => setEnabled.mutate(value)}
            disabled={setEnabled.isPending}
            trackColor={{ false: colors.border, true: colors.primary }}
          />
        </View>
      </View>

      {overview.enabled && (
        <>
          <LinearGradient colors={FAST_HERO_GRADIENT[view.tone]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={styles.hero}>
            <Text style={styles.heroLabel}>{view.label}</Text>
            <Text style={styles.heroTimer}>{view.timer}</Text>
            {view.showProgress && (
              <View style={styles.progress}>
                <View style={[styles.progressFill, { width: `${view.progressPct}%` }]} />
              </View>
            )}
            <Text style={styles.heroSub}>{view.sub}</Text>
          </LinearGradient>

          <View style={styles.card}>
            <Text style={styles.goalLabel}>Objectif de jeûne</Text>
            <View style={styles.goalTabs}>
              {overview.goalOptions.map((hours) => {
                const active = hours === overview.goalHours;
                return (
                  <Pressable
                    key={hours}
                    style={[styles.goalTab, active && styles.goalTabActive]}
                    onPress={() => !active && setGoal.mutate(hours)}
                    disabled={setGoal.isPending}
                  >
                    <Text style={[styles.goalTabText, active && styles.goalTabTextActive]}>
                      {hours}/{24 - hours}
                    </Text>
                  </Pressable>
                );
              })}
            </View>
            <Text style={styles.hint}>
              Le premier chiffre est la durée de jeûne visée, le second la fenêtre de repas. Avancez par palier, à votre
              rythme : commencer par 12/12 est un excellent point de départ.
            </Text>
          </View>

          <View style={styles.card}>
            <Text style={styles.goalLabel}>Début de la fenêtre de repas</Text>
            <View style={styles.stepperRow}>
              <Pressable
                style={styles.stepperButton}
                onPress={() => setWindowStart.mutate((overview.windowStartHour + 23) % 24)}
                disabled={setWindowStart.isPending}
              >
                <Ionicons name="remove" size={18} color={colors.primary} />
              </Pressable>
              <Text style={styles.stepperValue}>{String(overview.windowStartHour).padStart(2, '0')}h00</Text>
              <Pressable
                style={styles.stepperButton}
                onPress={() => setWindowStart.mutate((overview.windowStartHour + 1) % 24)}
                disabled={setWindowStart.isPending}
              >
                <Ionicons name="add" size={18} color={colors.primary} />
              </Pressable>
            </View>
            <Text style={styles.hint}>
              Heure à laquelle vous commencez habituellement à manger — le jeûne planifié se termine à cette heure et
              reprend à la fin de votre fenêtre de repas.
            </Text>
          </View>

          <View style={styles.card}>
            <View style={styles.infoHeader}>
              <Ionicons name="cafe-outline" size={15} color={colors.text} />
              <Text style={styles.cardTitle}>Autorisé pendant le jeûne</Text>
            </View>
            <View style={styles.infoList}>
              <Text style={styles.infoItem}>• Eau, plate ou gazeuse</Text>
              <Text style={styles.infoItem}>• Thé et tisanes, sans sucre ni miel</Text>
              <Text style={styles.infoItem}>• Café noir, sans sucre ni lait</Text>
            </View>
          </View>

          <View style={styles.disclaimer}>
            <Ionicons name="time-outline" size={14} color={colors.textMuted} style={styles.disclaimerIcon} />
            <Text style={styles.disclaimerText}>
              Le jeûne intermittent ne convient pas à tout le monde : à éviter en cas de grossesse, chez les
              adolescents, en cas de diabète traité ou d'antécédents de troubles du comportement alimentaire. Cet
              outil ne remplace pas un avis médical — écoutez votre corps et rompez le jeûne dès que nécessaire, sans
              culpabiliser.
            </Text>
          </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 },
  card: { backgroundColor: colors.card, borderRadius: radii.lg, padding: spacing.md, gap: spacing.sm },
  cardTitle: { ...typography.body, fontWeight: '700', color: colors.text },
  toggleRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.md },
  toggleText: { flex: 1, gap: 3 },
  toggleTitle: { ...typography.body, fontWeight: '700', color: colors.text },
  hint: { ...typography.caption, color: colors.textMuted, lineHeight: 18 },
  hero: { borderRadius: radii.xl, padding: spacing.lg, alignItems: 'center' },
  heroLabel: {
    fontSize: 12.5,
    fontWeight: '700',
    color: 'rgba(255,255,255,0.85)',
    textTransform: 'uppercase',
    letterSpacing: 0.4,
    marginBottom: spacing.xs,
    textAlign: 'center',
  },
  heroTimer: { fontSize: 38, fontWeight: '800', color: '#fff', letterSpacing: -0.5 },
  heroSub: { fontSize: 13.5, fontWeight: '700', color: 'rgba(255,255,255,0.9)', marginTop: spacing.sm, textAlign: 'center' },
  progress: {
    width: '100%',
    height: 8,
    borderRadius: radii.pill,
    backgroundColor: 'rgba(255,255,255,0.25)',
    overflow: 'hidden',
    marginTop: spacing.md,
  },
  progressFill: { height: '100%', borderRadius: radii.pill, backgroundColor: '#fff' },
  goalLabel: { ...typography.caption, fontWeight: '700', color: colors.textMuted },
  goalTabs: { flexDirection: 'row', alignSelf: 'flex-start', backgroundColor: colors.surface, borderRadius: radii.pill, padding: 3, gap: 2 },
  goalTab: { paddingHorizontal: spacing.md, paddingVertical: spacing.sm, borderRadius: radii.pill },
  goalTabActive: { backgroundColor: colors.card },
  goalTabText: { fontSize: 13.5, fontWeight: '800', color: colors.textMuted },
  goalTabTextActive: { color: colors.primary },
  stepperRow: { flexDirection: 'row', alignItems: 'center', alignSelf: 'flex-start', gap: spacing.md },
  stepperButton: {
    width: 36,
    height: 36,
    borderRadius: radii.pill,
    backgroundColor: colors.surface,
    alignItems: 'center',
    justifyContent: 'center',
  },
  stepperValue: { fontSize: 18, fontWeight: '800', color: colors.text, minWidth: 64, textAlign: 'center' },
  infoHeader: { flexDirection: 'row', alignItems: 'center', gap: 7 },
  infoList: { gap: 4 },
  infoItem: { ...typography.caption, fontSize: 13.5, color: colors.textMuted, lineHeight: 20 },
  disclaimer: { flexDirection: 'row', gap: spacing.sm, backgroundColor: colors.surface, borderRadius: radii.lg, padding: spacing.md },
  disclaimerIcon: { marginTop: 2 },
  disclaimerText: { flex: 1, ...typography.caption, fontSize: 12.5, color: colors.textMuted, lineHeight: 18 },
});
