"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { get } from "@/lib/api";
import { Notice, Spinner } from "@/components/ui";
import { DataGrid, type ColDef } from "@/components/DataGrid";
import { StatusBadge } from "@/components/processingStatus";
import { InfoIcon } from "@/components/icons";
import { HistoryModal } from "@/components/panels/QueuePanel";
import { timeAgo } from "@/lib/format";

type Processed = {
  productId: string;
  sku: string | null;
  gtin: string | null;
  productName: string | null;
  variantName: string | null;
  status: string;
  runCount: number;
  finishedAt: string | null;
  score: number | null;
  costChf: number | null;
  message: string | null;
  targeted: boolean;
};

function TargetedCell(p: any) {
  return p.data?.targeted ? (
    <span className="badge bg-blue-100 text-brand" title="Targeted enrichment job — only selected attributes were researched">Targeted</span>
  ) : (
    <span className="text-slate-300">—</span>
  );
}

function InfoCell(p: any) {
  return (
    <button
      type="button"
      className="rounded-sm p-1 text-slate-400 hover:bg-slate-100 hover:text-brand"
      aria-label="Processing history"
      onClick={() => p.context.onInfo(p.data.productId)}
    >
      <InfoIcon className="h-4 w-4" />
    </button>
  );
}

export default function ProcessedPanel() {
  const [items, setItems] = useState<Processed[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [updatedAt, setUpdatedAt] = useState<string | null>(null);
  const [historyId, setHistoryId] = useState<string | null>(null);

  const load = useCallback(async () => {
    try {
      const d = await get<{ count: number; items: Processed[] }>("products/processed");
      setItems(d.items);
      setUpdatedAt(new Date().toISOString());
      setError(null);
    } catch (e) {
      setError((e as Error).message);
    }
  }, []);

  useEffect(() => {
    load();
    const t = setInterval(load, 8000); // refresh as products finish
    return () => clearInterval(t);
  }, [load]);

  const columnDefs = useMemo<ColDef[]>(
    () => [
      { field: "sku", headerName: "SKU", flex: 1, minWidth: 140, valueFormatter: (p: any) => p.value || "—" },
      { field: "gtin", headerName: "GTIN", width: 150, valueFormatter: (p: any) => p.value || "—" },
      { headerName: "Product name", colId: "productName", flex: 1, minWidth: 170, valueGetter: (p: any) => p.data.productName || "—" },
      { field: "variantName", headerName: "Variant", width: 130, valueFormatter: (p: any) => p.value || "—" },
      { headerName: "Job", colId: "targeted", width: 105, cellRenderer: TargetedCell, cellClass: "flex items-center", valueGetter: (p: any) => (p.data.targeted ? "Targeted" : "Full") },
      { field: "status", headerName: "Outcome", width: 150, cellRenderer: (p: any) => <StatusBadge status={String(p.value)} /> },
      { field: "score", headerName: "Score", width: 90, valueFormatter: (p: any) => (p.value != null ? Number(p.value).toFixed(2) : "—") },
      { field: "costChf", headerName: "Cost (CHF)", width: 110, valueFormatter: (p: any) => (p.value != null ? Number(p.value).toFixed(4) : "—") },
      { field: "runCount", headerName: "Runs", width: 80 },
      {
        field: "finishedAt",
        headerName: "Processed",
        width: 150,
        valueFormatter: (p: any) => (p.value ? new Date(p.value).toLocaleString() : "—"),
      },
      { headerName: "", colId: "info", width: 64, sortable: false, filter: false, cellRenderer: InfoCell, cellClass: "flex items-center justify-center", pinned: "right" },
    ],
    [],
  );

  if (error) return <Notice kind="error">Could not load processed products: {error}</Notice>;
  if (!items) return <Spinner label="Loading processed products…" />;

  return (
    <>
      <p className="mb-3 text-sm text-slate-600">
        Every product that has finished processing — <strong>Done</strong>, <strong>Review</strong> or
        <strong> Failed</strong>. Click the ⓘ to open the full history (progress, attribute overview, gallery and log) for
        what was done on a product.
      </p>
      <div className="mb-3 text-xs text-slate-500" aria-live="polite">
        {items.length} processed · updated {timeAgo(updatedAt || undefined)}
      </div>

      <DataGrid
        rowData={items}
        columnDefs={columnDefs}
        height={560}
        getRowId={(p: any) => String(p.data.productId)}
        context={{ onInfo: (id: string) => setHistoryId(id) }}
      />

      <HistoryModal productId={historyId} onClose={() => setHistoryId(null)} />
    </>
  );
}
