import { useEffect, useState } from 'react';
import { View, Text, StyleSheet, ScrollView, ActivityIndicator, Pressable, TextInput } from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import Ionicons from '@expo/vector-icons/Ionicons';
import { useWeightOverview, useSaveWeight } from '../hooks/useWeight';
import { WeightChart } from '../components/WeightChart';
import { ActivityHistorySection } from '../components/ActivityHistorySection';
import { WeightPeriod } from '../../../api/weight';
import { colors, spacing, radii, typography, gradients } from '../../../theme';
import { formatKg, formatSignedKg } from '../utils/format';

const PERIODS: { value: WeightPeriod; label: string }[] = [
  { value: 'semaine', label: 'Semaine' },
  { value: 'mois', label: 'Mois' },
];

export function WeightScreen() {
  const [period, setPeriod] = useState<WeightPeriod>('semaine');
  const { data, isLoading, error } = useWeightOverview(period);
  const saveWeight = useSaveWeight(period);

  const [input, setInput] = useState('');
  const [message, setMessage] = useState<{ text: string; error: boolean } | null>(null);

  const todayWeight = data?.overview.todayWeight;
  useEffect(() => {
    setInput(todayWeight != null ? formatKg(todayWeight) : '');
  }, [todayWeight]);

  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 poids.</Text>
      </View>
    );
  }

  const { overview } = data;

  function handleSave() {
    const weightKg = parseFloat(input.replace(',', '.'));
    if (!Number.isFinite(weightKg) || weightKg <= 0) {
      setMessage({ text: 'Poids invalide.', error: true });
      return;
    }
    setMessage(null);
    saveWeight.mutate(weightKg, {
      onSuccess: () => setMessage({ text: 'Poids enregistré.', error: false }),
      onError: () => setMessage({ text: 'Une erreur est survenue.', error: true }),
    });
  }

  return (
    <ScrollView style={styles.container} contentContainerStyle={styles.content}>
      <Text style={styles.title}>Activité et poids</Text>

      <LinearGradient colors={gradients.hero} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={styles.hero}>
        <View style={styles.heroRow}>
          <View style={styles.heroKpi}>
            <Text style={styles.heroKpiLabel}>Poids actuel</Text>
            <Text style={styles.heroKpiValue}>{overview.current !== null ? `${formatKg(overview.current)} kg` : '—'}</Text>
          </View>
          <View style={styles.heroKpi}>
            <Text style={styles.heroKpiLabel}>Objectif</Text>
            <Text style={styles.heroKpiValue}>
              {overview.objective !== null ? `${formatKg(overview.objective)} kg` : 'Non défini'}
            </Text>
          </View>
          <View style={styles.heroKpi}>
            <Text style={styles.heroKpiLabel}>Écart objectif</Text>
            <Text
              style={[
                styles.heroKpiValue,
                overview.deltaObjective !== null && overview.deltaObjective > 0 && styles.heroValueOver,
                overview.deltaObjective !== null && overview.deltaObjective <= 0 && styles.heroValueUnder,
              ]}
            >
              {overview.deltaObjective !== null ? `${formatSignedKg(overview.deltaObjective)} kg` : '—'}
            </Text>
          </View>
        </View>
      </LinearGradient>

      <View style={styles.card}>
        <Text style={styles.addLabel}>
          {overview.todayWeight !== null ? 'Mettre à jour le poids du jour' : 'Ajouter le poids du jour'}
        </Text>
        <View style={styles.addRow}>
          <TextInput
            style={styles.addInput}
            keyboardType="decimal-pad"
            placeholder="Ex. 72,5"
            placeholderTextColor={colors.textMuted}
            value={input}
            onChangeText={setInput}
          />
          <Text style={styles.unit}>kg</Text>
          <Pressable style={styles.saveButton} onPress={handleSave} disabled={saveWeight.isPending}>
            <Ionicons name="checkmark" size={15} color="#fff" />
            <Text style={styles.saveButtonText}>Enregistrer</Text>
          </Pressable>
        </View>
        {message && <Text style={[styles.message, message.error && styles.messageError]}>{message.text}</Text>}
      </View>

      <View style={styles.card}>
        <View style={styles.chartHeader}>
          <View style={styles.tabs}>
            {PERIODS.map((p) => {
              const active = p.value === period;
              return (
                <Pressable key={p.value} style={[styles.tab, active && styles.tabActive]} onPress={() => setPeriod(p.value)}>
                  <Text style={[styles.tabText, active && styles.tabTextActive]}>{p.label}</Text>
                </Pressable>
              );
            })}
          </View>
          {overview.deltaPeriod !== null && (
            <Text style={styles.deltaPeriod}>{formatSignedKg(overview.deltaPeriod)} kg sur la période</Text>
          )}
        </View>

        {overview.hasData ? (
          <WeightChart points={overview.points} />
        ) : (
          <Text style={styles.empty}>Aucune donnée sur cette période. Ajoutez votre poids pour voir la courbe.</Text>
        )}
      </View>

      <ActivityHistorySection />
    </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 },
  hero: { borderRadius: radii.xl, padding: spacing.lg },
  heroRow: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.lg },
  heroKpi: { gap: 4 },
  heroKpiLabel: { fontSize: 11.5, fontWeight: '700', color: 'rgba(255,255,255,0.8)', textTransform: 'uppercase', letterSpacing: 0.4 },
  heroKpiValue: { fontSize: 22, fontWeight: '800', color: '#fff', letterSpacing: -0.3 },
  heroValueOver: { color: '#fecaca' },
  heroValueUnder: { color: '#bbf7d0' },
  addLabel: { ...typography.caption, fontWeight: '700', color: colors.textMuted },
  addRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
  addInput: {
    flex: 1,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.sm,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.sm,
    fontSize: 16,
    fontWeight: '700',
    color: colors.text,
  },
  unit: { ...typography.caption, fontWeight: '700', color: colors.textMuted },
  saveButton: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
    backgroundColor: colors.primary,
    borderRadius: radii.sm,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
  },
  saveButtonText: { fontSize: 13.5, fontWeight: '800', color: '#fff' },
  message: { fontSize: 13, fontWeight: '700', color: colors.success },
  messageError: { color: colors.danger },
  chartHeader: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: spacing.sm, flexWrap: 'wrap' },
  tabs: { flexDirection: 'row', backgroundColor: colors.surface, borderRadius: radii.pill, padding: 3, gap: 2 },
  tab: { paddingHorizontal: spacing.md, paddingVertical: spacing.sm, borderRadius: radii.pill },
  tabActive: { backgroundColor: colors.card },
  tabText: { fontSize: 13, fontWeight: '700', color: colors.textMuted },
  tabTextActive: { color: colors.primary },
  deltaPeriod: { fontSize: 13, fontWeight: '800', color: colors.textMuted },
  empty: { ...typography.caption, color: colors.textMuted, textAlign: 'center', paddingVertical: spacing.xl },
});
