import { React, useState, useContext } from "react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Button } from "primereact/button";
import { InputText } from "primereact/inputtext";
import { Dialog } from "primereact/dialog";
import { Checkbox } from "primereact/checkbox";
import { useRef } from "react";
import { Controller, useForm, useFieldArray } from "react-hook-form";
import axios from "axios";
import { Toast } from "primereact/toast";
import { useEffect } from "react";
import { ConfirmPopup, confirmPopup } from "primereact/confirmpopup";
import { InputTextarea } from "primereact/inputtextarea";
import { authUser } from "@/Components/AuthProvider";
import { Calendar } from "primereact/calendar";
import { Dropdown } from "primereact/dropdown";
import { can } from "../../Utils/helper";
import DataTable from "@/Components/DataTable";
import FormFieldRenderer from "@/Components/FormFieldRenderer";
import { getFormConfig } from "@/configs/formConfigs";


function Customer({ auth }) {
  const { permission } = useContext(authUser);
  const [status, setStatus] = useState("create");
  const [visible, setVisible] = useState(false);
  const [customer, setCustomer] = useState([]);
  const [id, setId] = useState();
  const [code, setCode] = useState();
  const [departments, setDepartments] = useState([]);
  const [designations, setDesignations] = useState([]);
  const formSubmit = useRef(null);
  const toast = useRef(null);
  const [branchModalVisible, setBranchModalVisible] = useState(false);
  const [selectedCustomerForBranches, setSelectedCustomerForBranches] = useState(null);
  const [branches, setBranches] = useState([]);
  const [branchStatus, setBranchStatus] = useState("create");
  const [branchId, setBranchId] = useState();
  const [branchCode, setBranchCode] = useState("");
  const [serialMap, setSerialMap] = useState({});
  const [refreshTrigger, setRefreshTrigger] = useState(0);
  const {
    control,
    register,
    handleSubmit,
    formState: { errors },
    setValue,
    watch,
    reset,
    setError,
  } = useForm({
    code: "",
    name: "",
    email: "",
    number: "",
    nid: "",
    address: "",
    user_type: "",
    status: "",
    invoice_type: "",
    opening_balance: "",
    opening_date: "",
    contact_persons: [],
  });

  const formdata = watch();

  const {
    control: branchControl,
    register: branchRegister,
    handleSubmit: branchHandleSubmit,
    formState: { errors: branchErrors },
    reset: branchReset,
    setValue: branchSetValue,
    watch: branchWatch,
  } = useForm({
    branch_name: "",
    branch_code: "",
    contact_person: "",
    phone: "",
    email: "",
    address: "",
    status: "1",
  });

  // Contact persons field array
  const { fields: contactFields, append: appendContact, remove: removeContact, replace: replaceContacts } = useFieldArray({
    control,
    name: "contact_persons",
  });

  useEffect(() => {
    axios.get(route("customer.view")).then((response) => {
      setCustomer(response.data.customer);
      setCode(response.data.code);
    });

    // Load departments and designations
    axios.get(route("department.view")).then((response) => {
      setDepartments(response.data.departments || []);
    }).catch((error) => {
      console.error("Error loading departments:", error);
    });

    axios.get(route("designation.view")).then((response) => {
      setDesignations(response.data.designations || []);
    }).catch((error) => {
      console.error("Error loading designations:", error);
    });
  }, []);

  {
    /*Table Header for shared DataTable*/
  }
  const renderHeader = ({ search, setSearch }) => {
    return (
      <>
        {permission.includes("customer_retailer_create") && (
          <Button
            type="button"
            icon={<span className="pi pi-plus text-sm pr-1" />}
            label="Add"
            onClick={() => {
              setVisible(true);
              setStatus("create");
              reset({
                name: "",
                email: "",
                number: "",
                nid: "",
                address: "",
                user_type: "customer",
                code: code,
                status: "1",
                invoice_type: "MRP",
                opening_balance: "",
                opening_date: "",
                contact_persons: [],
              });
              replaceContacts([]);
            }}
            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={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search"
          />
        </span>


      </>
    )

  };

  {
    /*Dilog Model Footer*/
  }
  const footerContent = (
    <div className="flex justify-end">
      <Button
        label="Cancel"
        icon="pi pi-times"
        onClick={() => {
          setVisible(false);
          reset({
            name: "",
            email: "",
            number: "",
            nid: "",
            address: "",
            user_type: "",
            status: "",
            invoice_type: "",
            opening_balance: "",
            opening_date: "",
            contact_persons: [],
          });
          replaceContacts([]);
          setId(null);
        }}
        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) => {
    axios
      .post(route("customer.store", data))
      .then((response) => {
        toast.current.show({
          severity: "info",
          summary: "Confirmed",
          detail: response.data.success,
          life: 3000,
        });
        setCustomer(response.data.customer);
        setCode(response.data.code);
        reset({
          name: "",
          email: "",
          number: "",
          nid: "",
          address: "",
          user_type: "",
          status: "",
          invoice_type: "",
          opening_balance: "",
          opening_date: "",
          contact_persons: [],
        });
        replaceContacts([]);
        setVisible(false);
        setId(null);
        // trigger server-side table to refetch
        setRefreshTrigger((prev) => prev + 1);
      })
      .catch((error) => {
        let errors = error.response.data.errors;
        Object.keys(errors).forEach((field) => {
          setError(field, {
            type: "manual",
            message: errors[field][0],
          });
        });
      });
  };

  // Data Delete (supports both confirmPopup(event) and confirm(id))
  const handelDelete = (arg) => {
    const isEvent = typeof arg === "object" && arg?.currentTarget?.getAttribute;
    const deleteId = isEvent ? arg.currentTarget.getAttribute("data-id") : arg;

    if (!deleteId) return;

    const doDelete = () => {
      axios
        .delete(route("customer.destroy", deleteId))
        .then((response) => {
          setCustomer(response.data.customer);
          setCode(response.data.code);
          setRefreshTrigger((prev) => prev + 1); // refresh server-side table
          toast.current.show({
            severity: "info",
            summary: "Confirmed",
            detail: response.data.success,
            life: 3000,
          });
        })
        .catch((error) => {
          const msg = error?.response?.data?.error || "Failed to delete";
          toast.current.show({
            severity: "warn",
            summary: "Rejected",
            detail: msg,
            life: 3000,
          });
        });
    };

    if (isEvent) {
      confirmPopup({
        target: arg.currentTarget,
        message: "Do you want to delete this record?",
        icon: "pi pi-info-circle",
        acceptClassName: "p-button-danger",
        accept: doDelete,
        reject() {
          toast.current.show({
            severity: "warn",
            summary: "Rejected",
            detail: "You have rejected",
            life: 3000,
          });
        },
      });
    } else {
      if (confirm("Do you want to delete this record?")) {
        doDelete();
      }
    }
  };
  // Data Update
  const UpdateData = (data) => {
    axios
      .put(route("customer.update", id), data)
      .then((response) => {
        toast.current.show({
          severity: "info",
          summary: "Confirmed",
          detail: response.data.success,
          life: 3000,
        });
        setCustomer(response.data.customer);
        setCode(response.data.code);
        reset({
          name: "",
          email: "",
          number: "",
          nid: "",
          address: "",
          user_type: "",
          status: "",
          invoice_type: "",
          opening_balance: "",
          opening_date: "",
          contact_persons: [],
        });
        replaceContacts([]);
        setVisible(false);
        setId(null);
        // trigger server-side table to refetch
        setRefreshTrigger((prev) => prev + 1);
      })
      .catch((error) => {
        let errors = error.response.data.errors;
        Object.keys(errors).forEach((field) => {
          setError(field, {
            type: "manual",
            message: errors[field][0],
          });
        });
      });
  };

  // Branch Management Functions
  const fetchBranches = (customerId) => {
    axios
      .get(route("customer.branches.view", customerId))
      .then((response) => {
        setBranches(response.data.branches);
        setBranchCode(response.data.branchCode);
      })
      .catch((error) => {
        console.error("Error fetching branches:", error);
      });
  };

  const openBranchModal = (rowData) => {
    setSelectedCustomerForBranches(rowData);
    setBranchModalVisible(true);
    setBranchStatus("create");
    branchReset({
      branch_name: "",
      branch_code: "",
      contact_person: "",
      phone: "",
      email: "",
      address: "",
      status: "1",
    });
    fetchBranches(rowData.id);
  };

  const branchStore = (data) => {
    axios
      .post(route("customer.branches.store"), {
        ...data,
        customer_id: selectedCustomerForBranches.id,
      })
      .then((response) => {
        toast.current.show({
          severity: "success",
          summary: "Success",
          detail: response.data.success,
          life: 3000,
        });
        fetchBranches(selectedCustomerForBranches.id);
        branchReset({
          branch_name: "",
          branch_code: "",
          contact_person: "",
          phone: "",
          email: "",
          address: "",
          status: "1",
        });
        setBranchStatus("create");
        setBranchId(null);
      })
      .catch((error) => {
        const errors = error.response?.data?.errors || {};
        Object.keys(errors).forEach((field) => {
          toast.current.show({
            severity: "error",
            summary: "Error",
            detail: errors[field][0],
            life: 3000,
          });
        });
      });
  };

  const branchUpdate = (data) => {
    axios
      .put(route("customer.branches.update", branchId), data)
      .then((response) => {
        toast.current.show({
          severity: "success",
          summary: "Success",
          detail: response.data.success,
          life: 3000,
        });
        fetchBranches(selectedCustomerForBranches.id);
        branchReset({
          branch_name: "",
          branch_code: "",
          contact_person: "",
          phone: "",
          email: "",
          address: "",
          status: "1",
        });
        setBranchStatus("create");
        setBranchId(null);
      })
      .catch((error) => {
        const errors = error.response?.data?.errors || {};
        Object.keys(errors).forEach((field) => {
          toast.current.show({
            severity: "error",
            summary: "Error",
            detail: errors[field][0],
            life: 3000,
          });
        });
      });
  };

  const branchDelete = (e, branchId) => {
    confirmPopup({
      target: e.currentTarget,
      message: "Do you want to delete this branch?",
      icon: "pi pi-info-circle",
      acceptClassName: "p-button-danger",
      accept: () => {
        axios
          .delete(route("customer.branches.destroy", branchId))
          .then((response) => {
            toast.current.show({
              severity: "success",
              summary: "Success",
              detail: response.data.success,
              life: 3000,
            });
            fetchBranches(selectedCustomerForBranches.id);
          })
          .catch((error) => {
            toast.current.show({
              severity: "error",
              summary: "Error",
              detail: error.response?.data?.message || "Failed to delete branch",
              life: 3000,
            });
          });
      },
    });
  };

  const handleTableDataChange = (items = []) => {
    const map = {};
    items.forEach((row, idx) => {
      map[row.id] = String(idx + 1);
    });
    setSerialMap(map);
  };

  return (
    <AuthenticatedLayout
      user={auth.user}
      header={
        <>
          <h2 className="text-skin-header font-medium ">
            {(() => {
              return can('for_labware') ? 'Company' : 'Customer & Retailer';
            })()}

          </h2>{" "}
          <p className="text-skin-sub-header font-semibold text-xs">
            {" "}
            Home -
            {(() => {
              return can('for_labware') ? 'Company' : 'Customer & Retailer';
            })()}


          </p>
        </>
      }
      headerButton={<></>}
    >
      <Toast ref={toast} />
      <DataTable
        key={refreshTrigger}
        fetchUrl={route("customer.view")}
        emptyMessage="No customer found."
        headerActions={renderHeader}
        className="category-table-compact"
        onDataChange={handleTableDataChange}
        columns={[
          {
            field: "serial",
            header: "SL",
            style: { width: "60px" },
            headerStyle: { textAlign: "center" },
            body: (rowData) => serialMap?.[rowData?.id] || "",
          },
          {
            field: "name",
            header: "Name",
            style: { minWidth: "12rem" },
            headerStyle: { textAlign: "center" },
            body: (data) => {
              const name = data?.name ?? "";
              const code = data?.code ?? "";

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

              return parts.join(" ");
            },
          },
          !can("for_labware") && {
            field: "email",
            header: "Email",
          },
          {
            field: "number",
            header: "Number",
            style: { minWidth: "6rem" },
          },
          {
            field: "opening_balance",
            header: "Opening Balance",
            style: { minWidth: "8rem" },
            body: (data) => (data.opening_balance ? data.opening_balance : "0"),
          },
          {
            field: "opening_date",
            header: "Opening Date",
            style: { minWidth: "8rem" },
            body: (data) => (data.opening_date ? data.opening_date : "N/A"),
          },
          !can("for_labware") && {
            field: "user_type",
            header: "Type",
            style: { minWidth: "6rem" },
          },
          // {
          //   field: "address",
          //   header: "Address",
          //   style: { minWidth: "12rem" },
          //   body: (data) => (data.address ? data.address : "N/A"),
          // },
          {
            type: "action",
            header: "Action",
            style: { width: "140px" },
            permission,
            context: {
              onEdit: (rowData) => {
                setVisible(true);
                setStatus("update");
                setId(rowData.id);

                const contactPersonsData =
                  Array.isArray(rowData.contact_persons) &&
                    rowData.contact_persons.length > 0
                    ? rowData.contact_persons.map((cp) => ({
                      name: cp.name || "",
                      designation_id: cp.designation_id
                        ? Number(cp.designation_id)
                        : null,
                      department_id: cp.department_id
                        ? Number(cp.department_id)
                        : null,
                      email: cp.email || "",
                      number: cp.number || "",
                    }))
                    : [];

                const formData = {
                  name: rowData.name || "",
                  email: rowData.email || "",
                  number: rowData.number || "",
                  nid: rowData.nid || "",
                  opening_date: rowData.opening_date || "",
                  opening_balance: rowData.opening_balance || "",
                  credit: rowData.credit || "",
                  credit_limit: rowData.credit_limit || "",
                  address: rowData.address || "",
                  user_type: rowData.user_type || "",
                  status: rowData.status || "",
                  proprietor: rowData.proprietor || "",
                  invoice_type: rowData.invoice_type || "",
                  code: rowData.code || "",
                  contact_persons: contactPersonsData,
                };

                reset(formData);
                replaceContacts(contactPersonsData);
              },
              onManageBranches: (rowData) => openBranchModal(rowData),
              onDelete: (id) => handelDelete(id),
            },
            actions: [
              {
                label: "Edit",
                icon: "pi pi-pencil",
                permission: "customer_retailer_edit",
                handler: (rowData, ctx) => ctx.onEdit(rowData),
              },
              {
                label: "Branches",
                icon: "pi pi-sitemap",
                permission: "customer_branch_view",
                handler: (rowData, ctx) => ctx.onManageBranches(rowData),
              },
              {
                label: "Delete",
                icon: "pi pi-trash",
                permission: "customer_retailer_delete",
                handler: (rowData, ctx) => ctx.onDelete(rowData.id),
              },
            ],
          },
        ].filter(Boolean)}
      />
      <Dialog
        header={() => (status == "create" ? "Create" : "Update")}
        visible={visible}
        className="md:w-[43vw] w-full"
        onHide={() => {
          setVisible(false);
          reset({
            name: "",
            email: "",
            number: "",
            nid: "",
            address: "",
            user_type: "",
            status: "",
            invoice_type: "",
            opening_balance: "",
            opening_date: "",
            contact_persons: [],
          });
          replaceContacts([]);
          setId(null);
        }}
        footer={footerContent}
      >
        <form
          onSubmit={
            status == "create"
              ? handleSubmit(StoreData)
              : handleSubmit(UpdateData)
          }
          ref={formSubmit}
        >
          <div className="grid grid-cols-12 gap-x-4 gap-y-7 pt-6">
            <FormFieldRenderer
              formName="customer"
              formData={formdata}
              setFormData={() => { }}
              errors={errors}
              context={{ control, permission }}
            />

            {/* Contact Persons Section */}
            {permission.includes("client_contact_person_view") && (
              <div className="col-span-12 mt-10">
                <div className="flex justify-between items-center mb-4">
                  <h3 className="text-lg font-semibold">Contact Persons</h3>
                  {permission.includes("client_contact_person_create") && (
                    <Button
                      type="button"
                      icon="pi pi-plus"
                      label="Add Contact Person"
                      onClick={() => appendContact({
                        name: "",
                        designation_id: "",
                        department_id: "",
                        email: "",
                        number: "",
                      })}
                      className="p-button-sm p-button-success"
                    />
                  )}
                </div>

                {contactFields.map((field, index) => (
                  <div key={field.id} className="grid grid-cols-12 gap-x-2 gap-y-6 mb-4 p-4 border rounded-lg bg-gray-50">
                    <div className="col-span-12 flex justify-between items-center mb-2">
                      <h4 className="font-medium text-sm">Contact Person {index + 1}</h4>
                      {permission.includes("client_contact_person_delete") && (
                        <Button
                          type="button"
                          icon="pi pi-trash"
                          onClick={() => removeContact(index)}
                          className="p-button-sm p-button-danger p-button-text"
                          severity="danger"
                        />
                      )}
                    </div>

                    <FormFieldRenderer
                      config={getFormConfig("customerContactPerson").map((f) => ({
                        ...f,
                        name: `contact_persons.${index}.${f.name}`,
                      }))}
                      formData={formdata}
                      setFormData={() => { }}
                      errors={errors}
                      context={{ control, designations, departments }}
                    />

                  </div>
                ))}

                {contactFields.length === 0 && (
                  <div className="text-center text-gray-500 py-4 border rounded-lg">
                    No contact persons added. {permission.includes("client_contact_person_create") && "Click \"Add Contact Person\" to add one."}
                  </div>
                )}
              </div>
            )}

          </div>
        </form>
      </Dialog>

      {/* Branch Management Dialog */}
      <Dialog
        header={`Manage Branches - ${selectedCustomerForBranches?.name || ""}`}
        visible={branchModalVisible}
        style={{ width: "90vw", maxWidth: "1000px" }}
        onHide={() => {
          setBranchModalVisible(false);
          setSelectedCustomerForBranches(null);
          setBranchStatus("create");
          branchReset();
        }}
        footer={
          <div className="flex justify-end">
            <Button
              label="Close"
              icon="pi pi-times"
              className="p-button-text"
              onClick={() => {
                setBranchModalVisible(false);
                setSelectedCustomerForBranches(null);
                setBranchStatus("create");
                branchReset();
              }}
            />
          </div>
        }
      >
        {selectedCustomerForBranches && (
          <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">
                Customer: {selectedCustomerForBranches.name} ({selectedCustomerForBranches.code})
              </div>
            </div>

            {/* Branch Form */}
            {((branchStatus === "create" && permission.includes("customer_branch_create")) ||
              (branchStatus === "update" && permission.includes("customer_branch_edit"))) && (
                <div className="mb-4 p-4 border rounded-lg bg-gray-50">
                  <h3 className="text-lg font-semibold mb-3">
                    {branchStatus === "create" ? "Add New Branch" : "Edit Branch"}
                  </h3>
                  <form onSubmit={branchHandleSubmit(branchStatus === "create" ? branchStore : branchUpdate)}>
                    <div className="grid grid-cols-12 gap-x-4 gap-y-7 pt-5">
                      <div className="col-span-6">
                        <div className="p-float-label">
                          <InputText
                            id="branch_name"
                            className={`w-full ${branchErrors.branch_name && "p-invalid"}`}
                            {...branchRegister("branch_name", { required: "Branch name is required" })}
                          />
                          <label htmlFor="branch_name">Branch Name *</label>
                        </div>
                        {branchErrors.branch_name && (
                          <small className="p-error">{branchErrors.branch_name.message}</small>
                        )}
                      </div>
                      <div className="col-span-6">
                        <div className="p-float-label">
                          <InputText
                            id="branch_code"
                            className="w-full"
                            value={branchWatch("branch_code") || branchCode}
                            onChange={(e) => branchSetValue("branch_code", e.target.value)}
                          />
                          <label htmlFor="branch_code">Branch Code</label>
                        </div>
                      </div>
                      <div className="col-span-6">
                        <div className="p-float-label">
                          <InputText
                            id="contact_person"
                            className="w-full"
                            {...branchRegister("contact_person")}
                          />
                          <label htmlFor="contact_person">Contact Person</label>
                        </div>
                      </div>
                      <div className="col-span-6">
                        <div className="p-float-label">
                          <InputText
                            id="phone"
                            className="w-full"
                            {...branchRegister("phone")}
                          />
                          <label htmlFor="phone">Contact Number</label>
                        </div>
                      </div>
                      <div className="col-span-6">
                        <div className="p-float-label">
                          <InputText
                            id="email"
                            type="email"
                            className="w-full"
                            {...branchRegister("email")}
                          />
                          <label htmlFor="email">Email</label>
                        </div>
                      </div>
                      <div className="col-span-6">
                        <div className="p-float-label">
                          <Controller
                            name="status"
                            control={branchControl}
                            render={({ field }) => (
                              <Dropdown
                                {...field}
                                options={[
                                  { label: "Active", value: "1" },
                                  { label: "Inactive", value: "0" },
                                ]}
                                optionLabel="label"
                                optionValue="value"
                                className="w-full"
                                placeholder="Select Status"
                              />
                            )}
                          />
                          <label htmlFor="status">Status</label>
                        </div>
                      </div>
                      <div className="col-span-12">
                        <div className="p-float-label">
                          <InputTextarea
                            id="address"
                            rows={3}
                            className="w-full"
                            {...branchRegister("address")}
                          />
                          <label htmlFor="address">Address</label>
                        </div>
                      </div>
                      <div className="col-span-12 flex justify-end gap-2">
                        {branchStatus === "update" && (
                          <Button
                            type="button"
                            label="Cancel"
                            icon="pi pi-times"
                            className="p-button-text"
                            onClick={() => {
                              setBranchStatus("create");
                              branchReset();
                              setBranchId(null);
                            }}
                          />
                        )}
                        {((branchStatus === "create" && permission.includes("customer_branch_create")) ||
                          (branchStatus === "update" && permission.includes("customer_branch_edit"))) && (
                            <Button
                              type="submit"
                              label={branchStatus === "create" ? "Add Branch" : "Update Branch"}
                              icon={branchStatus === "create" ? "pi pi-plus" : "pi pi-check"}
                            />
                          )}
                      </div>
                    </div>
                  </form>
                </div>
              )}

            {/* Branches List */}
            <div>
              <h3 className="text-lg font-semibold mb-3">Branches List</h3>
              <DataTable
                value={branches}
                emptyMessage="No branches found"
                className="p-datatable-sm"
              >
                <Column field="branch_name" header="Branch Name" />
                <Column field="branch_code" header="Code" />
                <Column field="contact_person" header="Contact Person" />
                <Column field="phone" header="Phone" />
                <Column field="email" header="Email" />
                <Column
                  field="status"
                  header="Status"
                  body={(rowData) => (
                    <span className={rowData.status === "1" ? "text-green-600" : "text-red-600"}>
                      {rowData.status === "1" ? "Active" : "Inactive"}
                    </span>
                  )}
                />
                <Column
                  header="Action"
                  body={(rowData) => (
                    <>
                      <ConfirmPopup />
                      <Button
                        icon="pi pi-pencil"
                        className="p-button-rounded p-button-success mr-2 w-8 h-8"
                        onClick={() => {
                          setBranchStatus("update");
                          setBranchId(rowData.id);
                          branchReset({
                            branch_name: rowData.branch_name,
                            branch_code: rowData.branch_code,
                            contact_person: rowData.contact_person || "",
                            phone: rowData.phone || "",
                            email: rowData.email || "",
                            address: rowData.address || "",
                            status: rowData.status || "1",
                          });
                        }}
                      />
                      <Button
                        icon="pi pi-trash"
                        className="p-button-rounded p-button-danger w-8 h-8"
                        onClick={(e) => branchDelete(e, rowData.id)}
                      />
                    </>
                  )}
                />
              </DataTable>
            </div>
          </div>
        )}
      </Dialog>
    </AuthenticatedLayout>
  );
}

export default Customer;
