"use client";

import Link from "next/link";
import { Plus } from "lucide-react";
import type { UiPart } from "@/types/uiPart";
import { ProductImage } from './ProductImage';

export default function PartsGrid(props: {
  viewMode: "card" | "list";
  parts: UiPart[];
  buildDetailHref: (p: UiPart) => string;

  onAddToBuild?: (p: UiPart) => void;
  addLabel?: string;
}) {
  const { viewMode, parts, buildDetailHref, onAddToBuild } = props;
  const addLabel = props.addLabel ?? "Add to Build";

  // ✅ Only show caliber column if we actually have caliber data
  const showCaliber = parts.some((p) => !!p.caliber);

  // ✅ Single source of truth for grid columns (prevents header/row drift)
  // Columns: Image | Part | Brand | (Caliber?) | Price | Actions
  const gridCols = showCaliber
    ? "md:grid-cols-[44px_minmax(0,1fr)_160px_120px_110px_120px]" // +Caliber
    : "md:grid-cols-[44px_minmax(0,1fr)_160px_110px_120px]"; // no Caliber"md:grid-cols-[44px_minmax(0,1fr)_160px_110px_120px]";

  const formatPrice = (price?: number | null) => {
    if (price == null) return "—";
    return `$${price.toFixed(2)}`;
  };

  if (viewMode === "card") {
    return (
      <div className="grid gap-3 md:grid-cols-2 lg:grid-cols-3">
        {parts.map((part) => {
          const buyHref = part.buyShortUrl ?? part.buyUrl;
          return (
            <div
              key={part.id}
              className="group relative flex flex-col rounded-md border border-zinc-700 bg-zinc-900/50 p-3 transition-all hover:border-amber-400/60 hover:bg-amber-400/10"
            >
              <div className="mb-3 flex items-center justify-between gap-2">
                <div className="min-w-0">
                  <div className="truncate text-sm font-semibold text-zinc-50">
                    {part.brand}{" "}
                    <span className="font-normal">— {part.name}</span>
                  </div>
                </div>

                <div className="whitespace-nowrap text-sm font-semibold text-amber-300">
                  {formatPrice(part.price)}
                </div>
              </div>

              <div className="mt-2 flex gap-2">
                <Link
                  href={buildDetailHref(part)}
                  className="flex-1 rounded-md border border-zinc-700 bg-zinc-800/50 px-3 py-2 text-center text-xs font-medium text-zinc-300 hover:border-zinc-600 hover:bg-zinc-700"
                >
                  View Details
                </Link>

                {onAddToBuild ? (
                  <button
                    type="button"
                    onClick={() => onAddToBuild(part)}
                    className="flex-1 rounded-md bg-amber-400 px-3 py-2 text-center text-xs font-semibold text-black hover:bg-amber-300"
                  >
                    {addLabel}
                  </button>
                ) : buyHref ? (
                  <a
                    href={buyHref}
                    target="_blank"
                    rel="noreferrer"
                    className="flex-1 rounded-md bg-amber-400 px-3 py-2 text-center text-xs font-semibold text-black hover:bg-amber-300"
                  >
                    Buy
                  </a>
                ) : (
                  <button
                    disabled
                    className="flex-1 rounded-md bg-zinc-700 px-3 py-2 text-center text-xs font-semibold text-zinc-200 opacity-50"
                  >
                    No Price
                  </button>
                )}
              </div>
            </div>
          );
        })}
      </div>
    );
  }

  // LIST view
  return (
    <>
      {/* Header (DESKTOP ONLY) */}
      <div
        className={[
          "hidden md:grid md:items-center md:gap-4 px-3 pb-2",
          "text-[0.7rem] uppercase tracking-[0.16em] text-zinc-500",
          gridCols,
        ].join(" ")}
      >
        <span className="text-left">Image</span>
        <span className="min-w-0">Part</span>
        <span className="text-right">Brand</span>
        {showCaliber ? <span className="text-right">Caliber</span> : null}
        <span className="text-right">Price</span>
        <span className="text-right">Actions</span>
      </div>

      {/* Rows */}
      <div className="space-y-2">
        {parts.map((part) => {
          const buyHref = part.buyShortUrl ?? part.buyUrl;

          return (
            <div
              key={part.id}
              className="group relative rounded-md border border-zinc-700 bg-zinc-900/50 p-3 transition-all hover:border-amber-400/60 hover:bg-amber-400/10"
            >
              <div
                className={[
                  "flex flex-col gap-2 md:grid md:items-center md:gap-4",
                  gridCols,
                ].join(" ")}
              >
                {/* Image */}
                <div className="hidden md:block justify-self-start">
                  <ProductImage
                    src={part.imageUrl}
                    alt=""
                    className="h-10 w-10 rounded object-cover border border-zinc-800 bg-zinc-950"
                    loading="lazy"
                  />
                </div>

                {/* Part */}
                <div className="min-w-0">
                  <Link
                    href={buildDetailHref(part)}
                    className="block text-sm font-semibold text-zinc-50 leading-snug line-clamp-2 break-words hover:text-amber-300 transition-colors"
                    title={part.name}
                  >
                    {part.name}
                  </Link>
                </div>

                {/* Brand */}
                <div className="hidden md:block text-sm text-zinc-300 text-right">
                  {part.brand || "—"}
                </div>

                {/* Caliber (optional) */}
                {showCaliber ? (
                  <div className="hidden md:block text-sm text-zinc-300 text-right">
                    {part.caliber ?? "—"}
                  </div>
                ) : null}

                {/* Price */}
                <div className="text-sm font-semibold text-amber-300 md:text-right">
                  {formatPrice(part.price)}
                </div>

                {/* Actions */}
                <div className="flex justify-end gap-2">
                  {onAddToBuild ? (
                    <button
                      type="button"
                      onClick={() => onAddToBuild(part)}
                      className="inline-flex items-center justify-center h-8 w-8 rounded-md bg-amber-400 text-black hover:bg-amber-300 transition-colors"
                      aria-label="Add to Build"
                      title="Add to Build"
                    >
                      <Plus className="h-4 w-4" />
                    </button>
                  ) : buyHref ? (
                    <a
                      href={buyHref}
                      target="_blank"
                      rel="noreferrer"
                      className="whitespace-nowrap rounded-md bg-amber-400 px-3 py-1.5 text-xs font-semibold text-black hover:bg-amber-300"
                    >
                      Buy
                    </a>
                  ) : (
                    <button
                      disabled
                      className="whitespace-nowrap rounded-md bg-zinc-700 px-3 py-1.5 text-xs font-semibold text-zinc-200 opacity-50"
                      title="No buy link available"
                    >
                      No Action
                    </button>
                  )}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </>
  );
}
