import { Suspense } from "react";
import Link from "next/link";
import { ArrowRight, Search, TrendingDown, TrendingUp, Minus, LineChart } from "lucide-react";
import { catalogApi } from "@/lib/api/catalog";
import type { ApiIngotPrice } from "@/lib/api/types";
import { Skeleton, TableSkeleton } from "@/components/ui/Skeleton";
import { formatCurrency, formatDateTime, formatRelativeAge } from "@/lib/utils";

export const metadata = {
  title: "Live Steel Raw Material Prices – Biznie",
  description: "Latest market rates for MS ingot, billet, sponge iron and steel raw materials across Indian markets.",
};

export const revalidate = 60;

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

async function safeFetch(location?: string) {
  try {
    return await catalogApi.prices({ location }, { next: { revalidate: 60 } });
  } catch {
    return { success: true as const, data: [] as ApiIngotPrice[], meta: { products: [] as string[], markets: 0, total: 0 } };
  }
}

/**
 * The heading names what the table actually holds. It used to be hard-coded
 * "Live Aluminium Ingot Prices" above a table of MS ingot rates (B16).
 */
function headingFor(products: string[]): string {
  if (products.length === 1) return `Live ${products[0]} Prices`;
  if (products.length === 2) return `Live ${products[0]} & ${products[1]} Prices`;
  return "Live Steel Raw Material Prices";
}

/**
 * Banner and the sign-up CTA don't depend on the filter, so they stream out
 * first and the board fills in behind them.
 */
export default function PricesPage({ searchParams }: PageProps) {
  return (
    <div className="min-h-screen bg-gray-50">
      <Suspense fallback={<Banner title="Live Market Prices" subtitle="Latest rates by product and market." />}>
        <PricesBanner searchParams={searchParams} />
      </Suspense>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        <Suspense
          fallback={
            <>
              <Skeleton className="mb-6 h-[74px] w-full rounded-2xl" />
              <TableSkeleton rows={10} />
            </>
          }
        >
          <PricesTable searchParams={searchParams} />
        </Suspense>

        <div className="mt-8 bg-gradient-to-r from-[#CC1414] to-[#8B0000] rounded-2xl p-8 text-white text-center">
          <h3 className="text-xl font-bold mb-2">Get Price Alerts &amp; Live Updates</h3>
          <p className="text-red-100 text-sm mb-5">Register free and get notified when prices change for your materials</p>
          <Link
            href="/login"
            className="inline-flex bg-white text-[#CC1414] font-bold px-6 py-3 rounded-xl text-sm hover:bg-gray-100 transition-colors"
          >
            Register Free <ArrowRight size={16} className="ml-2 self-center" />
          </Link>
        </div>
      </div>
    </div>
  );
}

function Banner({ title, subtitle }: { title: string; subtitle: string }) {
  return (
    <div className="bg-gradient-to-r from-[#CC1414] to-[#8B0000] text-white py-14">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <h1 className="text-3xl md:text-4xl font-black mb-3">{title}</h1>
        <p className="text-red-100 text-base max-w-2xl">{subtitle}</p>
      </div>
    </div>
  );
}

async function PricesBanner({ searchParams }: PageProps) {
  const sp = await searchParams;
  const { data, meta } = await safeFetch(sp.location?.trim() || undefined);
  const markets = Array.from(new Set(data.map((row) => row.market).filter(Boolean)));
  const subtitle = markets.length
    ? `Latest rates at ${markets.join(", ")} — one row per product and market, with the move since the previous update.`
    : "Latest rates by product and market.";
  return <Banner title={headingFor(meta.products)} subtitle={subtitle} />;
}

function Change({ row }: { row: ApiIngotPrice }) {
  if (row.change === null) return <span className="text-xs text-gray-400">—</span>;
  const up = row.change > 0;
  const flat = row.change === 0;
  const Icon = flat ? Minus : up ? TrendingUp : TrendingDown;
  const tone = flat ? "text-gray-500" : up ? "text-emerald-600" : "text-[#CC1414]";
  return (
    <span className={`inline-flex items-center gap-1 text-sm font-semibold tabular-nums ${tone}`}>
      <Icon size={14} aria-hidden />
      {flat ? "No change" : `${up ? "▲" : "▼"} ${formatCurrency(Math.abs(row.change))}`}
      {!flat && row.change_pct !== null && <span className="text-xs font-normal">({Math.abs(row.change_pct).toFixed(2)}%)</span>}
    </span>
  );
}

async function PricesTable({ searchParams }: PageProps) {
  const sp = await searchParams;
  const location = sp.location?.trim() || undefined;
  const { data: prices } = await safeFetch(location);

  return (
    <>
      <form action="/prices" method="get" className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 mb-6 flex gap-3">
        <div className="relative flex-1">
          <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
          <input
            type="text"
            name="location"
            defaultValue={location || ""}
            placeholder="Filter by market (e.g. Raipur, Gobindgarh)..."
            className="w-full pl-9 pr-4 py-2.5 text-sm text-gray-900 placeholder:text-gray-400 bg-white border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#CC1414]/20 focus:border-[#CC1414]"
          />
        </div>
        <button type="submit" className="bg-[#CC1414] text-white px-5 py-2.5 rounded-lg text-sm font-semibold hover:bg-[#A50E0E] transition-colors">
          Search
        </button>
      </form>

      <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
        <div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
          <h2 className="font-bold text-gray-900">Market Prices</h2>
          <span className="text-xs text-gray-400">
            {prices.length} {prices.length === 1 ? "market" : "markets"}
          </span>
        </div>

        <div className="overflow-x-auto">
          {prices.length === 0 ? (
            <div className="p-12 text-center text-sm text-gray-500">
              No price entries available{location ? ` for "${location}"` : ""}.
            </div>
          ) : (
            <table className="w-full min-w-[760px]">
              <thead>
                <tr className="bg-gray-50 text-left">
                  {["Product", "Market", "Price", "Change", "Updated", "Source", ""].map((h) => (
                    <th key={h} className="px-5 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap">
                      {h}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50">
                {prices.map((item) => (
                  <tr key={item.id} className="hover:bg-gray-50 transition-colors">
                    <td className="px-5 py-4 text-sm font-semibold text-gray-900 whitespace-nowrap">{item.product}</td>
                    <td className="px-5 py-4 text-sm text-gray-700 whitespace-nowrap">{item.market || "Pan India"}</td>
                    <td className="px-5 py-4 whitespace-nowrap">
                      <span className="text-sm font-bold text-gray-900 tabular-nums">
                        {item.price !== null ? formatCurrency(item.price) : "—"}
                      </span>
                      <span className="text-xs text-gray-400 ml-1">/{item.unit}</span>
                    </td>
                    <td className="px-5 py-4 whitespace-nowrap">
                      <Change row={item} />
                    </td>
                    <td className="px-5 py-4 text-xs text-gray-500 whitespace-nowrap">
                      {/* Always with the year: a rate from January must not read as today's (B17). */}
                      <div>{formatDateTime(item.date_time)}</div>
                      <div className="text-gray-400">{formatRelativeAge(item.date_time)}</div>
                    </td>
                    <td className="px-5 py-4 text-xs text-gray-500 whitespace-nowrap">{item.source || "Biznie market desk"}</td>
                    <td className="px-5 py-4 whitespace-nowrap text-right">
                      <div className="flex justify-end gap-3">
                        <Link
                          href={`/historical-data?id=${item.id}`}
                          className="inline-flex items-center gap-1 text-xs font-semibold text-gray-600 hover:text-[#CC1414]"
                        >
                          <LineChart size={13} aria-hidden /> History
                        </Link>
                        <Link href="/contact" className="text-xs font-semibold text-[#CC1414] hover:underline">
                          Get Quote →
                        </Link>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </>
  );
}
