// Değişim istatistikleri: sayfa, admin listesi ve görsel aynı hesabı kullanır.

export type Entry = {
  day: string; // YYYY-MM-DD
  weight: number | null;
  steps: number | null;
  calories: number | null;
  protein: number | null;
  fat: number | null;
  carbs: number | null;
  note?: string | null;
};

export type Goals = {
  start_date: string | null;
  start_weight: number | null;
  goal_weight: number | null;
  goal_date: string | null;
  calorie_goal: number | null;
  step_goal: number | null;
  protein_goal: number | null;
};

export type TrendPoint = {
  day: string;
  weight: number | null;
  avg7: number | null;
  plan: number | null;
};

export type Summary = {
  lastDay: string;
  dayNumber: number; // başlangıçtan bu yana kaçıncı gün (1'den başlar)
  startWeight: number;
  current: number;
  avg7: number | null;
  lost: number; // verilen (pozitif = kilo verildi)
  remaining: number | null; // hedefe kalan
  progressPct: number | null; // kilo hedefinin yüzdesi
  timePct: number | null; // sürenin yüzdesi
  daysLeft: number | null;
  lastWeekChange: number | null; // son 7 gün ortalaması − önceki 7 gün ortalaması
  requiredPerWeek: number | null;
  planToday: number | null;
  planDiff: number | null; // 7 günlük ort − plan (negatif = plandan önde)
  steps: { avg7: number | null; logged: number; hit: number };
  calories: { avg7: number | null; logged: number; hit: number };
  macros: {
    protein: number | null;
    fat: number | null;
    carbs: number | null;
    proteinPct: number | null;
    fatPct: number | null;
    carbsPct: number | null;
  };
};

const DAY_MS = 86_400_000;
export const dayNum = (s: string) => Date.parse(s + 'T00:00:00Z') / DAY_MS;
export const r1 = (x: number | null) => (x === null || !Number.isFinite(x) ? null : Math.round(x * 10) / 10);
export const r0 = (x: number | null) => (x === null || !Number.isFinite(x) ? null : Math.round(x));
const mean = (a: number[]) => (a.length ? a.reduce((s, v) => s + v, 0) / a.length : null);

export function sortEntries(entries: Entry[]): Entry[] {
  return [...entries].sort((a, b) => (a.day < b.day ? -1 : a.day > b.day ? 1 : 0));
}

/** Son tarihten geriye [from, to) gün aralığındaki değerler. */
function windowValues(rows: Entry[], field: keyof Entry, lastDay: number, from: number, to: number): number[] {
  return rows
    .filter((d) => {
      const g = dayNum(d.day);
      return d[field] !== null && d[field] !== undefined && g > lastDay - to && g <= lastDay - from;
    })
    .map((d) => Number(d[field]));
}

function planAt(day: number, startWeight: number, goals: Goals): number | null {
  if (!goals.start_date || !goals.goal_date || goals.goal_weight === null) return null;
  const total = dayNum(goals.goal_date) - dayNum(goals.start_date);
  if (total <= 0) return null;
  const ratio = Math.min(1, Math.max(0, (day - dayNum(goals.start_date)) / total));
  return startWeight - (startWeight - goals.goal_weight) * ratio;
}

export function computeTrend(entries: Entry[], goals: Goals): TrendPoint[] {
  const rows = sortEntries(entries);
  const weighed = rows.filter((d) => d.weight !== null);
  if (!weighed.length) return [];
  const startWeight = goals.start_weight ?? Number(weighed[0].weight);
  return rows.map((d) => {
    const g = dayNum(d.day);
    const win = weighed.filter((e) => dayNum(e.day) > g - 7 && dayNum(e.day) <= g).map((e) => Number(e.weight));
    return {
      day: d.day,
      weight: d.weight === null ? null : Number(d.weight),
      avg7: r1(mean(win)),
      plan: r1(planAt(g, startWeight, goals)),
    };
  });
}

export function computeSummary(entries: Entry[], goals: Goals): Summary | null {
  const rows = sortEntries(entries);
  const weighed = rows.filter((d) => d.weight !== null);
  if (!rows.length || !weighed.length) return null;

  const lastDay = rows[rows.length - 1].day;
  const last = dayNum(lastDay);
  const startWeight = goals.start_weight ?? Number(weighed[0].weight);
  const current = Number(weighed[weighed.length - 1].weight);
  const avg7 = mean(windowValues(rows, 'weight', last, 0, 7));
  const prev7 = mean(windowValues(rows, 'weight', last, 7, 14));
  const startDay = goals.start_date ? dayNum(goals.start_date) : dayNum(rows[0].day);
  const goalDay = goals.goal_date ? dayNum(goals.goal_date) : null;
  const goalW = goals.goal_weight;

  const totalDays = goalDay !== null ? goalDay - startDay : null;
  const elapsed = last - startDay;
  const daysLeft = goalDay !== null ? goalDay - last : null;
  const plan = planAt(last, startWeight, goals);

  const stepGoal = goals.step_goal;
  const calGoal = goals.calorie_goal;
  const withSteps = rows.filter((d) => d.steps !== null);
  const withCal = rows.filter((d) => d.calories !== null);

  const P = mean(windowValues(rows, 'protein', last, 0, 7));
  const F = mean(windowValues(rows, 'fat', last, 0, 7));
  const C = mean(windowValues(rows, 'carbs', last, 0, 7));
  const macroKcal = P !== null && F !== null && C !== null ? P * 4 + F * 9 + C * 4 : null;

  return {
    lastDay,
    dayNumber: elapsed + 1,
    startWeight,
    current,
    avg7: r1(avg7),
    lost: r1(startWeight - current) ?? 0,
    remaining: goalW !== null ? r1(current - goalW) : null,
    progressPct: goalW !== null && startWeight !== goalW ? r0(((startWeight - current) / (startWeight - goalW)) * 100) : null,
    timePct: totalDays && totalDays > 0 ? r0(Math.min(1, Math.max(0, elapsed / totalDays)) * 100) : null,
    daysLeft,
    lastWeekChange: avg7 !== null && prev7 !== null ? r1(avg7 - prev7) : null,
    requiredPerWeek: goalW !== null && daysLeft !== null && daysLeft > 0 ? r1((current - goalW) / (daysLeft / 7)) : null,
    planToday: r1(plan),
    planDiff: plan !== null && avg7 !== null ? r1(avg7 - plan) : null,
    steps: {
      avg7: r0(mean(windowValues(rows, 'steps', last, 0, 7))),
      logged: withSteps.length,
      hit: stepGoal ? withSteps.filter((d) => Number(d.steps) >= stepGoal).length : 0,
    },
    calories: {
      avg7: r0(mean(windowValues(rows, 'calories', last, 0, 7))),
      logged: withCal.length,
      hit: calGoal ? withCal.filter((d) => Number(d.calories) <= calGoal).length : 0,
    },
    macros: {
      protein: r0(P),
      fat: r0(F),
      carbs: r0(C),
      proteinPct: macroKcal ? r0(((P as number) * 4 / macroKcal) * 100) : null,
      fatPct: macroKcal ? r0(((F as number) * 9 / macroKcal) * 100) : null,
      carbsPct: macroKcal ? r0(((C as number) * 4 / macroKcal) * 100) : null,
    },
  };
}

/** Tüm kayıtların ortalaması (görsel için: "ortalama günlük adım" vb.). */
export function overallAverages(entries: Entry[]) {
  const avg = (f: keyof Entry) => r0(mean(entries.filter((d) => d[f] !== null && d[f] !== undefined).map((d) => Number(d[f]))));
  return { steps: avg('steps'), calories: avg('calories'), protein: avg('protein') };
}
