"use client";

import React, { useMemo, useState } from "react";

type Counts = Record<string, number>;

type DiffRow = {
  productId: number;
  name: string;
  platform: string | null;
  rawCategoryKey: string | null;

  resolvedMerchantId: number | null;

  existingPartRole: string | null;
  existingSource: string | null;
  partRoleLocked: boolean | null;
  platformLocked: boolean | null;

  resolvedPartRole: string | null;
  resolvedSource: string | null;
  resolvedConfidence: number | null;
  resolvedReason: string | null;

  status: string;
  meta?: Record<string, any>;
};

type ReconcileResponse = {
  dryRun: boolean;
  scanned: number;
  counts: Counts;
  samples: DiffRow[];
};

const DEFAULT_LIMIT = 500;
const DEFAULT_PLATFORM = "AR-15";

// Update these if your admin mapping UI lives elsewhere.
const MAPPING_UI_PATH = "/admin/mapping"; // <- change if needed
const API_BASE = process.env.NEXT_PUBLIC_API_BASE_URL ?? "";

const url = `${API_BASE}/admin/classification/reconcile?dryRun=true&limit=500&platform=AR-15&merchantId=4`;



export default function AdminClassificationReconcilePage() {
  const [merchantId, setMerchantId] = useState<string>("4"); // your current test merchant
  const [platform, setPlatform] = useState<string>(DEFAULT_PLATFORM);
  const [limit, setLimit] = useState<number>(DEFAULT_LIMIT);
  const [includeLocked, setIncludeLocked] = useState<boolean>(false);

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [data, setData] = useState<ReconcileResponse | null>(null);

  const [statusFilter, setStatusFilter] = useState<string>("ALL");

  const filteredSamples = useMemo(() => {
    if (!data?.samples) return [];
    if (statusFilter === "ALL") return data.samples;
    return data.samples.filter((r) => r.status === statusFilter);
  }, [data, statusFilter]);

  const uniqueStatuses = useMemo(() => {
    const set = new Set<string>();
    (data?.samples ?? []).forEach((r) => set.add(r.status));
    return ["ALL", ...Array.from(set.values()).sort()];
  }, [data]);

  async function runReconcile() {
    setLoading(true);
    setError(null);
  
    try {
      const params = new URLSearchParams();
      params.set("dryRun", "true");
      params.set("limit", String(limit));
      if (platform?.trim()) params.set("platform", platform.trim());
      if (merchantId?.trim()) params.set("merchantId", merchantId.trim());
      if (includeLocked) params.set("includeLocked", "true");
  
      const API_BASE = process.env.NEXT_PUBLIC_API_BASE_URL ?? "";
      const url = `${API_BASE}/admin/classification/reconcile?${params.toString()}`;
  
      const res = await fetch(url, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({}),
        cache: "no-store",
      });
  
      // Helpful error body (also avoids the "<!DOCTYPE" confusion)
      const text = await res.text();
      if (!res.ok) throw new Error(text || `Request failed (${res.status})`);
  
      const json = JSON.parse(text) as ReconcileResponse;
      setData(json);
    } catch (e: any) {
      setError(e?.message ?? "Unknown error");
      setData(null);
    } finally {
      setLoading(false);
    }
  }
  function mappingLink(row: DiffRow) {
    // Deep-link into existing mapping UI with prefilled values.
    // Adjust param names to match your mapping UI, if needed.
    const qs = new URLSearchParams();
    if (merchantId) qs.set("merchantId", merchantId);
    if (platform) qs.set("platform", platform);
    if (row.rawCategoryKey) qs.set("rawCategoryKey", row.rawCategoryKey);
    return `${MAPPING_UI_PATH}?${qs.toString()}`;
  }

  return (
    <div className="mx-auto max-w-6xl px-6 py-10">
      <div className="mb-8">
        <h1 className="text-2xl font-semibold tracking-tight">Classification Reconcile</h1>
        <p className="mt-2 text-sm text-zinc-400">
          Dry-run inspector for part-role classification. Finds <span className="text-zinc-200">UNMAPPED</span>,{" "}
          <span className="text-zinc-200">IGNORED</span>, rule hits, and drift. (No writes. No regrets.)
        </p>
      </div>

      {/* Controls */}
      <div className="rounded-lg border border-zinc-800 bg-zinc-950/60 p-5">
        <div className="grid grid-cols-1 gap-4 md:grid-cols-5">
          <label className="block">
            <div className="text-xs text-zinc-400">Merchant ID</div>
            <input
              value={merchantId}
              onChange={(e) => setMerchantId(e.target.value)}
              className="mt-1 w-full rounded-md border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100"
              placeholder="4"
            />
          </label>

          <label className="block">
            <div className="text-xs text-zinc-400">Platform</div>
            <select
              value={platform}
              onChange={(e) => setPlatform(e.target.value)}
              className="mt-1 w-full rounded-md border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100"
            >
              <option value="AR-15">AR-15</option>
              <option value="AR-10">AR-10</option>
              <option value="AR-9">AR-9</option>
              <option value="AK-47">AK-47</option>
              <option value="">(any)</option>
            </select>
          </label>

          <label className="block">
            <div className="text-xs text-zinc-400">Limit</div>
            <input
              type="number"
              value={limit}
              onChange={(e) => setLimit(Number(e.target.value))}
              className="mt-1 w-full rounded-md border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100"
              min={1}
              max={20000}
            />
          </label>

          <label className="flex items-end gap-2">
            <input
              type="checkbox"
              checked={includeLocked}
              onChange={(e) => setIncludeLocked(e.target.checked)}
              className="h-4 w-4 accent-zinc-200"
            />
            <span className="text-sm text-zinc-200">Include locked</span>
          </label>

          <div className="flex items-end justify-end">
            <button
              onClick={runReconcile}
              disabled={loading}
              className="inline-flex w-full items-center justify-center rounded-md bg-zinc-100 px-4 py-2 text-sm font-medium text-zinc-900 hover:bg-white disabled:opacity-60 md:w-auto"
            >
              {loading ? "Running…" : "Run reconcile"}
            </button>
          </div>
        </div>

        {error && (
          <div className="mt-4 rounded-md border border-red-900/40 bg-red-950/30 px-4 py-3 text-sm text-red-200">
            {error}
          </div>
        )}
      </div>

      {/* Results */}
      {data && (
        <div className="mt-8 space-y-6">
          <div className="rounded-lg border border-zinc-800 bg-zinc-950/60 p-5">
            <div className="flex flex-wrap items-center justify-between gap-3">
              <div className="text-sm text-zinc-300">
                Scanned: <span className="text-zinc-100 font-medium">{data.scanned}</span> • DryRun:{" "}
                <span className="text-zinc-100 font-medium">{String(data.dryRun)}</span>
              </div>

              <div className="flex items-center gap-2">
                <span className="text-xs text-zinc-400">Filter</span>
                <select
                  value={statusFilter}
                  onChange={(e) => setStatusFilter(e.target.value)}
                  className="rounded-md border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100"
                >
                  {uniqueStatuses.map((s) => (
                    <option key={s} value={s}>
                      {s}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            {/* Counts */}
            <div className="mt-4 grid grid-cols-2 gap-3 md:grid-cols-7">
              {Object.entries(data.counts ?? {}).map(([k, v]) => (
                <div key={k} className="rounded-md border border-zinc-800 bg-zinc-950 px-3 py-2">
                  <div className="text-[11px] uppercase tracking-wider text-zinc-500">{k}</div>
                  <div className="text-lg font-semibold text-zinc-100">{v}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Samples table */}
          <div className="rounded-lg border border-zinc-800 bg-zinc-950/60">
            <div className="flex items-center justify-between border-b border-zinc-800 px-5 py-4">
              <div>
                <div className="text-sm font-medium text-zinc-100">Samples</div>
                <div className="text-xs text-zinc-400">
                  Showing up to 50 interesting rows (UNMAPPED / IGNORED / CONFLICT / WOULD_UPDATE + rule hits).
                </div>
              </div>

              <a
                href={MAPPING_UI_PATH}
                className="text-sm text-zinc-200 underline decoration-zinc-700 underline-offset-4 hover:text-white"
              >
                Go to mappings →
              </a>
            </div>

            <div className="overflow-auto">
              <table className="w-full text-left text-sm">
                <thead className="sticky top-0 bg-zinc-950">
                  <tr className="border-b border-zinc-800 text-xs text-zinc-400">
                    <th className="px-5 py-3">Status</th>
                    <th className="px-5 py-3">Product</th>
                    <th className="px-5 py-3">Raw Category</th>
                    <th className="px-5 py-3">Existing Role</th>
                    <th className="px-5 py-3">Resolved</th>
                    <th className="px-5 py-3">Why</th>
                    <th className="px-5 py-3"></th>
                  </tr>
                </thead>

                <tbody>
                  {filteredSamples.length === 0 ? (
                    <tr>
                      <td colSpan={7} className="px-5 py-6 text-zinc-400">
                        No rows match this filter.
                      </td>
                    </tr>
                  ) : (
                    filteredSamples.map((r) => (
                      <tr key={r.productId} className="border-b border-zinc-900 align-top">
                        <td className="px-5 py-3">
                          <span className="rounded-md border border-zinc-800 bg-zinc-950 px-2 py-1 text-xs text-zinc-200">
                            {r.status}
                          </span>
                          {r.resolvedSource?.startsWith("rules_") && (
                            <div className="mt-2 text-[11px] text-zinc-500">
                              rule: <span className="text-zinc-300">{r.resolvedSource}</span>
                            </div>
                          )}
                        </td>

                        <td className="px-5 py-3">
                          <div className="text-zinc-100">{r.name}</div>
                          <div className="mt-1 text-xs text-zinc-500">
                            #{r.productId} • {r.platform ?? "—"} • merchantUsed: {r.resolvedMerchantId ?? "—"}
                          </div>
                        </td>

                        <td className="px-5 py-3">
                          <div className="text-zinc-200">{r.rawCategoryKey ?? "—"}</div>
                        </td>

                        <td className="px-5 py-3">
                          <div className="text-zinc-200">{r.existingPartRole ?? "—"}</div>
                          <div className="mt-1 text-xs text-zinc-500">
                            src: {r.existingSource ?? "—"}
                            {r.partRoleLocked ? " • locked" : ""}
                            {r.platformLocked ? " • platformLocked" : ""}
                          </div>
                        </td>

                        <td className="px-5 py-3">
                          <div className="text-zinc-100">{r.resolvedPartRole ?? "—"}</div>
                          <div className="mt-1 text-xs text-zinc-500">
                            src: {r.resolvedSource ?? "—"} • conf:{" "}
                            {typeof r.resolvedConfidence === "number" ? r.resolvedConfidence.toFixed(2) : "—"}
                          </div>
                        </td>

                        <td className="px-5 py-3">
                          <div className="text-zinc-300">{r.resolvedReason ?? "—"}</div>
                        </td>

                        <td className="px-5 py-3 text-right">
                          {r.status === "UNMAPPED" && r.rawCategoryKey ? (
                            <a
                              href={mappingLink(r)}
                              className="rounded-md border border-zinc-800 bg-zinc-950 px-3 py-2 text-xs text-zinc-200 hover:text-white"
                            >
                              Map category →
                            </a>
                          ) : (
                            <span className="text-xs text-zinc-600">—</span>
                          )}
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}