"use client";

import type { ReactNode } from "react";
import { useEffect, useState } from "react";
import Drawer from "./Drawer";
import { TruckIcon } from "../dashboard/icons";
import { getImageUrl } from "@/lib/imageUrl";
import { formatListingNo } from "@/lib/listingNo";

export type ProductDetailsData = {
  id: string;
  listingNo?: number | string;
  product: string;
  brand: string;
  modelNumber: string;
  category: string;
  price: string;
  workingCondition: string;
  physicalCondition: string;
  negotiable: boolean;
  currency: string;
  country: string;
  description: string;
  accessoriesIncluded: string;
  optionalAccessories?: string;
  detailedNotes?: string;
  images?: Array<{ url: string } | string> | string[];
};

function ProductImagePlaceholder({ className = "" }: { className?: string }) {
  return (
    <div className={`flex items-center justify-center bg-[#F2F4F7] ${className}`}>
      <svg width="42%" height="42%" viewBox="0 0 32 32" fill="none" aria-hidden="true">
        <rect x="3" y="10" width="20" height="14" rx="2.5" stroke="#98A2B3" strokeWidth="1.4" />
        <path d="M23 14.5 29 12v10l-6-2.5" stroke="#98A2B3" strokeWidth="1.4" strokeLinejoin="round" />
        <circle cx="13" cy="17" r="4.2" stroke="#98A2B3" strokeWidth="1.4" />
        <rect x="9" y="7" width="6" height="3.5" rx="1" stroke="#98A2B3" strokeWidth="1.4" />
      </svg>
    </div>
  );
}

function HighlightRow({ label, value }: { label: string; value: string }) {
  return (
    <li className="flex items-start gap-2 text-[13px] text-[#344054]">
      <span className="mt-1.5 h-1 w-1 shrink-0 rounded-full bg-[#344054]" />
      <span>
        {label}: <span className="font-medium text-[#101828]">{value}</span>
      </span>
    </li>
  );
}

// One free-text block of the product description; keeps the seller's line breaks, "-" when empty
function DescriptionSection({ title, value }: { title: string; value?: string }) {
  const text = value?.trim();
  return (
    <div className="mt-3 first-of-type:mt-1">
      <h4 className="text-[15px] font-semibold text-[#101828]">{title}</h4>
      <p className="mt-2 whitespace-pre-line break-words text-[13px] leading-6 text-[#475467]">{text || "-"}</p>
    </div>
  );
}

export default function ProductDetailsDrawer({
  product,
  open,
  onClose,
  footer,
}: {
  product: ProductDetailsData | null;
  open: boolean;
  onClose: () => void;
  footer: ReactNode;
}) {
  const [activeThumb, setActiveThumb] = useState(0);
  const [imgErrors, setImgErrors] = useState<Record<number, boolean>>({});

  useEffect(() => {
    setActiveThumb(0);
    setImgErrors({});
  }, [product?.id]);

  const displayListingNo = formatListingNo(product?.listingNo);

  const rawImages = ((): any[] => {
    const src = product?.images;
    if (Array.isArray(src)) {
      return src;
    }
    if (typeof src === "string" && (src as string).trim()) {
      try {
        const parsed = JSON.parse(src);
        if (Array.isArray(parsed)) return parsed;
      } catch {}
      return [(src as string).trim()];
    }
    return [];
  })();

  const normalizedImages = rawImages
    .map((img) => (typeof img === "string" ? getImageUrl(img) : getImageUrl(img?.url)))
    .filter(Boolean) as string[];

  const currentImg = normalizedImages[activeThumb] || normalizedImages[0];
  const hasValidMainImg = Boolean(currentImg && !imgErrors[activeThumb]);

  return (
    <Drawer open={open && product !== null} onClose={onClose} title="Product Details" width="873px" footer={footer}>
      {product && (
        <>
          <div className="flex flex-col gap-6 md:flex-row">
            <div className="shrink-0">
              {hasValidMainImg ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={currentImg}
                  alt={product.product}
                  className="h-[220px] w-[300px] rounded-xl object-cover border border-[#E4E7EC]"
                  onError={() => setImgErrors((prev) => ({ ...prev, [activeThumb]: true }))}
                />
              ) : (
                <ProductImagePlaceholder className="h-[220px] w-[300px] rounded-xl" />
              )}

              {normalizedImages.length > 0 && (
                <div className="mt-2 flex flex-wrap gap-2 max-w-[300px]">
                  {normalizedImages.map((img, index) => (
                    <button
                      key={index}
                      type="button"
                      onClick={() => setActiveThumb(index)}
                      className={`h-[54px] w-[54px] overflow-hidden rounded-lg border-2 transition-all cursor-pointer ${
                        activeThumb === index ? "border-[#1657D9] ring-2 ring-[#1657D9]/20" : "border-[#E4E7EC] hover:border-[#B9D0FF]"
                      }`}
                    >
                      {!imgErrors[index] ? (
                        // eslint-disable-next-line @next/next/no-img-element
                        <img
                          src={img}
                          alt={`thumb-${index}`}
                          className="h-full w-full object-cover"
                          onError={() => setImgErrors((prev) => ({ ...prev, [index]: true }))}
                        />
                      ) : (
                        <ProductImagePlaceholder className="h-full w-full" />
                      )}
                    </button>
                  ))}
                </div>
              )}
            </div>

            <div className="min-w-0 flex-1">
              <h3 className="text-[22px] font-bold text-[#101828]">{product.product}</h3>
              <div className="mt-2 flex items-center gap-2">
                <span className="rounded-md bg-[#EAF1FF] px-2 py-0.5 text-[12px] font-medium text-[#1657D9]">
                  {displayListingNo}
                </span>
                <span className="text-[13px] text-[#667085]">
                  {product.brand} {product.modelNumber !== "-" ? product.modelNumber : ""}
                </span>
              </div>

              <div className="mt-3 rounded-xl bg-[#F5F8FF] p-3.5">
                <p className="text-[14px] font-semibold text-[#1657D9]">
                  Don&apos;t Pay Too Much! Same Product - Better Price
                </p>
                <p className="mt-1.5 text-[12px] leading-5 text-[#1657D9]">
                  We can source the Same Product for often a Better Price &amp; your fully Covered.
                </p>
                <p className="mt-1.5 text-[12px] leading-5 text-[#1657D9]">
                  Package Deals &amp; Trade-ins may also be Available as well as Ex demo and good quality used. Ask
                  us for a quote!
                </p>
                <div className="mt-2 flex items-start gap-1.5">
                  <span className="mt-0.5 text-[#1657D9]">
                    <TruckIcon />
                  </span>
                  <p className="text-[12px] leading-5 text-[#1657D9]">
                    Full Local Warranty and Free Delivery within {product.country} for all Used Equipment.
                  </p>
                </div>
              </div>

              <p className="mt-4 text-[13px] leading-6 text-[#475467]">{product.description}</p>
            </div>
          </div>

          <div className="mt-6 rounded-xl bg-[#F5F7F9] p-4">
            <h4 className="text-[15px] font-semibold text-[#101828]">Product Highlights</h4>
            <div className="mt-3 grid grid-cols-1 gap-x-8 gap-y-2.5 sm:grid-cols-2">
              <ul className="space-y-2.5">
                <HighlightRow label="Manufacturer" value={product.brand} />
                <HighlightRow label="Model Number" value={product.modelNumber} />
                <HighlightRow label="Working Condition" value={product.workingCondition} />
                <HighlightRow label="Physical Condition" value={product.physicalCondition} />
                <HighlightRow label="Price EX GST" value={product.price} />
              </ul>
              <ul className="space-y-2.5">
                <HighlightRow label="Negotiable" value={product.negotiable ? "Yes" : "No"} />
                <HighlightRow label="Currency" value={product.currency} />
                <HighlightRow label="Country" value={product.country} />
                <HighlightRow label="Listing Number" value={displayListingNo} />
                <HighlightRow label="Category" value={product.category} />
              </ul>
            </div>
          </div>

          <div className="mt-6">
            <p className="text-[11px] font-semibold uppercase tracking-wide text-[#1657D9]">Product Description</p>
            <DescriptionSection title="Accessories Included" value={product.accessoriesIncluded} />
            <DescriptionSection title="Optional Accessories" value={product.optionalAccessories} />
            <DescriptionSection title="Detailed Notes / Specifications" value={product.detailedNotes} />
          </div>

          <div className="mt-6">
            <p className="text-[11px] font-semibold uppercase tracking-wide text-[#1657D9]">Technical Data</p>
            <h4 className="mt-1 text-[15px] font-semibold text-[#101828]">Technical Details</h4>

            <div className="mt-3 overflow-hidden rounded-xl border border-[#E4E7EC]">
              {[
                ["Manufacturer", product.brand],
                ["Model Number", product.modelNumber],
                ["Working Condition", product.workingCondition],
                ["Physical Condition", product.physicalCondition],
                ["Price EX GST", product.price],
                ["Negotiable", product.negotiable ? "Yes" : "No"],
                ["Currency", product.currency],
                ["Country", product.country],
                ["Listing Number", displayListingNo],
                ["Category", product.category],
              ].map(([label, value], index) => (
                <div
                  key={label}
                  className={`flex items-center justify-between gap-4 px-4 py-3 text-[13px] ${
                    index % 2 === 0 ? "bg-[#F5F7F9]" : "bg-white"
                  }`}
                >
                  <span className="text-[#667085]">{label}</span>
                  <span className="text-right font-medium text-[#101828]">{value}</span>
                </div>
              ))}
            </div>
          </div>
        </>
      )}
    </Drawer>
  );
}
