import { React, useState } from "react";
import { DataTable } from "primereact/datatable";
import { Column } from "primereact/column";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Button } from "primereact/button";
import { InputText } from "primereact/inputtext";
import { Dialog } from "primereact/dialog";

import { useRef } from "react";
import { useForm, Controller, useFieldArray } from "react-hook-form";
import axios from "axios";
import { Toast } from "primereact/toast";
import { useEffect } from "react";
import { FilterMatchMode, FilterOperator } from "primereact/api";
import { ConfirmPopup, confirmPopup } from "primereact/confirmpopup";

import { authUser } from "@/Components/AuthProvider";
import { useContext } from "react";

import { AutoComplete } from "primereact/autocomplete";
import { Calendar } from "primereact/calendar";
import { Dropdown } from "primereact/dropdown";
import DueReceiptPrint from "./DueReceiptPrint";
import SalesPersonSearch from "@/Components/SalesPersonSearch";
import WarehouseDropdown from "@/Components/WarehouseDropdown";
import { clientItemTemplate } from "@/Components/customerSearchClientTemplate";

function DeuCollection({ auth, bank, mobileBank }) {
  const { permission } = useContext(authUser);
  const [status, setStatus] = useState("create");
  const [visible, setVisible] = useState(false);
  const [id, setId] = useState();
  const formSubmit = useRef(null);
  const toast = useRef(null);
  const [customer, setCustomer] = useState([]);
  const [paymentStatus, setPaymentStatus] = useState("cash");
  const [payment, setPayment] = useState([]);
  const [due, setDue] = useState([]);
  const [salesPersonDisplayText, setSalesPersonDisplayText] = useState("");

  const [filters, setFilters] = useState({
    global: { value: null, matchMode: FilterMatchMode.CONTAINS },
    name: { value: null, matchMode: FilterMatchMode.STARTS_WITH },
    type: { value: null, matchMode: FilterMatchMode.STARTS_WITH },
    payment_type: { value: null },
  });
  const [filters2, setFilters2] = useState({
    global: { value: null, matchMode: FilterMatchMode.CONTAINS },
    "customer.name": {
      value: null,
      matchMode: FilterMatchMode.STARTS_WITH,
    },
    "customer.code": {
      value: null,
      matchMode: FilterMatchMode.STARTS_WITH,
    },
    order_no: { value: null, matchMode: FilterMatchMode.STARTS_WITH },
  });
  const [globalFilterValue, setGlobalFilterValue] = useState("");
  const [globalFilterValue2, setGlobalFilterValue2] = useState("");

  const [search, setSearchValue] = useState({
    company: "",
    customer: "",
  });
  const [customerFieldResetKey, setCustomerFieldResetKey] = useState(0);
  const [paymentType, setPaymentType] = useState({
    bank: "",
    mobile_bank: "",
    cash: "cash",
  });
  useEffect(() => {
    axios.get(route("due.collection.view")).then((res) => {
      setPayment(res.data);
    });

    if (!permission.includes("customer_collection_superAdmin_access")) {
      setValue("warehouse_id", auth.user.shop_id);
    }
  }, []);

  const {
    register,
    control,
    handleSubmit,
    formState: { errors },
    setValue,
    watch,
    reset,
    clearErrors,
    setError,
  } = useForm({
    customer_id: "",
    date: "",
    list: [
      {
        supplier_id: "",
        supplier_info: "",
        deu_balance: "",
        payment: "",
        payment_id: "",
        payment_type: "",
        index: "",
      },
    ],
  });

  const { fields, append, prepend, remove } = useFieldArray({
    control,
    name: "list",
  });

  const getFormErrorMessageMultiple = (name, index = null) => {
    return errors["list"] &&
      errors["list"][index] &&
      errors["list"][index][name] ? (
      <small className="p-error ">
        {errors["list"][index][name]["message"]}
      </small>
    ) : (
      ""
    );
  };

  const getFormErrorMessageSingel = (name) => {
    return errors[name] ? (
      <small className="p-error ">{errors[name]["message"]}</small>
    ) : (
      ""
    );
  };

  {
    /* Table Data Search */
  }
  const onGlobalFilterChange = (e) => {
    const value = e.target.value;
    let _filters = { ...filters };

    _filters["global"].value = value;

    setFilters(_filters);
    setGlobalFilterValue(value);
  };
  const onGlobalFilterChange2 = (e) => {
    const value = e.target.value;
    let _filters = { ...filters2 };

    _filters["global"].value = value;

    setFilters2(_filters);
    setGlobalFilterValue2(value);
  };
  {
    /*Table Header*/
  }
  const TableHeader = () => {
    return (
      <div
        className={`w-100% flex ${true ? "justify-between" : "justify-end"
          } `}
      >
        {permission.includes("customer_collection_create") && (
          <Button
            type="button"
            icon={<span className="pi pi-plus text-sm pr-1" />}
            label="Add"
            onClick={() => {
              setVisible(true);
              setStatus("create");
              setSearchValue({
                company: "",
                customer: "",
              });
              setSalesPersonDisplayText("");
              setPaymentStatus("cash");
              setPaymentType({
                bank: "",
                mobile_bank: "",
                cash: "cash",
              });
              setValue(`list.${0}.payment_id`, "cash");

              reset({
                warehouse_id: watch("warehouse_id"),
                list: [],
              });
            }}
            className="p-button-success h-[41px]  text-[14px] "
          />
        )}

        <span className="p-input-icon-left h-10 ">
          <i className="pi pi-search" />
          <InputText
            className="h-[41px] w-48"
            value={globalFilterValue2}
            onChange={onGlobalFilterChange2}
            placeholder="Search"
          />
        </span>
      </div>
    );
  };

  const CompanyTableHeader = () => {
    return (
      <div className={`w-100% flex justify-end`}>
        <span className="p-input-icon-left h-10 ">
          <i className="pi pi-search" />
          <InputText
            className="h-[41px] w-48"
            value={globalFilterValue}
            onChange={onGlobalFilterChange}
            placeholder="Search"
          />
        </span>
      </div>
    );
  };

  {
    /*Dilog Model Footer*/
  }
  const footerContent = (
    <div className="flex justify-end">
      <Button
        label="Cancel"
        icon="pi pi-times"
        onClick={() => {
          setVisible(false);
          setSalesPersonDisplayText("");
          reset({
            warehouse_id: watch("warehouse_id"),
            list: [],
          });
        }}
        className="p-button-text w-13 text-sm"
      />
      <Button
        label="Save"
        type="submit"
        onClick={() => {
          formSubmit.current.dispatchEvent(
            new Event("submit", { bubbles: true })
          );
        }}
        icon="pi pi-check"
        className="p-button-text w-13 text-sm"
      />
    </div>
  );

  // Store Data
  const StoreData = (data) => {
    if (data.list.length != 0) {
      axios
        .post(route("customer-store-due-collection"), data)
        .then((response) => {
          toast.current.show({
            severity: "info",
            summary: "Confirmed",
            detail: response.data.success,
            life: 3000,
          });

          setVisible(false);

          setPayment(response.data.payment);
          setSalesPersonDisplayText("");
          reset({
            warehouse_id: watch("warehouse_id"),
            list: [],
          });
        })
        .catch((error) => {
          let errors = error.response.data.errors;
          Object.keys(errors).forEach((field) => {
            setError(field, {
              type: "manual",
              message: errors[field][0],
            });
          });
        });
    } else {
      toast.current.show({
        severity: "warn",
        summary: "Rejected",
        detail: "Must need a Product",
        life: 3000,
      });
    }
  };

  const editData = (data) => {
    reset({
      list: [],
    });
    let inputValue = "";

    setSearchValue((old) => {
      return {
        ...old,
        // `clients.name` can be NULL in DB, so build a safe display string
        // from the first available field.
        customer: `${
          data?.customer?.name ||
          data?.customer?.number ||
          data?.customer?.code ||
          ""
        }${
          data?.customer?.code
            ? ` (${data.customer.code})`
            : ""
        }`,
      };
    });

    setTimeout(() => {
      setValue("customer_id", data.customer.id);
      setValue("sales_person_id", data.sales_person_id);
      setValue("date", new Date(data.date));
      setValue("order_no", data.order_no);
      setValue("note", data.note);
      setValue("payment_type", data.payment_type);
      setValue("warehouse_id", Number(data.warehouse_id));

      // Set sales person display text if available
      if (data.sales_person) {
        setSalesPersonDisplayText(
          `${data.sales_person.name} (${data.sales_person.code})`
        );
      } else {
        setSalesPersonDisplayText("");
      }

      setPaymentStatus(data.payment_type);
      let isCash = false;
      if (data.payment_type == "Bank") {
        setPaymentType((old) => {
          return {
            ...old,
            bank: data.payment_id,
          };
        });
      } else if (data.payment_type == "Mobile Bank") {
        setPaymentType((old) => {
          return {
            ...old,
            mobile_bank: data.payment_id,
          };
        });
      } else {
        isCash = true;
        setPaymentType((old) => {
          return {
            ...old,
            cash: "cash",
          };
        });
      }

      setId(data.id);
      let total =
        Number(data.total_sales) +
        Number(data.opening) -
        (Number(data.prev_payment) + Number(data.payment));
      append({
        deu_balance: total,
        payment: Number(data.payment),
        payment_id: isCash ? "cash" : Number(data.payment_id),
        payment_type: "cash",
        total_sales: total,
        prev_payment: Number(data.payment),
        index: 0,
      });
    }, 50);
  };

  // Data Update
  const UpdateData = (data) => {
    if (data.list.length != 0) {
      axios
        .post(route("customer-store-due-collection-edit", id), data)
        .then((response) => {
          toast.current.show({
            severity: "info",
            summary: "Confirmed",
            detail: response.data.success,
            life: 3000,
          });
          setVisible(false);
          setPayment(response.data.payment);
          setSalesPersonDisplayText("");
          reset({
            warehouse_id: watch("warehouse_id"),
            shop_id: "",
            list: [],
          });
        })
        .catch((error) => {
          let errors = error.response.data.errors;
          Object.keys(errors).forEach((field) => {
            setError(field, {
              type: "manual",
              message: errors[field][0],
            });
          });
        });
    } else {
      toast.current.show({
        severity: "warn",
        summary: "Rejected",
        detail: "Must need a Product",
        life: 3000,
      });
    }
  };

  const filterCustomer = (event) => {
    const query = (event?.query ?? "").toString();
    const warehouseIdFromForm = watch("warehouse_id");
    const warehouseIdFromAuth =
      auth?.user?.shop_id ?? null;
    const warehouseId =
      warehouseIdFromForm ??
      warehouseIdFromAuth ??
      null;

    // Backend only returns data when warehouse_id is truthy.
    // Treat only null/undefined/"" as missing.
    if (
      warehouseId === null ||
      warehouseId === undefined ||
      warehouseId === ""
    ) {
      setCustomer([]);
      return;
    }

    setTimeout(() => {
      axios
        .post(route("customer-search-due"), {
          data: query,
          warehouse_id: warehouseId,
        })
        .then((response) => {
          setCustomer(response.data.customer);
        })
        .catch((error) => {
          console.error(
            "customer-search-due failed:",
            error
          );
          setCustomer([]);
        });
    }, 250);
  };

  const selectedItem = (data) => {
    reset({
      customer_id: data.id,
      date: watch("date"),
      warehouse_id: watch("warehouse_id"),
      list: [],
    });
    setValue("payment_type", "cash");

    if (data.total_due != 0) {
      append({
        deu_balance: Number(data.total_due),
        total_sales: data.total_due,
        payment: 0,
        payment_id: "cash",
        payment_type: "cash",
        index: 0,
      });
    } else {
      toast.current.show({
        severity: "warn",
        summary: "Rejected",
        detail: "This customer has no due balance",
        life: 3000,
      });
    }
  };

  const typeFilterTemplate = (options) => {
    return (
      <>
        <div className="flex flex-col  gap-2">
          <Dropdown
            value={paymentStatus}
            options={["cash", "Bank", "Mobile Bank"]}
            onChange={(e) => {
              setValue("payment_type", e.value);
              if (e.value == "cash") {
                setValue(`list.${0}.payment_id`, "cash");
              }
              setPaymentStatus(e.value);
            }}
            placeholder="Select a Status"
            className="p-column-filter"
          />
          {paymentStatus == "Bank" && (
            <Dropdown
              value={Number(paymentType.bank)}
              options={bank}
              onChange={(e) => {
                setValue("payment_type", "Bank");

                setPaymentType((old) => {
                  return {
                    ...old,
                    bank: "Bank",
                  };
                });
              }}
              filter
              showClear
              optionLabel="bank_name"
              optionValue="id"
              itemTemplate={bankTemplate}
              placeholder="Select a Status"
              className="p-column-filter"
            />
          )}

          {paymentStatus == "Mobile Bank" && (
            <Dropdown
              value={Number(paymentType.mobile_bank)}
              options={mobileBank}
              onChange={(e) => {
                setValue("payment_type", "Mobile Bank");
                setPaymentType((old) => {
                  return {
                    ...old,
                    mobile_bank: e.value,
                  };
                });
              }}
              filter
              showClear
              optionLabel="account_type"
              optionValue="id"
              itemTemplate={mobileTemplate}
              placeholder="Select a Status"
              className="p-column-filter"
            />
          )}
        </div>
      </>
    );
  };
  const bankTemplate = (option) => {
    return (
      <div>
        <div>
          {option.bank_name} ({option.account_number})
        </div>
      </div>
    );
  };
  const mobileTemplate = (option) => {
    return (
      <div>
        <div>
          {option.account_type} ({option.account_number})
        </div>
      </div>
    );
  };

  const deleteElement = (id) => {
    let con = confirm("Are you sure to delete it");
    if (con) {
      axios
        .post(route("customer-store-due-collection-delete", id))
        .then((response) => {
          toast.current.show({
            severity: "info",
            summary: "Confirmed",
            detail: response.data.success,
            life: 3000,
          });
          setVisible(false);
          setPayment(response.data.payment);
          setSalesPersonDisplayText("");
          reset({
            warehouse_id: watch("warehouse_id"),
            list: [],
          });
        })
        .catch((error) => {
          let errors = error.response.data.errors;
          Object.keys(errors).forEach((field) => {
            setError(field, {
              type: "manual",
              message: errors[field][0],
            });
          });
        });
    }
  };

  return (
    <>
      <DueReceiptPrint due={due} />
      <AuthenticatedLayout
        user={auth.user}
        header={
          <>
            <h2 className="text-skin-header font-medium ">
              Due Collection
            </h2>{" "}
            <p className="text-skin-sub-header font-semibold text-xs">
              {" "}
              Home - Due Collection
            </p>
          </>
        }
        headerButton={<></>}
      >
        <Toast ref={toast} />
        <ConfirmPopup /> {/* View Table*/}
        <div className="card">
          <DataTable
            className="defulattable"
            value={payment}
            paginator
            showGridlines
            rows={10}
            dataKey="id"
            header={TableHeader}
            filters={filters2}
            emptyMessage="No product found."
          >
            <Column
              alignHeader="center"
              field="date"
              header="Date"
            />
            <Column
              alignHeader="center"
              field="order_no"
              filterField="order_no"
              header="Receipt No"
            />

            <Column
              alignHeader="center"
              filterField="customer.name"
              body={(data) => {
                const customer = data?.customer;
                const name = customer?.name ?? "";
                const code = customer?.code ?? "";
                const number = customer?.number ?? "";
                const userType = customer?.user_type ?? "";

                const parts = [];
                if (name) parts.push(name);
                if (code) parts.push(`(${code})`);
                if (number) parts.push(`(${number})`);
                if (userType) parts.push(`(${userType})`);

                return parts.join(" ");
              }}
              header="Customer/Retailer"
            />
            <Column
              alignHeader="center"
              field="location.name"
              header="Warehouse/shop"
            />

            {permission.includes(
              "customer_retailer_sales_person_view"
            ) && (
                <Column
                  alignHeader="center"
                  body={(data) => {
                    return data?.sales_person
                      ? `${data.sales_person.name} (${data.sales_person.code})`
                      : "No Sales Person";
                  }}
                  header="Sales Person"
                />
              )}
            {/* <Column
                        alignHeader="center"
                        field="supplier.name"
                        header="Company"
                    /> */}
            <Column
              field="account"
              alignHeader="center"
              className="text-right"
              header="Transaction Account"
            />
            <Column
              field="payment"
              alignHeader="center"
              className="text-right"
              header="Total"
            />

            <Column
              alignHeader="center"
              className="text-right"
              header="Action"
              body={(e) => {
                return (
                  <div className="flex  ">
                    {permission.includes(
                      "customer_collection_edit"
                    ) && (
                        <Button
                          icon="bx bx-edit"
                          data-id={e.id}
                          onClick={() => {
                            setVisible(true);
                            editData(e);
                            setStatus("update");
                          }}
                          className="p-button-rounded  p-button-success mr-2 px-3 py-2  w-10 h-10  font-medium"
                        />
                      )}
                    <Button
                      icon="bx bx-printer"
                      data-id={e.id}
                      onClick={() => {
                        setDue(e);
                        setTimeout(() => {
                          window.print();
                        }, 200);
                      }}
                      className="p-button-rounded p-button-info  mr-2 px-3 py-2  w-10 h-10  font-medium"
                    />
                    {permission.includes(
                      "customer_collection_delete"
                    ) && (
                        <Button
                          icon="bx  bxs-trash-alt"
                          data-id={e.id}
                          onClick={() => {
                            deleteElement(e.id);
                          }}
                          className="p-button-rounded p-button-danger  mr-2 px-3 py-2  w-10 h-10  font-medium"
                        />
                      )}
                  </div>
                );
              }}
            />
          </DataTable>
        </div>
        {/* View Table End*/}
        <Dialog
          header={() =>
            status == "create"
              ? "Due Collection"
              : "Update Due Collection"
          }
          visible={visible}
          className=" w-[100%] min-h-[100%] md:w-[70vw] md:min-h-[50vh]"
          onHide={() => {
            setVisible(false);
            setSalesPersonDisplayText("");
            reset({
              warehouse_id: watch("warehouse_id"),
              list: [],
            });
          }}
          footer={footerContent}
        >
          <form
            onSubmit={
              status == "create"
                ? handleSubmit(StoreData)
                : handleSubmit(UpdateData)
            }
            ref={formSubmit}
          >
            <div className=" grid grid-cols-12  gap-x-5 gap-y-6">
              {permission.includes(
                "customer_collection_superAdmin_access"
              ) && (
                  <div className="p-float-label  col-span-12 md:col-span-6">
                    <Controller
                      name="warehouse_id"
                      control={control}
                      rules={{
                        required:
                          "Warehouse/Shop field is required ",
                      }}
                      render={({ field, fieldState }) => (
                        <span className="p-float-label">
                          <WarehouseDropdown
                            setPermission="customer_collection_superAdmin_access"
                            warehouse={field.value}
                            setWarehouse={(data) => {
                              field.onChange(data);
                              reset({
                                warehouse_id: data,
                                customer_id: "",
                                list: [],
                              });
                              setSearchValue(
                                (old) => ({
                                  ...old,
                                  customer: "",
                                })
                              );
                              setCustomerFieldResetKey(
                                (k) => k + 1
                              );
                            }}
                          />
                          <label htmlFor={field.name}>
                            Select Warehouse/Shop
                          </label>
                        </span>
                      )}
                    />
                    {getFormErrorMessageSingel("warehouse_id")}
                  </div>
                )}

              <div className="p-float-label  col-span-12 md:col-span-6">
                <Controller
                  name="customer_id"
                  control={control}
                  rules={{
                    required:
                      "Customer/Retailer field is required ",
                  }}
                  render={({ field }) => (
                    <span className="p-float-label">
                      <AutoComplete
                        key={customerFieldResetKey}
                        value={search.customer}
                        suggestions={customer}
                        completeMethod={filterCustomer}
                        minLength={0}
                        aria-label="Customer"
                        dropdown
                        onClick={() =>
                          filterCustomer({
                            query: search.customer || "",
                          })
                        }
                        onFocus={() =>
                          filterCustomer({
                            query:
                              search.customer ||
                              "",
                          })
                        }
                        itemTemplate={
                          clientItemTemplate
                        }
                        onChange={(e) => {
                          const val = e.value;
                          if (
                            val &&
                            typeof val ===
                            "object" &&
                            val.id
                          ) {
                            field.onChange(val.id);
                            const displayName =
                              val.name ||
                              val.number ||
                              "";
                            const numberPart =
                              val.number &&
                                val.name
                                ? ` (${val.number})`
                                : "";
                            const userTypePart =
                              val.user_type
                                ? ` (${val.user_type})`
                                : "";
                            setSearchValue(
                              (old) => ({
                                ...old,
                                customer:
                                  displayName +
                                  numberPart +
                                  userTypePart,
                              })
                            );
                            selectedItem(val);
                          } else if (
                            typeof val === "string"
                          ) {
                            setSearchValue(
                              (old) => ({
                                ...old,
                                customer: val,
                              })
                            );
                          } else if (val == null) {
                            field.onChange(null);
                            reset({
                              customer_id: null,
                              date: watch("date"),
                              warehouse_id:
                                watch(
                                  "warehouse_id"
                                ),
                              list: [],
                            });
                            setSearchValue(
                              (old) => ({
                                ...old,
                                customer: "",
                              })
                            );
                          }
                        }}
                        dropdownAriaLabel="Select Customer"
                        className="w-full h-11"
                      />
                      <label htmlFor={field.name}>
                        {"Search Customer & Retailer"}
                      </label>
                    </span>
                  )}
                />
                {getFormErrorMessageSingel("customer_id")}
              </div>
              {permission.includes(
                "customer_retailer_sales_person_view"
              ) && (
                  <div className="p-float-label   col-span-12 md:col-span-6">
                    <Controller
                      name="sales_person_id"
                      control={control}
                      render={({ field, fieldState }) => (
                        <SalesPersonSearch
                          control={control}
                          salesPersonText={
                            salesPersonDisplayText
                          }
                          onSalesPersonSelect={(
                            selectedPerson
                          ) => {
                            field.onChange(
                              selectedPerson.id
                            );
                          }}
                          placeholder="Search Sales Person"
                          className="w-full h-11"
                        />
                      )}
                    />
                  </div>
                )}

              <div className="p-float-label   col-span-12 md:col-span-6">
                <Controller
                  name="date"
                  rules={{
                    required: "Date field is required ",
                  }}
                  control={control}
                  render={({ field, fieldState }) => (
                    <span className="p-float-label">
                      <Calendar
                        id="icon"
                        value={watch("date")}
                        {...field}
                        showIcon
                        className="w-full h-10"
                      />
                      <label htmlFor={field.name}>
                        Current Date
                      </label>
                    </span>
                  )}
                />
                {getFormErrorMessageSingel("date")}
              </div>
              <div className="p-float-label   col-span-12 md:col-span-6">
                <Controller
                  name="order_no"
                  rules={{
                    required:
                      "Receipt No  field is required",
                  }}
                  control={control}
                  render={({ field, fieldState }) => (
                    <span className="p-float-label">
                      <InputText
                        {...field}
                        className="w-full"
                      />

                      <label htmlFor={field.name}>
                        Receipt No
                      </label>
                    </span>
                  )}
                />
                {getFormErrorMessageSingel("order_no")}
              </div>
              <div className="p-float-label   col-span-12 md:col-span-6">
                <Controller
                  name="note"
                  control={control}
                  render={({ field, fieldState }) => (
                    <span className="p-float-label">
                      <InputText
                        {...field}
                        className="w-full"
                      />

                      <label htmlFor={field.name}>
                        Note
                      </label>
                    </span>
                  )}
                />
              </div>
            </div>

            <DataTable
              className="defulattable w-full overflow-x-auto" // Full width and allow horizontal scrolling
              value={fields}
              showGridlines
              dataKey="id"
              header={CompanyTableHeader}
              filters={filters}
              emptyMessage="No Company found."
              responsiveLayout="scroll" // Enable responsive layout in PrimeReact DataTable
            >
              <Column
                field="deu_balance"
                header="Due Balance"
                body={(data, index) => {
                  return (
                    <>
                      <Controller
                        control={control}
                        name={`list.${data.index}.deu_balance`}
                        rules={{
                          required:
                            "Balance Field is required",
                          min: {
                            value: 0,
                            message:
                              "negative value not allow",
                          },
                        }}
                        render={({ field }) => (
                          <InputText
                            readOnly
                            id={`opening_balance-${data.id}`}
                            className={`w-[140px] md:w-full h-10 ${errors?.list?.[
                              data.id
                            ]?.deu_balance &&
                              "p-invalid"
                              }`}
                            value={watch(
                              `list.${data.index}.deu_balance`
                            )}
                            placeholder="Due Balance"
                            onChange={(e) => {
                              setValue(
                                `list.${data.index}.deu_balance`,
                                e.target.value
                              );
                            }}
                            type="number"
                            min={0}
                          />
                        )}
                      />
                      {getFormErrorMessageMultiple(
                        `deu_balance`,
                        data.id
                      )}
                    </>
                  );
                }}
              />
              <Column
                field="payment"
                header="Payment"
                body={(data, index) => {
                  return (
                    <>
                      <Controller
                        control={control}
                        name={`list.${data.index}.payment`}
                        rules={{
                          required:
                            "Balance Field is required",
                          min: {
                            value: 0,
                            message:
                              "negative value not allow",
                          },
                          validate: (value) => {
                            const total = Number(
                              watch(
                                `list.${data.index}.total_sales`
                              ) || 0
                            );
                            const prev = Number(
                              watch(
                                `list.${data.index}.prev_payment`
                              ) || 0
                            );

                            const maxPayable =
                              total + prev;

                            return (
                              maxPayable >=
                              Number(value) ||
                              "Over pay not allowed"
                            );
                          },
                        }}
                        render={({ field }) => (
                          <InputText
                            id={`payment-${data.id}`}
                            className={`w-[140px] md:w-full h-10 ${errors?.list?.[
                              data.id
                            ]?.payment &&
                              "p-invalid"
                              }`}
                            value={watch(
                              `list.${data.index}.payment`
                            )}
                            placeholder="Payment"
                            onChange={(e) => {
                              setValue(
                                `list.${data.index}.payment`,
                                e.target.value
                              );
                            }}
                            type="number"
                            min={0}
                          />
                        )}
                      />
                      {getFormErrorMessageMultiple(
                        `payment`,
                        data.index
                      )}
                    </>
                  );
                }}
              />
              <Column
                field="payment_type"
                header={
                  "Payment Type  " + "(" + paymentStatus + ")"
                }
                filter
                filterElement={typeFilterTemplate}
                showFilterMatchModes={false}
                body={(data, index) => {
                  return (
                    <>
                      <Controller
                        control={control}
                        name={`list.${data.index}.payment_id`}
                        rules={{
                          required:
                            "Payment Field is required",
                          min: {
                            value: 0,
                            message:
                              "negative value not allow",
                          },
                        }}
                        render={({ field }) => (
                          <>
                            {paymentStatus ==
                              "Bank" && (
                                <Dropdown
                                  options={bank}
                                  {...field}
                                  filter
                                  showClear
                                  optionLabel="bank_name"
                                  optionValue="id"
                                  itemTemplate={
                                    bankTemplate
                                  }
                                  placeholder="Select a Status"
                                  className="p-column-filter w-full"
                                />
                              )}

                            {paymentStatus ==
                              "Mobile Bank" && (
                                <Dropdown
                                  value={Number(
                                    paymentType.mobile_bank
                                  )}
                                  options={
                                    mobileBank
                                  }
                                  filter
                                  {...field}
                                  showClear
                                  optionLabel="account_type"
                                  optionValue="id"
                                  itemTemplate={
                                    mobileTemplate
                                  }
                                  placeholder="Select a Status"
                                  className="p-column-filter w-full"
                                />
                              )}

                            {paymentStatus ==
                              "cash" && (
                                <Dropdown
                                  options={[
                                    {
                                      id: "cash",
                                      label: "Cash",
                                    },
                                  ]}
                                  filter
                                  {...field}
                                  showClear
                                  optionLabel="label"
                                  optionValue="id"
                                  placeholder="Select a Status"
                                  className="p-column-filter w-full"
                                />
                              )}
                          </>
                        )}
                      />
                      {getFormErrorMessageMultiple(
                        `payment_id`,
                        data.index
                      )}
                    </>
                  );
                }}
              />
            </DataTable>
          </form>
        </Dialog>
      </AuthenticatedLayout>
    </>
  );
}

export default DeuCollection;
