import React from "react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Column } from "primereact/column";
import { Button } from "primereact/button";
import { InputText } from "primereact/inputtext";
import { useEffect } from "react";
import axios from "axios";
import { useState, useRef } from "react";
import { ColumnGroup } from "primereact/columngroup";
import { Row } from "primereact/row";
import { Dropdown } from "primereact/dropdown";
import ProductDropdown from "@/Components/ProductDropdown";
import DynamicFieldGroup from "@/Components/DynamicFieldGroup";
import { Dialog } from "primereact/dialog";
import { useForm, Controller, useFieldArray } from "react-hook-form";
import { classNames } from "primereact/utils";
import { Calendar } from "primereact/calendar";
import { Toast } from "primereact/toast";
import { AutoComplete } from "primereact/autocomplete";
import { ConfirmPopup, confirmPopup } from "primereact/confirmpopup";
import { InputMask } from "primereact/inputmask";
import QuotationPrintPage from "./QuotationPrintPage";
import CustomerDropdown from "@/Components/CustomerDropdown";
import DocumentUpload from "@/Components/DocumentUpload";
import SendForApprovalModal from "@/Components/SendForApprovalModal";
import ServerSideDataTable from "@/Components/ServerSideDataTable";
import "react-quill/dist/quill.snow.css";
import { can } from "@/Utils/helper";

function Quotation({ auth, quotationSetting, client, quotation }) {
  const [warehouse, SetWarehouse] = useState([]);
  const [modelShow, setModelShow] = useState(false);
  const [warehouseList, setWarehouses] = useState([]);
  const [categoryList, SetCategoryList] = useState([]);
  const [supplierList, SetSupplierList] = useState([]);
  const [existOpening, setExistOpening] = useState(false);
  const [quotationList, setQuotationList] = useState([]);
  const [quotationInfo, setQuotationInfo] = useState([]);
  const [status, setStatus] = useState("create");
  const [selectCustomer, setSelectCustomer] = useState("");
  const [documentModalVisible, setDocumentModalVisible] = useState(false);
  const [selectedQuotationForDocs, setSelectedQuotationForDocs] = useState(null);
  const [approvalModalVisible, setApprovalModalVisible] = useState(false);
  const [selectedQuotationForApproval, setSelectedQuotationForApproval] = useState(null);
  const [search, setSearch] = useState({
    product: "",
  });
  const [product, setPriceProduct] = useState([]);
  const [refreshTrigger, setRefreshTrigger] = useState(0);

  const scroll = useRef();
  const toast = useRef();
  const FormSubmit = useRef();
  const dataTableRef = useRef(null);

  // Default view
  useEffect(() => {
    axios.get(route("warehouse-opening.view")).then((response) => {
      SetWarehouse(response.data.warehouse);
      setWarehouses(response.data.warehouseList);
      SetCategoryList(response.data.categoryList);
      SetSupplierList(response.data.supplier);
    });
  }, []);
  // Form Control forme React Form Hook
  const {
    control,
    register,
    formState: { errors },
    handleSubmit,
    reset,
    watch,
    setValue,
  } = useForm({
    defaultValues: {
      date: new Date(),
      customer_id: "",
      product_quotation_setting_id: "",
      delivery_lead_time: null,
      validity_period: "",
      payment_term: "",
      tax_exclude_include: "",
      list: [
        {
          product_name: "",
          product_id: "",
          attribute_id: "",
          quantity: "",
          unit_price: "",
          unit_price: "",
          tax: "",
          vat: "",
          total: 0,
          stock_qty: 0,
        },
      ],
    },
  });
  const { fields, append, remove } = useFieldArray({
    control,
    name: "list",
  });
  //Model Hide
  const hideModel = () => {
    setModelShow(false);
    setSelectCustomer("");
    reset({
      date: new Date(),
      customer_id: "",
      product_quotation_setting_id: "",
      delivery_lead_time: null,
      validity_period: "",
      payment_term: "",
      tax_exclude_include: "",
      list: [
        {
          product_id: "",
          quantity: "",
          price: "",
          unit_id: "",
          category_id: "",
          total: 0,
        },
      ],
    });
  };

  // Refresh data table
  const refreshData = () => {
    setRefreshTrigger(prev => prev + 1);
  };

  {
    /* Model Footer Content  */
  }
  const footerContent = (
    <div className="grid  grid-cols-12 ">
      <div className="col-span-12">
        <Button
          label="Cancel"
          icon="pi pi-times"
          onClick={hideModel}
          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>
    </div>
  );
  {
    /* Model Footer Content  */
  }

  // set Error Message Multiple field
  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>
    ) : (
      ""
    );
  };
  // set Error Message Multiple single Field
  const getFormErrorMessageSingle = (name) => {
    return errors[name] ? (
      <small className="p-error ">{errors[name]["message"]}</small>
    ) : (
      ""
    );
  };


  //Set Selected Product
  const selectedItem = (item) => {
    setSearch((old) => {
      return {
        product: "",
      };
    });
    // Assuming "inputField" is the reference to your input field
    let inputValue = "";

    if (item.product) {
      inputValue += item.product.name + " ";

      if (item.sku) inputValue += "(SKU: " + item.sku + ")";
    }

    let list = watch("list");
    let find = list && list.find((e) => e.attribute_id == item.id);

    if (find) {
      toast.current.show({
        severity: "warn",
        summary: "Rejected",
        detail: "Your Product is already add ",
        life: 3000,
      });
    } else {
      // Get stock quantity from warehouse relation
      const stockQty = item.warehouse?.quantity ?? 0;
      
      append({
        product_name: inputValue,
        product_id: Number(item.product.id),
        other: item,
        attribute_id: Number(item.id),
        quantity: "",
        unit_price: Number(item.unit_price),
        vat: 0,
        tax: 0,
        total: "",
        stock_qty: Number(stockQty),
      });
    }
  };

  // Format date to YYYY-MM-DD for MySQL
  const formatDateForDB = (date) => {
    if (!date) return null;
    if (date instanceof Date) {
      return date.toISOString().split('T')[0];
    }
    if (typeof date === 'string') {
      return date.split('T')[0];
    }
    return null;
  };

  const storeWareHouse = (data) => {
    if (data.list.length != 0) {
      // Format dates before sending
      const formattedData = {
        ...data,
        date: formatDateForDB(data.date),
        delivery_lead_time: formatDateForDB(data.delivery_lead_time),
      };
      axios
        .post(route("product-quotation.store"), formattedData)
        .then((response) => {
          toast.current.show({
            severity: "info",
            summary: "Confirmed",
            detail: response.data.message,
            life: 3000,
          });
          refreshData();
          setSelectCustomer("");
          reset({
            date: new Date(),
            customer_id: "",
            product_quotation_setting_id: "",
            delivery_lead_time: null,
            validity_period: "",
            payment_term: "",
            tax_exclude_include: "",
            list: [],
          });
          setModelShow(false);
        });
    } else {
      toast.current.show({
        severity: "warn",
        summary: "Rejected",
        detail: "Must  need a product",
        life: 3000,
      });
    }
  };

  let list = watch("list");
  // easiest Product Store array for check
  const ProductCheck = [];
  // Update Warehouse Data  Opening Stock
  const updateWarehouse = (data) => {
    if (data.list.length != 0) {
      // Format dates before sending
      const formattedData = {
        ...data,
        date: formatDateForDB(data.date),
        delivery_lead_time: formatDateForDB(data.delivery_lead_time),
      };
      axios
        .put(route("product-quotation.update", data.id), formattedData)
        .then((response) => {
          toast.current.show({
            severity: "info",
            summary: "Confirmed",
            detail: response.data.message,
            life: 3000,
          });
          refreshData();
          setSelectCustomer("");
          reset({
            date: new Date(),
            customer_id: "",
            product_quotation_setting_id: "",
            delivery_lead_time: null,
            validity_period: "",
            payment_term: "",
            tax_exclude_include: "",
            list: [],
          });
          setModelShow(false);
        });
    } else {
      toast.current.show({
        severity: "warn",
        summary: "Rejected",
        detail: "Must  need a product",
        life: 3000,
      });
    }
  };

  // Data Delete
  const handelDelete = (e) => {
    const id = e.currentTarget.getAttribute("data-id");

    confirmPopup({
      target: e.currentTarget,
      message: "Do you want to delete this record?",
      icon: "pi pi-info-circle",
      acceptClassName: "p-button-danger",
      accept() {
        axios
          .delete(route("product-quotation.destroy", id))
          .then((response) => {
            refreshData();
            toast.current.show({
              severity: "info",
              summary: "Confirmed",
              detail: response.data.message,
              life: 3000,
            });
          })
          .catch((error) => {
            toast.current.show({
              severity: "warn",
              summary: "Rejected",
              detail: error.response.data.error,
              life: 3000,
            });
          });
      },
      reject() {
        toast.current.show({
          severity: "warn",
          summary: "Rejected",
          detail: "You have rejected",
          life: 3000,
        });
      },
    });
  };




  return (
    <>
      <div className=" hidden print:block">
        <QuotationPrintPage quotationInfo={quotationInfo} />
      </div>

      <AuthenticatedLayout
        user={auth.user}
        header={
          <>
            <h2 className="text-skin-header font-medium ">
              Quotations
            </h2>{" "}
            <p className="text-skin-sub-header font-semibold text-xs">
              {" "}
              Home - Quotations
            </p>
          </>
        }
        headerButton={<></>}
      >
        <Toast ref={toast} />
        {/* View Table*/}
        <div className="card">
          <ServerSideDataTable
            key={refreshTrigger}
            fetchUrl={route("product-quotation.view")}
            emptyMessage="No quotation found."
            headerActions={({ search, setSearch }) => (
              <>
                <Button
                  type="button"
                  icon={<span className="pi pi-plus text-sm pr-1" />}
                  label="Add"
                  onClick={() => {
                    setStatus("create");
                    setSelectCustomer("");
                    reset({
                      date: new Date(),
                      customer_id: "",
                      product_quotation_setting_id: "",
                      delivery_lead_time: "",
                      validity_period: "",
                      payment_term: "",
                      tax_exclude_include: "",
                      list: [],
                    });
                    setModelShow(true);
                  }}
                  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"
                    placeholder="Search"
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                  />
                </span>
              </>
            )}
          >
            <Column
              body={(e) =>
                new Date(e.date).toLocaleDateString("en-us")
              }
              header="Date"
              className="text-left "
            />
            <Column
              field="client.name"
              header="Customer"
              className="text-left "
            />
            <Column
              field="product_quotation_setting.title"
              header="Quotation Info"
              className="text-left "
            />
            <Column
              header="Status"
              body={(rowData) => {
                return (
                  <div className="flex flex-col gap-1 items-center">
                    {rowData.approval_status == 'draft' && (
                      <span className="px-2 py-1 text-xs font-semibold rounded bg-gray-100 text-gray-800">
                        DRAFT
                      </span>
                    )}
                    {rowData.approval_status && rowData.approval_status !== 'draft' && (
                      <span
                        className={`px-2 py-1 rounded text-xs font-semibold ${rowData.approval_status === 'approved'
                          ? 'bg-green-100 text-green-800'
                          : rowData.approval_status === 'rejected'
                            ? 'bg-red-100 text-red-800'
                            : 'bg-yellow-100 text-yellow-800'
                          }`}
                        title={`Approval Status: ${rowData.approval_status}`}
                      >
                        {rowData.approval_status?.toUpperCase()}
                      </span>
                    )}
                  </div>
                );
              }}
              bodyClassName="text-center"
              style={{ minWidth: "120px" }}
            />
            <Column
              header="Action"
              body={(rowData) => (
                <>
                  {" "}
                  <ConfirmPopup />{" "}
                  <Button
                    icon="pi pi-eye"
                    title="View Details"
                    onClick={() => {
                      window.location.href = route("product-quotation.show", rowData.id);
                    }}
                    className="p-button-rounded p-button-help mr-2 px-3 py-2 w-10 h-10 font-medium"
                  />
                  <Button
                    icon="pi pi-pencil"
                    onClick={() => {
                      setModelShow(true);
                      setStatus("update");
                      setExistOpening(true);
                      const customerName = rowData.client
                        ? `${rowData.client.name}${rowData.client.code
                          ? ` (${rowData.client.code})`
                          : ""
                        }`
                        : "";
                      setSelectCustomer(customerName);
                      // Get header and footer from the quotation setting relationship
                      const setting = rowData.product_quotation_setting;
                      reset({
                        id: rowData.id,
                        date: new Date(rowData.date), // Converts date string to Date object
                        customer_id: Number(
                          rowData.customer_id
                        ), // Converts warehouse_id to number
                        product_quotation_setting_id:
                          Number(
                            rowData.product_quotation_setting_id
                          ), // Converts supplier_id to number
                        delivery_lead_time: rowData.delivery_lead_time ? new Date(rowData.delivery_lead_time) : null,
                        validity_period: rowData.validity_period || "",
                        payment_term: rowData.payment_term || "",
                        tax_exclude_include: rowData.tax_exclude_include || "",
                        header: setting?.header || "",
                        footer: setting?.footer || "",
                        list: rowData.product_quotation_details.map(
                          (item) => {
                            // Mapping over rowData.details
                            return {
                              product_name:
                                item.product_name, // Adjust according to your data
                              product_id: Number(
                                item.product_id
                              ),
                              attribute_id:
                                Number(
                                  item.attribute_id
                                ),
                              quantity: Number(
                                item.quantity
                              ),
                              unit_price: Number(
                                item.unit_price
                              ),

                              tax: Number(
                                item.tax
                              ), // Ensure correct key names and avoid duplicates
                              vat: Number(
                                item.vat
                              ),
                              total: Number(
                                item.total
                              ),
                              stock_qty: Number(item.stock_qty || 0),
                              other: Number(
                                item
                              ),
                            };
                          }
                        ),
                      });
                    }}
                    className="p-button-rounded p-button-success mr-2 px-3 py-2  w-10 h-10 font-medium"
                  />
                  <Button
                    icon="bx bx-printer"
                    onClick={() => {
                      setQuotationInfo(rowData);
                      setTimeout(() => {
                        window.print();
                      }, 100);
                    }}
                    className="p-button-rounded p-button-info  mr-2 px-3 py-2  w-10 h-10  font-medium"
                  />
                  <Button
                    icon="pi pi-file"
                    title="Manage Documents"
                    onClick={() => {
                      setSelectedQuotationForDocs(rowData);
                      setDocumentModalVisible(true);
                    }}
                    className="p-button-rounded mr-2 p-button-secondary w-10 h-10 font-medium"
                  />

                  {rowData.approval_status === 'draft' || !rowData.approval_status ? (
                    <Button
                      icon="pi pi-send"
                      title="Send for Approval"
                      onClick={() => {
                        setSelectedQuotationForApproval(rowData);
                        setApprovalModalVisible(true);
                      }}
                      className="p-button-rounded p-button-primary mr-2 px-3 py-2 w-10 h-10 font-medium"
                    />
                  ) : rowData.approval_status === 'rejected' ? (
                    <Button
                      icon="pi pi-refresh"
                      title="Reapply for Approval"
                      onClick={() => {
                        setSelectedQuotationForApproval(rowData);
                        setApprovalModalVisible(true);
                      }}
                      className="p-button-rounded p-button-warning mr-2 px-3 py-2 w-10 h-10 font-medium"
                    />
                  ) : null}
                  <Button
                    icon="pi pi-trash"
                    data-id={rowData.id}
                    onClick={handelDelete}
                    className="p-button-rounded p-button-warning px-3 py-2  w-10 h-10  font-medium"
                  />
                </>
              )}
              dataType="boolean"
              bodyClassName="text-center"
            />
          </ServerSideDataTable>
        </div>
        {/* View Table End*/}

        {/* Create Model*/}
        <Dialog
          header="Quotation "
          visible={modelShow}
          style={{ width: "80vw", height: "100vh" }}
          footer={footerContent}
          onHide={hideModel}
        >
          <form
            onSubmit={
              status == "create"
                ? handleSubmit(storeWareHouse)
                : handleSubmit(updateWarehouse)
            }
            className="p-fluid relative"
            method="POST"
            ref={FormSubmit}
          ></form>
          <div className="grid grid-cols-12 gap-x-5 gap-y-6  mt-5">
            <div className="col-span-4">
              <span className="p-float-label">
                <Controller
                  name="date"
                  control={control}
                  rules={{ required: "Date is required." }}
                  render={({ field, fieldState }) => (
                    <Calendar
                      {...field}
                      className="w-full h-11"
                    />
                  )}
                />
                <label htmlFor="name"> Date</label>
              </span>
              {getFormErrorMessageSingle("date")}
            </div>
            <div className="col-span-4">
              <span className="p-float-label">
                <Controller
                  name="product_quotation_setting_id"
                  control={control}
                  rules={{
                    required: "quotation info is required.",
                  }}
                  render={({ field, fieldState }) => (
                    <Dropdown
                      showClear={true}
                      options={quotationSetting}
                      optionLabel="title"
                      optionValue="id"
                      value={field.value}
                      onChange={(event) => {
                        field.onChange(
                          event.value ?? ""
                        );

                      }}
                      placeholder="Select a quotation info"
                      className="w-full md:w-14rem"
                    />
                  )}
                />
                <label htmlFor="name"> Quotation info</label>
              </span>
              {getFormErrorMessageSingle(
                "product_quotation_setting_id"
              )}
            </div>
            <div className="col-span-4">
              <Controller
                name="customer_id"
                control={control}

                rules={{
                  required: "Customer is required.",
                }}
                render={({ field }) => (
                  <CustomerDropdown
                    selectedValue={selectCustomer}
                    placeholder={can('for_labware') ? 'Company search ' : 'Customer search '}
                    onSelect={(customer) => {
                      setSelectCustomer(
                        customer
                          ? `${customer.name}${customer.code
                            ? ` (${customer.code})`
                            : ""
                          }`
                          : ""
                      );
                      field.onChange(
                        customer?.id || ""
                      );
                    }}
                    showLabel={false}
                    className="w-full"
                    inputClassName="w-full h-11 rounded-lg"
                  />
                )}
              />
              {getFormErrorMessageSingle("customer_id")}
            </div>
            <div className="col-span-4">
              <span className="p-float-label">
                <Controller
                  name="delivery_lead_time"
                  control={control}
                  render={({ field, fieldState }) => (
                    <Calendar
                      value={field.value ? (field.value instanceof Date ? field.value : new Date(field.value)) : null}
                      onChange={(e) => field.onChange(e.value)}
                      className="w-full h-11"
                      showIcon
                      dateFormat="yy-mm-dd"
                    />
                  )}
                />
                <label htmlFor="delivery_lead_time">
                  Delivery Lead Time
                </label>
              </span>
            </div>
            <div className="col-span-4">
              <span className="p-float-label">
                <Controller
                  name="validity_period"
                  control={control}
                  render={({ field }) => (
                    <InputText
                      {...field}
                      className="w-full h-11"
                    />
                  )}
                />
                <label htmlFor="validity_period">
                  Validity Period of the Quotation
                </label>
              </span>
            </div>
            <div className="col-span-4">
              <span className="p-float-label">
                <Controller
                  name="tax_exclude_include"
                  control={control}
                  render={({ field }) => (
                    <Dropdown
                      {...field}
                      options={[
                        { label: "Exclude", value: "exclude" },
                        { label: "Include", value: "include" }
                      ]}
                      optionLabel="label"
                      optionValue="value"
                      placeholder="Select"
                      className="w-full h-11"
                      showClear
                    />
                  )}
                />
                <label htmlFor="tax_exclude_include">
                  Tax Exclude/Include
                </label>
              </span>
            </div>
            <div className="col-span-4">
              <span className="p-float-label">
                <Controller
                  name="payment_term"
                  control={control}
                  render={({ field }) => (
                    <InputText
                      {...field}
                      className="w-full h-11"
                    />
                  )}
                />
                <label htmlFor="payment_term">
                  Payment Term
                </label>
              </span>
            </div>


            <>
              <div className="field col-span-12 md:col-span-12 mx-[25%] mt-5">
                <Controller
                  name="remark"
                  control={control}
                  render={({ field, fieldState }) => (
                    <ProductDropdown
                      field={field}
                      selectedItem={selectedItem}
                    />
                  )}
                />
              </div>
            </>
          </div>
          <div
            className=" grid grid-cols-12 gap-6 mt-10 "
            ref={scroll}
          >
            {fields.map((item, index) => (
              <DynamicFieldGroup
                key={item.id}
                control={control}
                watch={watch}
                setValue={setValue}
                remove={remove}
                index={index}
                getFormErrorMessageMultiple={
                  getFormErrorMessageMultiple
                }
                mode="quotation"
                readOnlyFields={[
                  "product_name",
                  "total",
                ]}
              />

            ))}
          </div>


          <div className="grid grid-cols-12 ">
            <div className="col-span-6 text-right mr-3">
              {list && (
                <b>
                  Total QTY:{" "}
                  {list.reduce(
                    (acc, item) =>
                      acc + Number(item.quantity),
                    0
                  )}
                </b>
              )}
            </div>
            <div className="col-span-4 text-right mr-3">
              {list && (
                <b>
                  Total Unit Price:{" "}
                  {list.reduce(
                    (acc, item) => acc + Number(item.total),
                    0
                  )}
                </b>
              )}
            </div>
          </div>


        </Dialog>
        {/* Create Model End*/}

        {/* Document Management Modal */}
        <Dialog
          header="Manage Documents"
          visible={documentModalVisible}
          style={{ width: "90vw", maxWidth: "800px" }}
          onHide={() => {
            setDocumentModalVisible(false);
            setSelectedQuotationForDocs(null);
          }}
          footer={
            <div className="flex justify-end">
              <Button
                label="Close"
                icon="pi pi-times"
                className="p-button-text"
                onClick={() => {
                  setDocumentModalVisible(false);
                  setSelectedQuotationForDocs(null);
                }}
              />
            </div>
          }
        >
          {selectedQuotationForDocs && (
            <div className="p-4">
              <div className="mb-4 p-3 bg-blue-50 rounded-lg border border-blue-200">
                <div className="text-sm font-semibold text-blue-900">
                  Quotation: {selectedQuotationForDocs.quotation_number}
                </div>
                <div className="text-xs text-blue-700 mt-1">
                  Date: {new Date(selectedQuotationForDocs.date).toLocaleDateString()}
                </div>
                {selectedQuotationForDocs.client && (
                  <div className="text-xs text-blue-700 mt-1">
                    Client: {selectedQuotationForDocs.client.name}
                  </div>
                )}
              </div>
              <DocumentUpload
                documentableType="App\\Models\\productQuotationMaster"
                documentableId={selectedQuotationForDocs.id}
                showLabel={true}
                label="Documents"
              />
            </div>
          )}
        </Dialog>

        {/* Send for Approval Modal */}
        <SendForApprovalModal
          visible={approvalModalVisible}
          onHide={() => {
            setApprovalModalVisible(false);
            setSelectedQuotationForApproval(null);
          }}
          approvableType="productQuotationMaster"
          approvableId={selectedQuotationForApproval?.id}
          onSuccess={() => {
            refreshData();
          }}
        />
      </AuthenticatedLayout>
    </>
  );
}

export default Quotation;
