"use client";

import AuthPageLayout, {
  AuthFormFooter,
  AuthPageContent,
} from "@/components/auth/AuthPageLayout";
import AuthNextButton from "@/components/auth/AuthNextButton";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import ProductCategoryPicker from "@/components/shops/ProductCategoryPicker";
import useAxios from "@/hooks/useAxios";
import { useProductWizardId } from "@/hooks/useProductWizardId";
import { IShopCategory } from "@/types/types";
import { useParams, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

function ProductCategoryPage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const params = useParams<{ shopId: string }>();
  const shopId = params.shopId;
  const { request, loading } = useAxios();
  const listingId = useProductWizardId(shopId);

  const [categoryList, setCategoryList] = useState<IShopCategory[] | null>(null);
  const [category, setCategory] = useState("");
  const [subCategory, setSubCategory] = useState("");
  const [subSubCategory, setSubSubCategory] = useState("");

  useEffect(() => {
    request<{ categories: IShopCategory[] }>("GET", "/shop-categories")
      .then((res) => setCategoryList(res?.categories || []))
      .catch(() => setCategoryList([]));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (!listingId) return;
    request<{
      listing: {
        category?: string | null;
        sub_category?: string | null;
        sub_sub_category?: string | null;
      };
    }>("GET", `/shop-products/${listingId}`).then((res) => {
      if (!res?.listing) return;
      if (res.listing.category) setCategory(res.listing.category);
      if (res.listing.sub_category) setSubCategory(res.listing.sub_category);
      if (res.listing.sub_sub_category) setSubSubCategory(res.listing.sub_sub_category);
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [listingId]);

  const handleCategorySelect = (value: string) => {
    setCategory(value);
    setSubCategory("");
    setSubSubCategory("");
  };

  const handleSubCategorySelect = (value: string) => {
    setSubCategory(value);
    setSubSubCategory("");
  };

  const handleSubmit = async () => {
    if (!listingId) return;

    if (!category) {
      toast.error(t("shops.productCategoryRequired"));
      return;
    }

    const selectedCategory = categoryList?.find((item) => item.category === category);
    const hasSubCategories = (selectedCategory?.sub_categories.length ?? 0) > 0;
    if (hasSubCategories && !subCategory) {
      toast.error(t("shops.productCategoryRequired"));
      return;
    }

    const selectedSubCategory = selectedCategory?.sub_categories.find(
      (item) => item.name === subCategory
    );
    const hasSubSubCategories = (selectedSubCategory?.sub_sub_categories?.length ?? 0) > 0;
    if (hasSubSubCategories && !subSubCategory) {
      toast.error(t("shops.productCategoryRequired"));
      return;
    }

    try {
      await request("PATCH", `/shop-products/${listingId}`, {
        category,
        sub_category: subCategory,
        sub_sub_category: subSubCategory,
      });
      router.push(`/shops/${shopId}/products/new/images`);
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { message?: string } } })?.response
          ?.data?.message || t("shops.unknownError");
      toast.error(message);
    }
  };

  if (!listingId) return null;

  return (
    <LocalePageShell>
      <AuthPageLayout>
        <AuthPageContent>
          <span className="text-xl font-bold">{t("shops.productCategoryTitle")}</span>
          <ProductCategoryPicker
            categoryList={categoryList}
            category={category}
            subCategory={subCategory}
            subSubCategory={subSubCategory}
            onCategorySelect={handleCategorySelect}
            onSubCategorySelect={handleSubCategorySelect}
            onSubSubCategorySelect={setSubSubCategory}
          />
        </AuthPageContent>
        <AuthFormFooter>
          <AuthNextButton
            type="button"
            loading={loading}
            disabled={loading}
            onClick={handleSubmit}
          >
            {t("shops.saveAndContinue")}
          </AuthNextButton>
        </AuthFormFooter>
      </AuthPageLayout>
    </LocalePageShell>
  );
}

export default ProductCategoryPage;
