import { useEffect, useRef, useState } from 'react';
import { View, Text, StyleSheet, ScrollView, ActivityIndicator, TextInput, Pressable, Switch } from 'react-native';
import { useProfile, useUpdateProfile, useSetWaterTrackingEnabled, useSetSuggestMealsToFamily } from '../hooks/useProfile';
import { ProfileUpdateInput } from '../../../api/profile';
import { useAuthStore } from '../../../store/authStore';
import { colors, spacing, radii, typography } from '../../../theme';
import { PillGroup } from '../components/PillGroup';
import { RhythmSelector } from '../components/RhythmSelector';
import { ToneSelector } from '../components/ToneSelector';
import { formatLiters } from '../../tracking/utils/format';

type FormState = {
  sexe: string | null;
  tailleCm: string;
  poidsKg: string;
  age: string;
  poidsObjectifKg: string;
  niveauActivite: string | null;
  rythmeCalorique: string | null;
  customCalorieTargetKcal: string;
  dieticianTone: string;
};

const EMPTY_FORM: FormState = {
  sexe: null,
  tailleCm: '',
  poidsKg: '',
  age: '',
  poidsObjectifKg: '',
  niveauActivite: null,
  rythmeCalorique: null,
  customCalorieTargetKcal: '',
  dieticianTone: 'conseil',
};

// Accepte la virgule décimale française (ex. "86,5") en plus du point — même
// conversion que WeightScreen.handleSave(), sinon Number("86,5") vaut NaN et
// le poids est silencieusement enregistré à null (efface la valeur existante).
function toNumberOrNull(value: string): number | null {
  const normalized = value.trim().replace(',', '.');
  return normalized !== '' && !Number.isNaN(Number(normalized)) ? Number(normalized) : null;
}

function toIntOrNull(value: string): number | null {
  return value.trim() !== '' && !Number.isNaN(parseInt(value, 10)) ? parseInt(value, 10) : null;
}

export function ProfileScreen() {
  const { data, isLoading, error } = useProfile();
  const updateProfile = useUpdateProfile();
  const setWaterTracking = useSetWaterTrackingEnabled();
  const setSuggestMealsToFamily = useSetSuggestMealsToFamily();
  const setToken = useAuthStore((state) => state.setToken);

  const [form, setForm] = useState<FormState>(EMPTY_FORM);
  const initialized = useRef(false);
  const debounceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    if (data && !initialized.current) {
      initialized.current = true;
      setForm({
        sexe: data.sexe,
        tailleCm: data.tailleCm?.toString() ?? '',
        poidsKg: data.poidsKg?.toString() ?? '',
        age: data.age?.toString() ?? '',
        poidsObjectifKg: data.poidsObjectifKg?.toString() ?? '',
        niveauActivite: data.niveauActivite,
        rythmeCalorique: data.rythmeCalorique,
        customCalorieTargetKcal: data.customCalorieTargetKcal?.toString() ?? '',
        dieticianTone: data.dieticianTone,
      });
    }
  }, [data]);

  useEffect(() => () => { if (debounceTimer.current) clearTimeout(debounceTimer.current); }, []);

  function scheduleSave(next: FormState) {
    if (debounceTimer.current) clearTimeout(debounceTimer.current);
    debounceTimer.current = setTimeout(() => {
      const input: ProfileUpdateInput = {
        sexe: next.sexe,
        tailleCm: toIntOrNull(next.tailleCm),
        poidsKg: toNumberOrNull(next.poidsKg),
        age: toIntOrNull(next.age),
        poidsObjectifKg: toNumberOrNull(next.poidsObjectifKg),
        niveauActivite: next.niveauActivite,
        rythmeCalorique: next.rythmeCalorique,
        customCalorieTargetKcal: toIntOrNull(next.customCalorieTargetKcal),
        dieticianTone: next.dieticianTone,
      };
      updateProfile.mutate(input);
    }, 600);
  }

  function update(patch: Partial<FormState>) {
    setForm((prev) => {
      const next = { ...prev, ...patch };
      scheduleSave(next);
      return next;
    });
  }

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

  const hasTarget = data.calorieTarget !== null;

  return (
    <ScrollView style={styles.container} contentContainerStyle={styles.content}>
      <View>
        <Text style={styles.title}>Mon profil</Text>
        <Text style={styles.subtitle}>
          Ces informations permettent à l'IA de calculer votre objectif calorique quotidien. Elles sont enregistrées automatiquement.
        </Text>
      </View>

      <View style={styles.targetBox}>
        {hasTarget ? (
          <>
            <Text style={styles.targetValue}>{data.calorieTarget}</Text>
            <Text style={styles.targetLabel}>kcal / jour{'\n'}Objectif appliqué à votre planning</Text>
          </>
        ) : (
          <Text style={styles.targetLabel}>
            {data.noGoalChosen
              ? 'Vous comptez vos calories sans objectif chiffré. Choisissez un rythme ci-dessous pour en avoir un.'
              : 'Complétez votre profil pour obtenir un objectif calorique personnalisé.'}
          </Text>
        )}
      </View>

      <View style={styles.hydroBox}>
        <View style={styles.hydroMain}>
          <Text style={styles.targetValue}>{data.hydrationTarget ? formatLiters(data.hydrationTarget) : '—'}</Text>
          <Text style={styles.targetLabel}>Recommandation en boissons / jour{'\n'}Eau, thé, café… (hors sucre et alcool)</Text>
        </View>
        <View style={styles.hydroToggle}>
          <Text style={styles.hydroToggleLabel}>Afficher le suivi dans "Mon suivi"</Text>
          <Switch
            value={data.waterTrackingEnabled}
            onValueChange={(value) => setWaterTracking.mutate(value)}
            disabled={setWaterTracking.isPending}
            trackColor={{ false: colors.border, true: colors.primary }}
          />
        </View>
      </View>

      <View style={styles.hydroBox}>
        <View style={styles.hydroToggle}>
          <Text style={styles.hydroToggleLabel}>Suggérer mes repas à ma famille</Text>
          <Switch
            value={data.suggestMealsToFamily}
            onValueChange={(value) => setSuggestMealsToFamily.mutate(value)}
            disabled={setSuggestMealsToFamily.isPending}
            trackColor={{ false: colors.border, true: colors.primary }}
          />
        </View>
      </View>

      <View style={styles.card}>
        <Text style={styles.fieldLabel}>Sexe</Text>
        <PillGroup options={data.sexes} value={form.sexe} onChange={(sexe) => update({ sexe })} />

        <View style={styles.grid}>
          <View style={styles.gridItem}>
            <Text style={styles.fieldLabel}>Taille (cm)</Text>
            <TextInput
              style={styles.input}
              keyboardType="number-pad"
              value={form.tailleCm}
              onChangeText={(tailleCm) => update({ tailleCm })}
            />
          </View>
          <View style={styles.gridItem}>
            <Text style={styles.fieldLabel}>Poids actuel (kg)</Text>
            <TextInput
              style={styles.input}
              keyboardType="decimal-pad"
              value={form.poidsKg}
              onChangeText={(poidsKg) => update({ poidsKg })}
            />
          </View>
          <View style={styles.gridItem}>
            <Text style={styles.fieldLabel}>Âge</Text>
            <TextInput
              style={styles.input}
              keyboardType="number-pad"
              value={form.age}
              onChangeText={(age) => update({ age })}
            />
          </View>
          <View style={styles.gridItem}>
            <Text style={styles.fieldLabel}>Poids objectif (kg)</Text>
            <TextInput
              style={styles.input}
              keyboardType="decimal-pad"
              value={form.poidsObjectifKg}
              onChangeText={(poidsObjectifKg) => update({ poidsObjectifKg })}
            />
          </View>
        </View>

        <Text style={styles.fieldLabel}>Niveau d'activité</Text>
        <PillGroup options={data.niveauxActivite} value={form.niveauActivite} onChange={(niveauActivite) => update({ niveauActivite })} />
      </View>

      <View style={styles.card}>
        <Text style={styles.fieldLabel}>Rythme calorique</Text>
        <Text style={styles.hint}>Choisissez le rythme selon l'objectif calorique quotidien qu'il représente pour vous.</Text>
        <RhythmSelector
          options={data.rythmesCaloriques}
          value={form.rythmeCalorique}
          rhythmTargets={data.rhythmTargets}
          customKcal={form.customCalorieTargetKcal}
          onSelect={(rythmeCalorique) => update({ rythmeCalorique })}
          onCustomKcalChange={(customCalorieTargetKcal) => update({ customCalorieTargetKcal })}
        />
      </View>

      <View style={styles.card}>
        <Text style={styles.fieldLabel}>Mode du bilan diététique</Text>
        <Text style={styles.hint}>Choisissez comment ClemAI communique avec vous dans votre bilan quotidien.</Text>
        <ToneSelector
          options={data.dieticianTones}
          value={form.dieticianTone}
          onSelect={(dieticianTone) => update({ dieticianTone })}
        />
      </View>

      <Pressable style={styles.logoutButton} onPress={() => setToken(null)}>
        <Text style={styles.logoutText}>Se déconnecter</Text>
      </Pressable>
    </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 },
  targetBox: { backgroundColor: colors.card, borderRadius: radii.lg, padding: spacing.md, alignItems: 'center', gap: 4 },
  targetValue: { fontSize: 28, fontWeight: '700', color: colors.text },
  targetLabel: { ...typography.caption, color: colors.textMuted, textAlign: 'center' },
  hydroBox: { backgroundColor: colors.card, borderRadius: radii.lg, padding: spacing.md, gap: spacing.md },
  hydroMain: { alignItems: 'center', gap: 4 },
  hydroToggle: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
  hydroToggleLabel: { ...typography.body, fontSize: 14, color: colors.text, flex: 1, marginRight: spacing.sm },
  card: { backgroundColor: colors.card, borderRadius: radii.lg, padding: spacing.md, gap: spacing.sm },
  fieldLabel: { ...typography.body, fontWeight: '700', color: colors.text },
  hint: { ...typography.caption, color: colors.textMuted, marginTop: -spacing.xs },
  grid: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm },
  gridItem: { flexBasis: '47%', flexGrow: 1, gap: 4 },
  input: {
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.sm,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.sm,
    color: colors.text,
  },
  logoutButton: {
    alignItems: 'center',
    paddingVertical: spacing.md,
    borderRadius: radii.md,
    borderWidth: 1,
    borderColor: colors.danger,
  },
  logoutText: { color: colors.danger, fontWeight: '700' },
});
