import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { ErrBox, Loading, Screen, Sec, Tile, TileGrid } from '../components/ui';
import { load } from '../lib/api';
import { agoTxt, fmtDY, hm } from '../lib/format';
import { C } from '../lib/theme';
import type { MeditationSessionsResponse, MeditationStats } from '../lib/types';
import { useLoad } from '../lib/use-load';

export default function Mind() {
  const { data, err, loading, refresh } = useLoad(() =>
    Promise.all([
      load<MeditationStats>('medStats'),
      load<MeditationSessionsResponse>('medSessions'),
    ]),
  );

  let body: React.ReactNode = null;
  if (loading && !data) body = <Loading />;
  else if (err) body = <ErrBox msg={err} />;
  else if (data) {
    const [stats, sess] = data;
    const list = [...(sess.sessions || [])].sort((a, b) => (a.startedAt < b.startedAt ? 1 : -1));
    const rated = list.filter((x) => x.rating);
    const avgR = rated.length ? rated.reduce((sum, x) => sum + x.rating!, 0) / rated.length : null;

    body = (
      <>
        <TileGrid>
          <Tile label="Total time" value={String(stats.totalMinutes)} unit="min"
            sub={`${stats.totalSessions} sessions`} />
          <Tile label="Current streak" value={String(stats.currentStreak)} unit="days" />
          <Tile label="Avg rating" value={avgR ? avgR.toFixed(1) : '—'}
            unit={avgR ? '/ 5' : undefined} sub={`${rated.length} rated`} />
          <Tile label="Last sit"
            value={list.length
              ? hm((new Date(list[0].endedAt).getTime() - new Date(list[0].startedAt).getTime()) / 1000)
              : '—'}
            sub={list.length ? agoTxt(list[0].startedAt) : undefined} />
        </TileGrid>
        <Sec title="Sessions" count={list.length} />
        {list.map((x) => (
          <View key={x.startedAt} style={s.row}>
            <View style={{ flexDirection: 'row', justifyContent: 'space-between', gap: 10 }}>
              <Text style={{ fontSize: 13.5, fontWeight: '500', color: C.text }}>
                {x.actualMin} min
                {!x.completed && (
                  <Text style={{ color: C.yellow, fontSize: 11 }}>
                    {'  '}· {x.completionPct}% of {x.plannedMin}
                  </Text>
                )}
              </Text>
              <Text style={{ fontSize: 11, color: C.muted }}>{fmtDY(x.startedAt)}</Text>
            </View>
            {x.rating ? (
              <Text style={{ color: C.yellow, letterSpacing: 1, fontSize: 12, marginTop: 2 }}>
                {'★'.repeat(x.rating)}{'☆'.repeat(5 - x.rating)}
              </Text>
            ) : null}
            {x.note ? (
              <Text style={{ fontSize: 12, color: C.muted, marginTop: 6, fontStyle: 'italic' }}>
                {x.note}
              </Text>
            ) : null}
          </View>
        ))}
      </>
    );
  }

  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,
  },
});
