import productService from "@/lib/services/product";
import FileUpload from "./components/file-upload";
import ProductActions from "./components/product-actions";
import { notFound } from "next/navigation";
import Breadcrumbs from "../common/breadcrumbs";
import { ProductOptionAttributeItem } from "@/lib/types/models";
import orderService from "@/lib/services/order";

interface NestedParentInfo {
  name?: string;
  slug?: string;
  parentId?: {
    name?: string;
    slug?: string;
  };
}

export default async function Page({
  searchParams
}: {
  searchParams: Record<string, string>;
}) {
  const queryObject = searchParams;

  if (!queryObject?.productId) {
    notFound();
  }
  const productResponse = await productService.fetchProductOptionById(
    queryObject?.productId
  );
  const detailArray: ProductOptionAttributeItem[] = productResponse?.data?.options || [];
  const result: Record<string, string> = detailArray?.length
    ? detailArray.reduce(
      (acc: Record<string, string>, item: ProductOptionAttributeItem) => {
        const key = item?.variantCode;
        const value = item?.attributeItemName;
        if (value) {
          acc[key] = value;
        }
        return acc;
      },
      {} as Record<string, string>
    )
    : {};

  const parentInfo = productResponse?.data?.parentId as unknown as NestedParentInfo | undefined;


  return (
    <div className="min-h-screen py-2 sm:py-4 mb-5">
      <div className="main-container mobile-container">
        <Breadcrumbs
          item={[
            {
              link: `/${parentInfo?.parentId?.slug || ''}`,
              name: parentInfo?.parentId?.name || 'Category'
            },
            {
              link: `/${parentInfo?.parentId?.slug || ''}/${parentInfo?.slug || ''}`,
              name: parentInfo?.name || 'Product'
            },
            { name: "File Upload" }
          ]}
        />
      </div>
      <div className="main-container mobile-container ">
        <div className="py-[5px] relative">
          <h2 className="text-[20px] lg:text-[24px] leading-[25.2px] lg:leading-[42.84px] text-neutral-black-87 font-semibold mb-1">
            File Upload
          </h2>
          <div className="mb-3 text-gray-600 text-lg md:text-base">
            {result?.Size || ''} {parentInfo?.name || productResponse?.data?.name || ''}
          </div>
        </div>

        <div className="flex flex-col md:flex-row gap-4 sm:gap-6 md:gap-8 items-start justify-center md:justify-start">
          <FileUpload produtData={result} queryObject={searchParams} />
        </div>
        <ProductActions />
      </div>
    </div>
  );
}
