// Reports screen — pulls signal history stats + algo stats and renders KPIs.
import React from "react";
import { View, ScrollView, RefreshControl } from "react-native";
import { useQuery } from "@tanstack/react-query";
import { Card, H1, H2, Muted, Row, Pill, Body } from "@/components/ui";
import { colors, spacing } from "@/theme";
import { api } from "@/api/client";

export default function ReportsScreen() {
  const history = useQuery({
    queryKey: ["signal-history-stats"],
    queryFn: () => api.signalHistory({ limit: 1 }),
    refetchInterval: 30_000,
  });
  const algo = useQuery({
    queryKey: ["algo-stats"],
    queryFn: () => api.algoStats(),
    refetchInterval: 30_000,
  });

  const s = (history.data?.stats ?? {}) as Record<string, number>;
  const refreshing = history.isFetching || algo.isFetching;
  const onRefresh = () => { history.refetch(); algo.refetch(); };

  return (
    <ScrollView
      style={{ backgroundColor: colors.bg }}
      contentContainerStyle={{ padding: spacing.lg }}
      refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={colors.primary} />}
    >
      <H1>Reports</H1>
      <Muted>Signals · Algorithms · Hit rate</Muted>
      <View style={{ height: spacing.md }} />
      <Row style={{ gap: spacing.sm }}>
        <Card style={{ flex: 1 }}>
          <Muted>Hit rate</Muted>
          <H2 style={{ color: colors.long }}>{Number(s.hit_rate_pct ?? 0).toFixed(1)}%</H2>
          <Muted>{s.target_hit ?? 0}/{s.resolved ?? 0} resolved</Muted>
        </Card>
        <Card style={{ flex: 1 }}>
          <Muted>Total signals</Muted>
          <H2>{s.total ?? 0}</H2>
          <Muted>{s.pending ?? 0} pending</Muted>
        </Card>
      </Row>
      <Row style={{ gap: spacing.sm }}>
        <Card style={{ flex: 1 }}>
          <Muted>Target hits</Muted>
          <H2 style={{ color: colors.long }}>{s.target_hit ?? 0}</H2>
        </Card>
        <Card style={{ flex: 1 }}>
          <Muted>Stop hits</Muted>
          <H2 style={{ color: colors.short }}>{s.stop_hit ?? 0}</H2>
        </Card>
        <Card style={{ flex: 1 }}>
          <Muted>Expired</Muted>
          <H2 style={{ color: colors.warn }}>{s.expired ?? 0}</H2>
        </Card>
      </Row>

      <View style={{ height: spacing.md }} />
      <H2>Algorithm comparison</H2>
      {(algo.data?.items ?? []).length === 0 && <Muted>No algorithm data yet.</Muted>}
      {(algo.data?.items ?? []).map((a) => (
        <Card key={String(a.algo)}>
          <Row style={{ justifyContent: "space-between" }}>
            <View style={{ flex: 1 }}>
              <Body style={{ fontWeight: "700" }}>{String(a.algo_name ?? a.algo)}</Body>
              <Muted>{a.total} total · {a.resolved} resolved · avg conf {a.avg_confidence_pct}%</Muted>
            </View>
            <Pill
              label={`${Number(a.hit_rate_pct ?? 0).toFixed(0)}% hit`}
              tone={Number(a.hit_rate_pct ?? 0) >= 55 ? "long" : "warn"}
            />
          </Row>
        </Card>
      ))}
    </ScrollView>
  );
}
