import React from "react";
import { Dispatch, SetStateAction } from "react";
import { Product } from "@/modules/products/product";
import Select from "react-select";
import { selectStyle } from "@/lib/utils";
import MainButton from "@/components/ui/MainButton";
import TranslateClient from "@/components/ui/localization/TranslateClient";
import { useCartStore } from "@/app/store/cartStore";
import { toast } from "@/components/ui/use-toast";
import useCurrentLanguage from "@/hooks/useCurrentLanguage";

type SelectColorAndCountProps = {
  product: Product;
  selectedColorId: number | null;
  selectedCountId: number | null;
  setSelectedColorId: Dispatch<SetStateAction<number | null>>;
  setSelectedCountId: Dispatch<SetStateAction<number | null>>;
  setOpen: Dispatch<SetStateAction<boolean>>;
};

function SelectColorAndCount({
  product,
  setSelectedColorId,
  selectedColorId,
  setSelectedCountId,
  selectedCountId,
  setOpen,
}: SelectColorAndCountProps) {
  const options = Array.from({ length: product?.count }, (_, i) => ({
    label: i + 1,
    value: i + 1,
  }));
  const {
    addToCart,
    getProducts,
    getPriceSummary,
    postingDataState,
    gettingDataState,
    gettingSummaryState,
  } = useCartStore();

  const { locale, lang } = useCurrentLanguage();
  const loading = postingDataState || gettingDataState || gettingSummaryState;

  const addToCartHandler = async () => {
    await addToCart({
      product_id: product?.id,
      color_id: selectedColorId || product?.colors?.[0]?.id,
      count: selectedCountId || 1,
    })
      .then(async () => {
        await getPriceSummary();
        await getProducts();

        toast({
          title: "success",
          description: locale?.["add_to_cart_successfully"],
          className: "bg-green-700 text-white rounded-xl",
        });
      })
      .catch((err) => {
        toast({
          title: "Error",
          description: locale?.["oops_something_went_wrong"],
          className: "bg-red-700 text-white rounded-xl",
        });
      })
      .finally(() => {
        setOpen(false);
      });
  };
//   console.log("options",options)
// console.log("product",product?.count)
  return (
    <>
      <h2 className="mt-6 mb-3 capitalize text-xl font-semibold">
        {product.name[lang]}
      </h2>
      <div className="space-y-8 mb-6">
        <div className="space-y-3">
          <p className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
            <TranslateClient text="select_count" />
          </p>
          <Select
            className="basic-single hide_scroll w-full"
            classNamePrefix="select"
            placeholder={<TranslateClient text="Select" />}
            isSearchable = {false}
            options={options}
            onChange={(option) => {
              // setValue(option as never)
              // @ts-ignore
              setSelectedCountId(option!.value);
            }}
            styles={selectStyle}
          />
        </div>
        <div className="space-y-3">
          <p className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
            <TranslateClient text="select_color" />
          </p>
          <div className="flex flex-wrap gap-2">
            {product?.colors?.map((item) => (
              <button
                key={item?.id}
                onClick={() => setSelectedColorId(item?.id)}
                className={`border mx-1 rounded-full flex items-center justify-center p-2 hover:scale-110 duration-200 w-10 h-10 ${
                  item?.id === selectedColorId && "border-red-400"
                }`}
              >
                <span
                  className="w-6 h-6 rounded-full inline-block"
                  style={{ background: item?.color_degree }}
                />
              </button>
            ))}
          </div>
        </div>
      </div>
      <MainButton
        onClick={addToCartHandler}
        intent={loading ? "loading" : "primary"}
        disabled={loading || !selectedCountId || !selectedColorId}
      >
        <TranslateClient text={"add_to_cart"} />
      </MainButton>
    </>
  );
}

export default SelectColorAndCount;
