import React from 'react';
import { useWindowDimensions } from 'react-native';
import { SleepChart } from '../components/charts';
import { ErrBox, LegendRow, Loading, Panel, Screen, Sec, SrcNote, Tile, TileGrid } from '../components/ui';
import { load } from '../lib/api';
import { fmtDY, hm, num } from '../lib/format';
import { shapeSleep } from '../lib/shape';
import { C } from '../lib/theme';
import type { SleepApiResponse, SleepCycleExport } from '../lib/types';
import { useLoad } from '../lib/use-load';

export default function Sleep() {
  const { width } = useWindowDimensions();
  const chartW = Math.min(608, width - 32) - 28;
  const { data, err, loading, refresh } = useLoad(() =>
    Promise.all([load<SleepApiResponse>('sleepApi'), load<SleepCycleExport>('sleepCycle')]),
  );

  let body: React.ReactNode = null;
  if (loading && !data) body = <Loading />;
  else if (err) body = <ErrBox msg={err} />;
  else if (data) {
    const [api, sc] = data;
    const nights = shapeSleep(api, sc);
    const recent = nights.slice(-30);
    const last7 = nights.slice(-7);
    const avg = (arr: typeof nights, f: (t: (typeof nights)[0]) => number) =>
      arr.reduce((sum, x) => sum + f(x), 0) / (arr.length || 1);
    const a7 = avg(last7, (t) => t.asleep);
    const deepPct =
      avg(last7.filter((t) => t.deep), (t) => t.deep / (t.asleep || 1)) * 100;
    const esNights = nights.filter((t) => t.hrv);
    const lastHrv = esNights.length ? esNights[esNights.length - 1] : null;
    const last = nights[nights.length - 1];

    body = (
      <>
        <TileGrid>
          <Tile label="Last night on record" value={hm(last.asleep)}
            sub={`${fmtDY(last.date)} · ${last.src}`} />
          <Tile label="Avg · last 7 recorded" value={hm(a7)} />
          <Tile label="Deep sleep share" value={deepPct ? deepPct.toFixed(0) : '—'}
            unit={deepPct ? '%' : undefined} sub="of asleep time, when staged" />
          {lastHrv ? (
            <Tile label="HRV · last Eight Sleep night" value={String(Math.round(lastHrv.hrv!))}
              unit="ms" sub={`${fmtDY(lastHrv.date)} · HR ${Math.round(lastHrv.hr!)} bpm`} />
          ) : null}
        </TileGrid>
        <Sec title="Last 30 recorded nights" />
        <Panel title="Time asleep by stage" sub="tap a bar">
          <SleepChart nights={recent} width={chartW} />
          <LegendRow
            items={[
              ['Deep', C.s1], ['REM', C.s2], ['Light / unstaged', C.s3], ['Awake', C.awake],
            ]}
          />
        </Panel>
        <SrcNote>
          Sources: Eight Sleep pod (through Feb 2026, incl. HRV/HR) and Sleep Cycle app export
          (through {sc.exported_at}). {num(nights.length)} nights total on record.
        </SrcNote>
      </>
    );
  }

  return <Screen onRefresh={refresh}>{body}</Screen>;
}
