import { FC, useEffect, useState } from "react";
import { useFieldArray, useFormContext } from "react-hook-form";
import DropdownList from "../common/Dropdown";
import { InputField, Select } from "../forms/Inputs";
import { TSproductSchema } from "../forms/schema/product";
import ProductSerial from "./product-serial";

const ProductFiberFormBackup: FC = () => {
  const [selectedProduct, setSelectedProduct] = useState<
    TSproductSchema | undefined
  >(undefined);
  const {
    control,
    setValue,
    watch,
    formState: { errors = {} as any },
  } = useFormContext();
  const { fields } = useFieldArray({
    name: "product",
    control,
  });
  useEffect(() => {
    const { unsubscribe } = watch((value, { name, type }) => {
      if (
        name === "product.0.fiber_meter_start" ||
        name === "product.0.fiber_meter_end"
      ) {
        const meter_start = value["product"][0]["fiber_meter_start"];
        const meter_end = value["product"][0]["fiber_meter_end"];
        let quantity = meter_end - meter_start;
        if (quantity < 0) {
          quantity = 0;
        }
        setValue("product.0.quantity", quantity);
      }
    });
    return () => unsubscribe();
  }, [watch]);
  useEffect(() => {
    if (selectedProduct !== undefined) {
      setValue(`product.${0}.has_serial`, selectedProduct?.has_serial);
      setValue(`product.${0}.vat`, selectedProduct?.vat);
    }
  }, [selectedProduct]);
  return (
    <div className="p-5 pt-0  bg-white -mt-5 pb-10">
      <div className="grid grid-cols-2 md:grid-cols-12 mt-5">
        <div className="border col-span-2">
          <div className="text-center font-medium block text-sm p-1">
            Product
          </div>
        </div>
        <div className="border text-center font-medium col-span-1 text-sm p-1">
          Brand
        </div>
        <div className="border text-center font-medium p-1 text-sm">Status</div>
        <div className="border text-center font-medium p-1 text-sm">
          Fiber ID
        </div>
        <div className="border text-center font-medium p-1 text-sm">
          Meter Start
        </div>
        <div className="border text-center font-medium p-1 text-sm">
          Meter End
        </div>
        <div className="border text-center font-medium p-1 text-sm">
          Quantity
        </div>
        <div className="border text-center font-medium p-1 text-sm">
          Unit Cost
        </div>
        <div className="border text-center font-medium p-1 text-sm">
          Sale Price
        </div>
        <div className="border text-center font-medium text-sm p-1">VAT(%)</div>
        <div className="border co-span-2 text-center font-medium text-sm p-1">
          Total
        </div>
      </div>
      {fields.map((field: any, index) => (
        <div className="border" key={field.id}>
          <div className="grid grid-cols-2 md:grid-cols-12">
            <div className=" border col-span-2">
              <div className="relative">
                <div className="py-2 h-full text-md absolute -left-4 font-bold z-5">
                  <span className="mt-2 block">{index + 1}</span>
                </div>
                <div className="py-2 px-1 overflow-visible w-full">
                  <DropdownList
                    idName={`product.${index}.product_id`}
                    name="product"
                    getLabel={(product) => product?.name}
                    isMulti={false}
                    isClearable={false}
                    height={20}
                    setOriginalValue={(product) => setSelectedProduct(product)}
                  />
                  {errors?.["product"]?.[index] && (
                    <p className="text-red-500">Product is required</p>
                  )}
                </div>
              </div>
            </div>
            <div className="px-1 border col-span-1">
              <InputField
                name={`product.${index}.brand`}
                placeholder="brand"
                size="sm"
              />
            </div>
            <div className="px-1 pt-2 border">
              <Select
                size="sm"
                name={`product.${index}.status`}
                defaultValue={"new"}
                options={[
                  { value: "new", label: "New" },
                  { value: "old", label: "Old" },
                  { value: "replace", label: "Replace" },
                ]}
              />
            </div>
            <div className="border px-1">
              <InputField
                name={`product.${index}.fiberID`}
                placeholder="Fiber ID"
                size="sm"
              />
            </div>
            <div className="border px-1">
              <InputField
                name={`product.${index}.fiber_meter_start`}
                placeholder="Fiber meter start"
                inputType="number"
                size="sm"
              />
            </div>
            <div className="border px-1">
              <InputField
                name={`product.${index}.fiber_meter_end`}
                placeholder="Fiber meter end"
                inputType="number"
                size="sm"
              />
            </div>
            <div className="border px-1">
              <InputField
                name={`product.${index}.quantity`}
                placeholder="Quantity"
                inputType="number"
                size="sm"
                readonly={true}
              />
            </div>
            <div className="border px-1">
              <InputField
                name={`product.${index}.unit_price`}
                placeholder="Unit cost"
                inputType="number"
                size="sm"
              />
            </div>
            <div className="border px-1">
              <InputField
                name={`product.${index}.unit_sell_price`}
                placeholder="unit sell price"
                size="sm"
              />
            </div>
            <div className="border px-1">
              <InputField
                name={`product.${index}.vat`}
                placeholder="Vat"
                size="sm"
              />
            </div>
            <div className="border flex relative">
              <div className="col-span-8 px-1">
                <InputField
                  readonly={true}
                  name={`product.${index}.total_price`}
                  placeholder="Total"
                  inputType="number"
                  size="sm"
                />
              </div>
            </div>
          </div>
          <div className="p-2 pt-0 grid grid-cols-2 gap-2 md:grid-cols-8">
            <ProductSerial {...{ control, index, field }} />
          </div>
        </div>
      ))}
    </div>
  );
};

export default ProductFiberFormBackup;
