import type { ReactNode } from 'react';
import type { StatsBucket } from './shared';
import { ArrowDownToLine, ArrowUpFromLine, HardDrive, Loader2 } from 'lucide-react';
import { formatDuration, formatRatio, formatSize, formatSpeed } from './format';
import { useFreeSpace, useSession, useSessionStats, useTorrents } from './useTransmissionData';

// Session statistics. Two columns because Transmission keeps two counters and conflating them is a classic
// misreading — "this session" resets when the daemon restarts, "all time" never does.

export const StatsView = () => {
  const { stats, isLoading } = useSessionStats();
  const { session } = useSession();
  const { torrents } = useTorrents();
  const downloadDir = session?.['download-dir'];
  const { bytes: freeBytes } = useFreeSpace(downloadDir);

  if (isLoading && !stats) {
    return (
      <div className="flex h-full items-center justify-center text-sm text-muted-foreground">
        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
        Loading statistics…
      </div>
    );
  }

  if (!stats) {
    return <div className="flex h-full items-center justify-center text-sm text-muted-foreground">No statistics.</div>;
  }

  const totalSize = torrents.reduce((sum, t) => sum + (t.totalSize ?? 0), 0);
  const onDisk = torrents.reduce((sum, t) => sum + (t.haveValid ?? 0), 0);

  return (
    <div className="h-full overflow-y-auto p-4">
      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <Tile
          icon={<ArrowDownToLine className="h-4 w-4 text-blue-500" />}
          label="Download"
          value={formatSpeed(stats.downloadSpeed) || '0 B/s'}
        />
        <Tile
          icon={<ArrowUpFromLine className="h-4 w-4 text-emerald-500" />}
          label="Upload"
          value={formatSpeed(stats.uploadSpeed) || '0 B/s'}
        />
        <Tile label="Torrents" value={String(stats.torrentCount)} hint={`${stats.activeTorrentCount} active`} />
        <Tile
          icon={<HardDrive className="h-4 w-4 text-muted-foreground" />}
          label="Free space"
          value={freeBytes == null ? '—' : formatSize(freeBytes)}
          hint={downloadDir}
        />
      </div>

      <div className="mt-4 grid gap-4 lg:grid-cols-2">
        <Bucket title="This session" bucket={stats['current-stats']} />
        <Bucket title="All time" bucket={stats['cumulative-stats']} />
      </div>

      <section className="mt-4 rounded-xl border border-border p-4">
        <h3 className="mb-3 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">Local library</h3>
        <dl className="grid gap-x-6 gap-y-1.5 text-xs sm:grid-cols-2">
          <Row label="Torrents" value={String(torrents.length)} />
          <Row label="Paused" value={String(stats.pausedTorrentCount)} />
          <Row label="Total size" value={formatSize(totalSize)} />
          {/* haveValid, not totalSize: an unfinished or partially-wanted torrent occupies less than it
              claims, and the difference is the whole reason to look. */}
          <Row label="Verified on disk" value={formatSize(onDisk)} />
        </dl>
      </section>
    </div>
  );
};

const Bucket = ({ title, bucket }: { title: string; bucket: StatsBucket }) => (
  <section className="rounded-xl border border-border p-4">
    <h3 className="mb-3 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">{title}</h3>
    <dl className="grid gap-x-6 gap-y-1.5 text-xs sm:grid-cols-2">
      <Row label="Downloaded" value={formatSize(bucket.downloadedBytes)} />
      <Row label="Uploaded" value={formatSize(bucket.uploadedBytes)} />
      <Row
        label="Ratio"
        value={formatRatio(bucket.downloadedBytes > 0 ? bucket.uploadedBytes / bucket.downloadedBytes : -1)}
      />
      <Row label="Torrents added" value={bucket.filesAdded.toLocaleString()} />
      <Row label="Running time" value={formatDuration(bucket.secondsActive)} />
      <Row label="Sessions" value={bucket.sessionCount.toLocaleString()} />
    </dl>
  </section>
);

type TileProps = { label: string; value: string; hint?: string; icon?: ReactNode };

const Tile = ({ label, value, hint, icon }: TileProps) => (
  <div className="rounded-xl border border-border p-4">
    <div className="flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground">
      {icon}
      {label}
    </div>
    <div className="mt-1 text-xl font-semibold tabular-nums">{value}</div>
    {hint && (
      <div className="mt-0.5 truncate text-xs text-muted-foreground" title={hint}>
        {hint}
      </div>
    )}
  </div>
);

const Row = ({ label, value }: { label: string; value: string }) => (
  <div className="flex items-baseline gap-3">
    <dt className="w-32 shrink-0 text-muted-foreground">{label}</dt>
    <dd className="tabular-nums">{value}</dd>
  </div>
);
