import { FC, useEffect, useState } from "react";
import { useFieldArray, useFormContext } from "react-hook-form";
import { HiMinus, HiPlus } from "react-icons/hi";
import DropdownList from "../common/Dropdown";
import { InputField } from "../forms/Inputs";
import { TSproductOutSchema } from "../forms/schema/product-out";
import ProductOutSerial from "./product-out-serial";
import { twMerge } from "tailwind-merge";

type props = {
  defaultProduct: TSproductOutSchema;
};
const ProductOutRowForm: FC<props> = ({ defaultProduct }) => {
  const [selectedProduct, setSelectedProduct] = useState<TSproductOutSchema[]>(
    []
  );

  const {
    control,
    setValue,
    getValues,
    watch,
    formState: { errors = {} as any },
  } = useFormContext();

  const { fields, remove, insert } = useFieldArray({
    name: "product",
    control,
  });

  useEffect(() => {
    if (selectedProduct?.length > 0) {
      selectedProduct?.map((product: any, index) => {
        setValue(`product.${index}.has_serial`, product?.has_serial);
        setValue(`product.${index}.vat`, product?.vat);
      });
    }
  }, [selectedProduct]);

  const setProduct = (index: number, product: any) => {
    const newProduct = [...selectedProduct];
    newProduct[index] = product;
    setValue(
      `product.${index}.product_category_id`,
      product.product_category_id
    );
    setSelectedProduct(newProduct);
  };
  useEffect(() => {
    const { unsubscribe } = watch((value, items) => {
      if (
        (items.name?.startsWith("product") &&
          (items.name?.endsWith("unit_price") ||
            items.name?.endsWith("quantity") ||
            items.name?.endsWith("vat"))) ||
        items.name?.endsWith("discount")
      ) {
        const index = parseInt(items.name.split(".")[1]);
        const price = value.product?.at(index)?.unit_price;
        const quantity = value.product?.at(index)?.quantity;
        const vat = value.product?.at(index)?.vat ?? 0;
        const discount = value.product?.at(index)?.discount ?? 0;
        if (price && quantity) {
          let total = price * quantity;
          if (vat > 0) {
            total = total + (total / 100) * vat;
          }
          if (discount > 0) {
            total = total - discount;
          }
          setValue(`product.${index}.total_price`, total);
        }
      }
    });
    return () => unsubscribe();
  }, [watch]);
  return (
    <div className="py-5 mt-2 pt-0 pr-8 bg-white -mt-5 pb-10">
      <div className="grid grid-cols-2 md:grid-cols-9 mt-5">
        <div className="border-t border-l col-span-2">
          <div className="text-center font-medium block text-sm p-1">
            Product
          </div>
        </div>
        <div className="border-t border-l col-span-2 text-center font-medium text-sm p-1">
          Product IN
        </div>
        <div className="border-t border-l text-center font-medium p-1 text-sm">
          Quantity
        </div>
        <div className="border-t border-l text-center font-medium p-1 text-sm">
          Unit Price
        </div>
        <div className="border-t border-l text-center font-medium text-sm p-1">VAT(%)</div>
        <div className="border-t border-l text-center font-medium text-sm p-1">
          Discount
        </div>
        <div className="border-t border-l border-r co-span-2 text-center font-medium text-sm p-1">
          Total
        </div>
      </div>
      {fields.map((field: any, index) => (
        <div key={field.id}>
          <div className="" key={field.id}>
            <div className="grid grid-cols-2 md:grid-cols-9">
              <div className={twMerge("border-b border-l col-span-2", index === 0 && "border-t")}>
                <div className="relative my-2">
                  <div className=" h-full text-md absolute -left-4 font-bold z-5">
                    <span className="mt-2 block">{index + 1}</span>
                  </div>
                  <div className=" px-1 overflow-visible w-full">
                    <DropdownList
                      idName={`product.${index}.product_id`}
                      name="product"
                      filter="in"
                      getLabel={(product) => product?.name}
                      isMulti={false}
                      height={20}
                      setOriginalValue={(product) => setProduct(index, product)}
                    />
                    {errors?.["product"]?.[index]?.["product_id"] && (
                      <p className="text-red-500">Product is required</p>
                    )}
                  </div>
                </div>
              </div>
              <div className={twMerge(" px-1 border-b border-l col-span-2", index === 0 && "border-t")}>
                <div className="my-2">
                  <DropdownList
                    idName={`product.${index}.productin_id`}
                    name={`product_in`}
                    getLabel={(productIn) => productIn?.name}
                    isMulti={false}
                    height={20}
                    depend_on={getValues(`product.${index}.product_id`)}
                    isEnabled={false}
                    placeholder="Product IN"
                    setOriginalValue={(productIn) => {
                      console.log(productIn);
                      setValue(
                        `product.${index}.unit_price`,
                        productIn?.unit_sell_price
                      );
                    }}
                  />
                </div>
              </div>
              <div className={twMerge("border-b border-l px-1", index === 0 && "border-t")}>
                <InputField
                  name={`product.${index}.quantity`}
                  placeholder="Quantity"
                  inputType="number"
                  size="sm"
                />
              </div>
              <div className={twMerge("border-b border-l px-1", index === 0 && "border-t")}>
                <InputField
                  name={`product.${index}.unit_price`}
                  placeholder="Unit cost"
                  inputType="number"
                  size="sm"
                />
              </div>
              <div className={twMerge("border-b border-l px-1", index === 0 && "border-t")}>
                <InputField
                  name={`product.${index}.vat`}
                  placeholder="Vat"
                  size="sm"
                />
              </div>
              <div className={twMerge("border-b border-l px-1", index === 0 && "border-t")}>
                <InputField
                  name={`product.${index}.discount`}
                  placeholder="discount"
                  size="sm"
                />
              </div>
              <div className={twMerge("border-b border-l border-r flex relative", index === 0 && "border-t")}>
                <div className="col-span-8 px-1">
                  <InputField
                    readonly={true}
                    name={`product.${index}.total_price`}
                    placeholder="Total"
                    inputType="number"
                    size="sm"
                  />
                </div>
                <div className="absolute -right-6 -top-0.5">
                  {index > 0 ? (
                    <div
                      className="border h-[31px] cursor-pointer bg-red-600"
                      onClick={() => remove(index)}
                    >
                      <HiMinus className="text-xl mt-1 text-white" />
                    </div>
                  ) : (
                    <div className="border h-[31px] bg-red-300">
                      <HiMinus className="text-xl text-gray-300 mt-1" />
                    </div>
                  )}
                  <div
                    className="border h-[30px] cursor-pointer bg-green-600"
                    onClick={() => insert(index + 1, defaultProduct)}
                  >
                    <HiPlus className="text-xl mt-1 text-white" />
                  </div>
                </div>
              </div>
            </div>
            {/* {getValues(`product.${index}.product_category_id`) === 2 && (
              <div>
                <ProductFiberForm index={index} />
              </div>
            )} */}
            <div className=" pt-0">
              {getValues(`product.${index}.has_serial`) === 1 && (
                <ProductOutSerial {...{ control, index, field }} />
              )}
            </div>
          </div>
        </div>
      ))}
    </div>
  );
};

export default ProductOutRowForm;
