import React, { useMemo, useState } from 'react';
import { Pressable, StyleSheet, Text, View, useWindowDimensions } from 'react-native';
import { VolumeChart } from '../components/charts';
import { ErrBox, Loading, Panel, Screen, Sec, Tile, TileGrid } from '../components/ui';
import { load } from '../lib/api';
import { agoTxt, fmtD, fmtDY, num } from '../lib/format';
import { shapeWeeks, weekStart, workoutVolume } from '../lib/shape';
import { C } from '../lib/theme';
import type { Workout, WorkoutsResponse } from '../lib/types';
import { useLoad } from '../lib/use-load';

function WorkoutRow({ w }: { w: Workout }) {
  const [open, setOpen] = useState(false);
  const { vol, sets } = workoutVolume(w);
  const mins = Math.round(
    (new Date(w.end_time).getTime() - new Date(w.start_time).getTime()) / 60000,
  );
  return (
    <Pressable style={s.row} onPress={() => setOpen(!open)}>
      <View style={{ flexDirection: 'row', justifyContent: 'space-between', gap: 10 }}>
        <Text style={{ fontSize: 13.5, fontWeight: '500', color: C.text, flex: 1 }}>{w.title}</Text>
        <Text style={{ fontSize: 11, color: C.muted }}>{fmtDY(w.start_time)}</Text>
      </View>
      <Text style={{ fontSize: 12, color: C.muted, marginTop: 3 }}>
        {mins} min · {w.exercises.length} exercises · {sets} sets · {num(Math.round(vol))} kg
      </Text>
      {open && (
        <View style={s.detail}>
          {(w.exercises || []).map((ex, i) => {
            const ss = (ex.sets || [])
              .map((st) => {
                if (st.reps != null) return st.weight_kg ? `${st.reps}×${st.weight_kg}kg` : `${st.reps}`;
                if (st.duration_seconds) return `${Math.round(st.duration_seconds / 60)}min`;
                return '—';
              })
              .join(', ');
            return (
              <Text key={i} style={{ fontSize: 12, marginVertical: 3 }}>
                <Text style={{ color: C.text }}>{ex.title}</Text>
                <Text style={{ color: C.muted }}>  {ss}</Text>
              </Text>
            );
          })}
        </View>
      )}
    </Pressable>
  );
}

export default function Train() {
  const { width } = useWindowDimensions();
  const chartW = Math.min(608, width - 32) - 28;
  const { data, err, loading, refresh } = useLoad(() => load<WorkoutsResponse>('workouts'));

  const shaped = useMemo(() => {
    if (!data) return null;
    const ws = [...data.workouts].sort((a, b) => (a.start_time < b.start_time ? -1 : 1));
    return { ws, weeks: shapeWeeks(ws, 16) };
  }, [data]);

  let body: React.ReactNode = null;
  if (loading && !data) body = <Loading />;
  else if (err) body = <ErrBox msg={err} />;
  else if (data && shaped) {
    const { ws, weeks } = shaped;
    const thisWk = weekStart(new Date().toISOString());
    const wkCount = ws.filter((w) => weekStart(w.start_time) === thisWk).length;
    const last8 = weeks.slice(-8);
    const avgWk = last8.reduce((sum, w) => sum + w.count, 0) / (last8.length || 1);
    const last = ws[ws.length - 1];

    body = (
      <>
        <TileGrid>
          <Tile label="Workouts logged" value={String(ws.length)} sub="via Hevy" />
          <Tile label="This week" value={String(wkCount)}
            sub={`avg ${avgWk.toFixed(1)}/week over 8 weeks`} />
          <Tile label="Last session" value={last.title} sub={agoTxt(last.start_time)} />
          <Tile label="Last synced" value={fmtD(data.synced_at)} sub="syncs every 6 h" />
        </TileGrid>
        <Sec title="Weekly volume · 16 weeks" />
        <Panel title="Lifted volume (kg)" sub="tap a bar">
          <VolumeChart weeks={weeks} width={chartW} />
        </Panel>
        <Sec title="Recent workouts" />
        {ws.slice(-20).reverse().map((w) => (
          <WorkoutRow key={w.start_time} w={w} />
        ))}
      </>
    );
  }

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

const s = StyleSheet.create({
  row: {
    backgroundColor: C.surface, borderWidth: 1, borderColor: C.border, borderRadius: 12,
    paddingVertical: 12, paddingHorizontal: 14, marginBottom: 8,
  },
  detail: { marginTop: 10, borderTopWidth: 1, borderTopColor: C.border, paddingTop: 10 },
});
