"use client";

import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { ArrowRight, Plus } from "lucide-react";
import { sellerApi } from "@/lib/api/seller";
import type { ApiSellerProduct } from "@/lib/api/types";
import Loader from "@/components/ui/Loader";
import SafeImage from "@/components/ui/SafeImage";
import UpdateButton from "@/app/(dashboard)/seller/products/[id]/updates/UpdateButton";
import { formatValidity, inr } from "@/app/(dashboard)/seller/products/format";
import { formatNumber, formatRelativeAge, formatUnit } from "@/lib/utils";
import Figure from "./Figure";

const LIMIT = 6;

/** `YYYY-MM-DDTHH:mm` already behind us: buyers are being quoted a stale price. */
function isExpired(validity: string | null): boolean {
  if (!validity) return false;
  const at = new Date(validity).getTime();
  return Number.isFinite(at) && at < Date.now();
}

function validityLabel(validity: string | null): string {
  if (!validity) return "Not set";
  return isExpired(validity) ? `Expired ${formatValidity(validity)}` : formatValidity(validity);
}

function dispatchLabel(days: string): string {
  if (days === "") return "—";
  const n = Number(days);
  if (n === 0) return "Same day";
  return `${days} day${n === 1 ? "" : "s"}`;
}

/**
 * The seller's live products with an Update Price button on each, so the daily
 * price change happens from the dashboard instead of product by product. The
 * button opens the same dialog as the product page, and each row shows every
 * value that dialog saves, so a seller can see what is live at a glance.
 */
export default function SellerProductsCard({ token }: { token: string }) {
  const [products, setProducts] = useState<ApiSellerProduct[] | null>(null);
  const [total, setTotal] = useState(0);
  const [failed, setFailed] = useState(false);
  const [savedId, setSavedId] = useState<number | null>(null);

  const load = useCallback(() => {
    sellerApi
      .products(token, { page: 1, perPage: LIMIT, requestStatus: "approved" })
      .then((res) => {
        setProducts(res.data);
        setTotal(res.meta?.total ?? res.data.length);
        setFailed(false);
      })
      .catch(() => setFailed(true));
  }, [token]);

  useEffect(() => {
    load();
  }, [load]);

  return (
    <div className="rounded-xl bg-white p-4 shadow-sm ring-1 ring-gray-100">
      <div className="mb-3 flex items-start justify-between gap-3">
        <div className="min-w-0">
          <h2 className="text-base font-semibold text-gray-900">My Products</h2>
          <p className="text-xs text-gray-500">Buyers are quoted off your last price. Update it here.</p>
        </div>
        <Link href="/seller/products" className="flex shrink-0 items-center gap-1 text-xs text-[#CC1414] hover:underline">
          View all{total > LIMIT ? ` (${total})` : ""} <ArrowRight className="h-3 w-3" />
        </Link>
      </div>

      {products === null ? (
        failed ? (
          <p className="py-4 text-center text-sm text-gray-500">Could not load your products.</p>
        ) : (
          <Loader size="sm" label="Loading products…" className="py-4" />
        )
      ) : products.length === 0 ? (
        <div className="py-4 text-center text-sm text-gray-500">
          <p>No live products yet.</p>
          <Link href="/seller/products/new" className="mt-2 inline-flex items-center gap-1 font-medium text-[#CC1414] hover:underline">
            <Plus className="h-4 w-4" /> Add Product
          </Link>
        </div>
      ) : (
        <ul className="space-y-2">
          {products.map((p) => {
            const stale = !p.price_validity || isExpired(p.price_validity);
            const unit = formatUnit(p.unit?.name);
            const justSaved = savedId === p.id;
            return (
              <li
                key={p.id}
                className={`grid grid-cols-[minmax(0,1fr)_auto] items-center gap-3 rounded-lg border p-3 transition xl:grid-cols-[minmax(0,13rem)_minmax(0,1fr)_auto] ${
                  justSaved ? "border-emerald-200 bg-emerald-50/50" : "border-gray-100 hover:border-[#CC1414]/30 hover:bg-red-50/30"
                }`}
              >
                <div className="flex min-w-0 items-center gap-3">
                  <div className="relative h-10 w-10 shrink-0 overflow-hidden rounded-lg bg-gray-50 ring-1 ring-gray-100">
                    <SafeImage src={p.thumbnail || "/logo.png"} alt={p.name} fill sizes="40px" className="object-cover" />
                  </div>
                  <div className="min-w-0">
                    <Link href={`/seller/products/${p.id}`} className="block truncate text-sm font-semibold text-gray-900 hover:text-[#CC1414]">
                      {p.name}
                    </Link>
                    <div className="flex flex-wrap items-center gap-x-1.5 text-xs text-gray-500">
                      <span className={justSaved ? "font-medium text-emerald-700" : undefined}>
                        {p.updated_at ? `Updated ${formatRelativeAge(p.updated_at)}` : "Not updated yet"}
                      </span>
                      {p.status !== "active" && (
                        <span className="rounded bg-gray-100 px-1.5 text-[10px] font-semibold uppercase text-gray-500">Inactive</span>
                      )}
                    </div>
                  </div>
                </div>

                {/* Last in the row on wide screens; beside the name otherwise. */}
                <div className="xl:order-last">
                  <UpdateButton
                    panel="price"
                    product={p}
                    onSaved={() => {
                      setSavedId(p.id);
                      load();
                    }}
                  />
                </div>

                {/* Every value the price dialog saves. */}
                <dl className="col-span-2 grid grid-cols-2 gap-x-4 gap-y-2 sm:grid-cols-6 xl:col-span-1">
                  <Figure label="Base price">{p.base_price ? inr.format(p.base_price) : "—"}</Figure>
                  <Figure label="Ex price">
                    {p.ex_price ? (
                      <span className="text-[#CC1414]">
                        {inr.format(p.ex_price)} <span className="text-xs font-normal text-gray-500">/ {unit}</span>
                      </span>
                    ) : (
                      "—"
                    )}
                  </Figure>
                  <Figure label="Quantity">
                    {p.quantity !== "" ? `${formatNumber(p.quantity, Number.isInteger(Number(p.quantity)) ? 0 : 2)} ${unit}` : "—"}
                  </Figure>
                  <Figure label="Dispatch within">{dispatchLabel(p.load_within)}</Figure>
                  <Figure label="Price validity" className="col-span-2">
                    <span className={stale ? "text-amber-700" : undefined}>{validityLabel(p.price_validity)}</span>
                  </Figure>
                </dl>
              </li>
            );
          })}
        </ul>
      )}
    </div>
  );
}
