import { Suspense } from "react";
import Link from "next/link";
import { TrendingUp, ArrowLeft } from "lucide-react";
import { catalogApi } from "@/lib/api/catalog";
import type { ApiIngotPrice } from "@/lib/api/types";
import PageHeader from "@/components/ui/PageHeader";
import PriceTrendChart, { MIN_TREND_POINTS } from "@/components/products/PriceTrendChart";
import { Skeleton, TableSkeleton } from "@/components/ui/Skeleton";
import { formatCurrency, formatDateShort, formatDateTime } from "@/lib/utils";

export const metadata = {
  title: "Historical Prices – Biznie",
  description: "View historical price trends for steel raw materials across Indian markets.",
};

export const revalidate = 120;

type PageProps = { searchParams: Promise<{ id?: string }> };

async function loadHistory(id: number) {
  try {
    return await catalogApi.priceHistory(id, { next: { revalidate: 120 }, limit: 90 });
  } catch {
    return { success: true as const, data: [] as ApiIngotPrice[], meta: { product: "", market: "" } };
  }
}

async function loadBoard() {
  try {
    return (await catalogApi.prices({}, { next: { revalidate: 120 } })).data;
  } catch {
    return [] as ApiIngotPrice[];
  }
}

/**
 * Header and back-link stream immediately; the market list and price series
 * arrive behind the boundary.
 */
export default function HistoricalDataPage({ searchParams }: PageProps) {
  return (
    <div className="min-h-screen bg-gray-50">
      <PageHeader title="Historical Price Data" subtitle="Track raw material price movements over time." />

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        <Link href="/prices" className="inline-flex items-center gap-1 text-sm text-[#CC1414] font-semibold hover:underline mb-5">
          <ArrowLeft size={14} /> Back to Live Prices
        </Link>

        <Suspense
          fallback={
            <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
              <aside className="lg:col-span-4 bg-white border border-gray-100 rounded-2xl shadow-sm p-4">
                <Skeleton className="mb-3 h-4 w-24" />
                <div className="space-y-2">
                  {Array.from({ length: 6 }).map((_, i) => (
                    <Skeleton key={i} className="h-10 w-full rounded-lg" />
                  ))}
                </div>
              </aside>
              <section className="lg:col-span-8">
                <TableSkeleton rows={10} />
              </section>
            </div>
          }
        >
          <HistoryBody searchParams={searchParams} />
        </Suspense>
      </div>
    </div>
  );
}

async function HistoryBody({ searchParams }: PageProps) {
  const sp = await searchParams;
  const idNum = sp.id ? Number(sp.id) : NaN;

  // The sidebar is the board itself: one row per product × market. It used to
  // be the 100 newest price rows, i.e. the same market listed 100 times (B18).
  const markets = await loadBoard();
  const targetId = Number.isFinite(idNum) ? idNum : markets[0]?.id;
  const { data: history, meta } = targetId ? await loadHistory(targetId) : { data: [] as ApiIngotPrice[], meta: { product: "", market: "" } };

  const selectedKey = history.length ? `${history[0].product}|${history[0].location}` : null;
  const points = history
    .filter((row) => row.price !== null)
    .map((row) => ({ label: formatDateShort(row.date_time).replace(/ \d{2}(\d{2})$/, " $1"), value: row.price as number }));
  const newestFirst = [...history].reverse();

  return (
    <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
      <aside className="lg:col-span-4 bg-white border border-gray-100 rounded-2xl shadow-sm p-4 lg:max-h-[600px] lg:overflow-y-auto">
        <h2 className="font-bold text-gray-900 mb-3 text-sm uppercase tracking-wider">Markets</h2>
        {markets.length === 0 ? (
          <p className="text-sm text-gray-500">No markets available.</p>
        ) : (
          <ul className="space-y-1">
            {markets.map((m) => {
              const isActive = selectedKey ? `${m.product}|${m.location}` === selectedKey : m.id === targetId;
              return (
                <li key={m.id}>
                  <Link
                    href={`/historical-data?id=${m.id}`}
                    className={`flex items-center justify-between gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${
                      isActive ? "bg-[#CC1414] text-white font-semibold" : "text-gray-700 hover:bg-gray-50"
                    }`}
                  >
                    <span className="min-w-0">
                      <span className="block truncate">{m.market}</span>
                      <span className={`block text-xs ${isActive ? "text-red-100" : "text-gray-400"}`}>{m.product}</span>
                    </span>
                    <span className={`tabular-nums ${isActive ? "text-red-100" : "text-gray-500"}`}>
                      {m.price !== null ? formatCurrency(m.price) : "—"}
                    </span>
                  </Link>
                </li>
              );
            })}
          </ul>
        )}
      </aside>

      <section className="lg:col-span-8 space-y-6">
        {points.length >= MIN_TREND_POINTS && (
          <PriceTrendChart
            points={points}
            unit="MT"
            title={`${meta.product} — ${meta.market}`}
            subtitle={`Last ${points.length} updates, ₹ per MT`}
          />
        )}

        <div className="bg-white border border-gray-100 rounded-2xl shadow-sm overflow-hidden">
          <div className="px-5 py-4 border-b border-gray-100 flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-red-50 flex items-center justify-center text-[#CC1414]">
              <TrendingUp size={18} />
            </div>
            <div>
              <h2 className="font-bold text-gray-900">{meta.market ? `${meta.product} · ${meta.market}` : "Price History"}</h2>
              <p className="text-xs text-gray-500">{history.length} entries</p>
            </div>
          </div>

          {history.length === 0 ? (
            <div className="p-12 text-center text-sm text-gray-500">No historical data available.</div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full min-w-[560px] text-sm">
                <thead className="bg-gray-50 text-gray-600">
                  <tr>
                    <th className="text-left px-5 py-3 font-semibold">Date &amp; Time</th>
                    <th className="text-left px-5 py-3 font-semibold">Market</th>
                    <th className="text-right px-5 py-3 font-semibold">Price (₹/MT)</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {newestFirst.map((row) => (
                    <tr key={row.id} className="hover:bg-gray-50">
                      <td className="px-5 py-3 text-gray-700">{formatDateTime(row.date_time)}</td>
                      <td className="px-5 py-3 text-gray-700">{row.market || "—"}</td>
                      <td className="px-5 py-3 text-right font-semibold text-gray-900 tabular-nums">
                        {row.price !== null ? formatCurrency(row.price) : "—"}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </section>
    </div>
  );
}
