"use client";
import type { Session } from "next-auth";
import React, { ReactNode } from "react";

import { useSearchParams, useRouter } from 'next/navigation';
import { Pagination, Spin } from 'antd';

import Filter from "@/app/(profile)/profile/products/_components/Filter";
import ProductIntegration from "@/app/(profile)/profile/products/_components/ProductIntegration";
import ProductRow from "../Product/ProductRow";
import Card from "@/core/components/Card";
import { ProductViewModel } from "@/core/types/dto";
import getOptions from "@/core/utils/helpers/getOptions";

function groupProductsByProductId(products: any[]): any[] {
  const groupedProducts: { [key: string]: any } = {};
  const separateProducts: any[] = [];

  products.forEach((product) => {
    const productId = product.productId?.$oid;

    if (productId) {
      if (!groupedProducts[productId]) {
        // Clone the product and initialize variations array with itself
        groupedProducts[productId] = {
          ...product,
          variations: [product],
        };
      } else {
        // Add subsequent variations to the existing product's variations field
        groupedProducts[productId].variations!.push(product);
      }
    } else {
      // Products without productId are treated separately
      separateProducts.push(product);
    }
  });

  // Combine grouped products and separate products without productId
  console.log(separateProducts);
  console.log('-----------------------------------');
  console.log(Object.values(groupedProducts));
  return [...Object.values(groupedProducts), ...separateProducts];
}

interface ProductsClientInterfaceProps {
  session: Session | null;
}
/**
 * NOTE: The `antd` library should be _ELIMINATED_ from any project's component!
 *  It is going to a lot of browsers **errors** & **warnings**.
 * @return {ReactNode} – component
 * @constructor
 */
export default function ProductsClientInterface(props: Readonly<ProductsClientInterfaceProps>): ReactNode {
  const session = props.session;
  const [products, setProducts] = React.useState<any[]>([]);
  const [loading, setLoading] = React.useState<boolean>(false);
  const [selectedProducts, setSelectedProducts] = React.useState<any[]>([]);
  const [mode, setMode] = React.useState<string>("add");
  const [selectedProduct, setSelectedProduct] = React.useState<ProductViewModel | null>(null);
  const [isModalOpen, setIsModalOpen] = React.useState<boolean>(false);
  const [searchTerm, setSearchTerm] = React.useState<string>("");
  const [total, setTotal] = React.useState<number>(0);
  const searchParams = useSearchParams();
  const router = useRouter();
  const page = Number(searchParams.get('page')) || 1;
  const limit = Number(searchParams.get('limit')) || 10;
  const sortPrice = searchParams.get('sortPrice') || "asc";
  const sortDate = searchParams.get('sortDate') || "asc";

  const params = new URLSearchParams({ page: page.toString() });

  searchTerm !== "" ? params.set('limit', products.length.toString()) : params.set('limit', "10")
  sortPrice !== undefined && params.set('sortPrice', sortPrice);
  sortDate !== undefined && params.set('sortCreatedAt', sortDate);

  const handleChangePage = (newPage: number) => {
    const newParams = new URLSearchParams(searchParams.toString());
    newParams.set('page', newPage.toString());
    router.push(`${window.location.pathname}?${newParams.toString()}`);
  };

  const handleSelectedProduct = (product: ProductViewModel, isChecked: boolean) => {
    setSelectedProducts(prevState => {
      if (isChecked) {
        return [...prevState, product];
      } else {
        return prevState.filter(item => item._id !== product._id);
      }
    });
  };

  const handleAllSelectedProducts = (isChecked: boolean) => {
    if (isChecked) return setSelectedProducts(products);
    setSelectedProducts([]);
  };

  React.useEffect(() => {
    const loadProducts = async () => {
      try {
        setLoading(true);
        const shopId = props.session?.user.shopId;
        if (props.session?.user?.role !== 'shop_admin' && !shopId) {
          setLoading(false);
          return false;
        }
        const options = await getOptions("GET");
        const res = await fetch(
          `${process.env.NEXT_PUBLIC_BASE_API_URL}/shops/${shopId}/products?${params.toString()}&searchQuery=${searchTerm}`,
          options);
        const data = await res.json();

        if (data) {
          setProducts(data.data);
          setTotal(data.total);

          console.log(groupProductsByProductId(data.data));
        }
      } catch {
        console.error("Error fetched products");
      } finally {
        setLoading(false);
      }
    };

    session?.user.id && loadProducts();
  }, [page, limit, sortPrice, sortDate, session, searchTerm]);

  return (
    <Card height="auto">
      <div className="p-8">
        <Filter
          setProducts={setProducts}
          searchTerm={searchTerm}
          setSearchTerm={setSearchTerm}
          handleSelectedAllProducts={handleAllSelectedProducts}
          counts={products?.length || 0}
          total={total}
          selectedProducts={selectedProducts}
          setSelectedProducts={setSelectedProducts}
        />
        <p
          className={`
            mt-[34px] font-[500] text-[14px] text-[#00000099] 
            ${selectedProducts?.length !== 0 ? "" : "invisible"}
          `}
        >
          {`Selected products: ${selectedProducts?.length || 0}`}
        </p>
        <Spin tip="Loading data products..." spinning={loading}>
          <>
            {!loading && products.length === 0
              ? (<section className={`h-[652px] overflow-y-auto flex flex-col gap-[10px] mt-[10px] mb-[30px]`}>
                <h1 className="font-[600] text-[24px] leading-[32.4px] text-center my-auto">The list is empty</h1>
              </section>)
              :
              (<div className="overflow-x-auto">
                <table className="min-w-full">
                  <thead>
                    <tr>
                      <th className="w-1/4 px-4 py-2 font-normal">Product Name</th>
                      <th className="px-4 py-2 font-normal">Page Name</th>
                      <th className="px-4 py-2 font-normal">Left</th>
                      {/* <th className="px-4 py-2">Brand</th> */}
                      <th className="px-4 py-2 font-normal">Size</th>
                      <th className="px-4 py-2 font-normal">Edit</th>
                    </tr>
                  </thead>
                  <tbody>
                    {products && products?.map?.((product: any, index: number) => (
                      <React.Fragment key={product.id}>
                        <ProductRow
                          setIsModalOpen={setIsModalOpen}
                          isChecked={selectedProducts.some(p => p._id === product._id)}
                          onCheckboxChange={handleSelectedProduct}
                          productData={product}
                          setSelectedProduct={setSelectedProduct}
                          setMode={setMode}
                          index={index}
                        />
                      </React.Fragment>
                    ))}
                  </tbody>
                </table>
              </div>)
            }
          </>
        </Spin>
        <Pagination
          className='mb-[30px] pt-2'
          align="center"
          current={page}
          pageSize={limit}
          defaultCurrent={page}
          total={total}
          onChange={(page) => handleChangePage(page)}
        />
        <ProductIntegration
          setTotal={setTotal}
          setIsModalOpen={setIsModalOpen}
          isModalOpen={isModalOpen}
          setSelectProduct={setSelectedProduct}
          selectedProduct={selectedProduct}
          mode={mode}
          setMode={setMode}
          setProducts={setProducts}
        />
      </div>
    </Card>
  );
};