"use client";

import React, {useCallback, useEffect, useState} from "react";
import { Spin } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import AppList from "@/components/ui/list";
import ProductCard from "@/components/manage-content/item-card-content";
import { useSearchParams } from "next/navigation";
import { usePathname } from "@/i18n/routing";
import { ProductQueryParams } from "@/types/product";
import { SortDirection, SortField, Status } from "@/types/common";
import useSWR from "swr";
import {onGetProductPaging} from "@/services/apis/product";
import {DeliveryOptions, SettingAppCustomer} from "@/types/appSetting";
import {useTranslations} from "use-intl";
import StoreHelper from "@/lib/storeHelper";
import { debounce } from "next/dist/server/utils";
import { useMounted } from "@/hooks/useMounted";
import AppInput from "@/components/ui/input";
import AppSelect from "@/components/ui/select";

interface Product {
    id: number;
    name: string;
    description: string;
    image: string;
    status: Status;
    contentDownloadId: string
    beContentId: string;
    beGroupContentId: string;
    expireDate: string | null;
}

interface ProductClientProps {
    initialData: {
        content: Product[];
        pageNumber: number;
        numberOfElements: number;
        totalElements: number;
        totalPages: number;
        pageSize: number;
    };
    initialQuery: ProductQueryParams;
    customerId: string;
    customerToken: string;
    isSettingAppCustomer: SettingAppCustomer;
}

const ProductClient: React.FC<ProductClientProps> = ({
                                                         initialData,
                                                         initialQuery,
                                                         customerId,
                                                         customerToken,
                                                         isSettingAppCustomer
                                                     }) => {

    const pathname = usePathname();
    const searchParams = useSearchParams();
    const t = useTranslations("ManageContentPage");
    const mounted = useMounted();
    const [searchTerm, setSearchTerm] = useState<string>(
        ""
    );
    const [isLoading, setIsLoading] = useState(false);
    const [contentQuery, setContentQuery] = useState<ProductQueryParams>(
        initialQuery
    );

  const swrKey = `${pathname}?${searchParams.toString()}`;
  const { data, error, mutate } = useSWR(swrKey, null, {
    fallbackData: { status: "success", data: initialData, errorMsg: "" },
    revalidateOnFocus: false,
    revalidateIfStale: false,
  });
  const products = data?.data?.content || [];

  const paging = {
    pageNumber: data?.data?.pageNumber || 1,
    numberOfElements: data?.data?.numberOfElements || 0,
    totalElements: data?.data?.totalElements || 0,
    totalPages: data?.data?.totalPages || 0,
    pageSize: data?.data?.pageSize || 10,
  };

  const handleSearch = (e) => {
    const value = e.target.value.trim();
    setSearchTerm(value);

    setContentQuery(prevState => ({
      ...prevState,
      searchKeyName: value,
      pageNumber: 1,
    }))
  };
  const handleFetchContent = useCallback( debounce(async (query) => {
    setIsLoading(true);
    try {
      await mutate(
        () =>
          onGetProductPaging({
            ...contentQuery,
            ...query,
          }),
        {
          revalidate: true,
          populateCache: true,
        }
      );
    } catch (error: any) {
      console.error("Error fetching content", error);
      return;
    } finally {
      setIsLoading(false);
    }
  }, 400), [contentQuery, mutate]);

    const renderProduct = (product: Product) => (
        <ProductCard
            key={product.id}
            id={product.id}
            customerId={customerId}
            title={product.name}
            subtitle={product.description}
            imageUrl={product.image}
            contentDownloadId={product.contentDownloadId}
            contentId={product.beContentId}
            contentGroupId={product.beGroupContentId}
            isSettingAppCustomer={isSettingAppCustomer}
            expireDate={product?.expireDate}
        />
    );
const handleSortDirectionChange = (value: SortDirection) => {
    setContentQuery(prevState => ({
     ...prevState,
      sortDirection: value
    }))
  };

  useEffect(() => {
    StoreHelper.setCookie("customerToken", customerToken, {
      maxAge: 30 * 24 * 60 * 60,
    });
    StoreHelper.removeCookie("token");
  }, [customerToken]);

  useEffect(() => {
    handleFetchContent(contentQuery);
  }, [contentQuery]);

  return (
    <div className="min-h-screen bg-gray-50 py-6 px-4 md:px-8">
      <div className="max-w-7xl mx-auto">
        <div className="mb-8 flex flex-col md:flex-row md:items-center md:justify-between">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">{t("content")}</h1>
          </div>

          <div className="mt-4 md:mt-0 flex flex-col md:flex-row gap-4 w-full md:w-auto">
            <AppInput
              placeholder={t("search_content")}
              prefix={<SearchOutlined />}
              value={searchTerm}
              onChange={handleSearch}
              allowClear
            />
            <div className="w-[300px]">
              <AppSelect
                defaultValue={SortDirection.DESC}
                options={[
                  { label: t("descending"), value: SortDirection.DESC },
                  { label: t("ascending"), value: SortDirection.ASC },
                ]}
                placeholder={t("select_sort_direction")}
                prefix={<SearchOutlined />}
                onChange={handleSortDirectionChange}
                className="w-full"
              />
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl shadow-sm overflow-hidden p-4">
          <div className="p-4">
            {isLoading ? (
              <div className="flex justify-center items-center py-12">
                <Spin size="large" />
              </div>
            ) : error ? (
              <div className="text-center text-red-500 py-12">
                {t("errorLoadingData")}
              </div>
            ) : (
              <>
                {products.length === 0 ? (
                  <div className="text-center py-12 text-gray-500">
                    {t("noProductsFound")}
                  </div>
                ) : (
                  <>
                    {mounted && (
                      <AppList
                        data={products}
                        loading={isLoading}
                        renderItem={renderProduct}
                        hasMore={false}
                        infiniteScroll={false}
                        className="space-y-6"
                        pagination={{
                          current: paging.pageNumber,
                          pageSize: paging.pageSize,
                          total: paging.totalElements,
                          onChange: (page) => {
                            setContentQuery(prevState => ({
                              ...prevState,
                              pageNumber: page,
                              pageSize: 10,
                            }));
                          },
                          showSizeChanger: false,
                          showTotal: (total, range) =>
                            `${range[0]}-${range[1]} ${t("of")} ${total} ${t(
                              "items"
                            )}`,
                        }}
                      />
                    )}
                  </>
                )}
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};


export default ProductClient;
