import { FC, useEffect } from "react";
import { useFormContext } from "react-hook-form";
import { InputField } from "../forms/Inputs";

type props = {
  index: number;
};

const ProductFiberForm: FC<props> = ({ index }) => {
  const { setValue, watch } = useFormContext();
  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]);
  return (
    <div className="grid gap-0 grid-cols-3">
      <div className="border px-1 pb-2">
        <InputField
          name={`product.${index}.fiberID`}
          placeholder="Fiber ID: EX:ACED1B"
          size="sm"
        />
      </div>
      <div className="border px-1 pb-2">
        <InputField
          name={`product.${index}.fiber_meter_start`}
          placeholder="Fiber meter start: EX:120"
          inputType="number"
          size="sm"
        />
      </div>
      <div className="border px-1 pb-2">
        <InputField
          name={`product.${index}.fiber_meter_end`}
          placeholder="Fiber meter end: EX:150"
          inputType="number"
          size="sm"
        />
      </div>
    </div>
  );
};

export default ProductFiberForm;
