import React from "react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { FilterMatchMode } from "primereact/api";
import { DataTable } from "primereact/datatable";
import { Column } from "primereact/column";
import { InputText } from "primereact/inputtext";
import { Button } from "primereact/button";
import { useState } from "react";
import { Dialog } from "primereact/dialog";
import { Dropdown } from "primereact/dropdown";
import { classNames } from "primereact/utils";
import { useRef } from "react";
import { useForm, Controller } from "react-hook-form";
import axios from "axios";
import { Toast } from "primereact/toast";
import { useEffect } from "react";
import { ConfirmPopup, confirmPopup } from "primereact/confirmpopup";
import { authUser } from "@/Components/AuthProvider";
import { useContext } from "react";

export default function Brand({ auth }) {
  const { permission } = useContext(authUser);
  const [modelstatus, setmodelStatus] = useState("create");
  const [modelShow, SetModelShow] = useState(false);

  const [showBrand, setBrand] = useState([]);
  const [showMessage, setShowMessage] = useState(false);
  const [formData, setFormData] = useState({});
  const [currentId, setid] = useState(null);
  const [filters, setFilters] = useState({
    global: { value: null, matchMode: FilterMatchMode.CONTAINS },
    name: { value: null, matchMode: FilterMatchMode.STARTS_WITH },
  });
  const [globalFilterValue, setGlobalFilterValue] = useState("");
  const defaultValues = {
    name: "",
  };
  const toast = useRef(null);
  const {
    control,
    formState: { errors },
    handleSubmit,
    reset,
    setError,
  } = useForm({ defaultValues });

  {
    /* Defualt Data View  */
  }
  useEffect(() => {
    axios.get(route("brand.view")).then((res) => {
      setBrand(res.data.brands);
    });
  }, []);
  {
    /* Table Data Search */
  }
  const onGlobalFilterChange = (e) => {
    const value = e.target.value;
    let _filters = { ...filters };

    _filters["global"].value = value;

    setFilters(_filters);
    setGlobalFilterValue(value);
  };
  {
    /* Data Edit Section */
  }

  {
    /* Table Header Component  */
  }
  const renderHeader = () => {
    return (
      <div
        className={`w-100% flex ${permission.includes("brand_create")
            ? "justify-between"
            : "justify-end"
          } `}
      >
        {permission.includes("brand_create") && (
          <Button
            type="button"
            icon={<span className="pi pi-plus text-sm pr-1" />}
            label="Add"
            onClick={() => {
              SetModelShow(true);
              setmodelStatus("create");
              reset({
                name: "",
              });
            }}
            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={globalFilterValue}
            onChange={onGlobalFilterChange}
            placeholder="Search"
          />
        </span>
      </div>
    );
  };
  const header = renderHeader();
  {
    /*End Table Header   */
  }
  {
    /* Model Footer Content  */
  }
  const footerContent = (
    <div className="flex justify-end">
      <Button
        label="Cancel"
        onClick={() => {
          SetModelShow(false);
        }}
        icon="pi pi-times"
        className="p-button-text w-13 text-sm"
      />
    </div>
  );
  {
    /* Model Footer Content  */
  }

  {
    /* error messages   */
  }
  const getFormErrorMessage = (name) => {
    return (
      errors[name] && (
        <small className="p-error">{errors[name].message}</small>
      )
    );
  };

  {
    /* Store Data  */
  }
  const onSubmit = (data) => {
    setFormData(data);
    setShowMessage(true);
    axios
      .post(route("brand.store", data))
      .then((response) => {
        toast.current.show({
          severity: "success",
          summary: response.data.success,
          detail: "Data Insterted ",
          life: 3000,
          className: "custom-toast-class",
        });
        SetModelShow(false);
        reset();
        setBrand(response.data.brands);
      })
      .catch((error) => {
        let errors = error.response.data.errors;
        Object.keys(errors).forEach((field) => {
          setError(field, {
            type: "manual",
            message: errors[field][0],
          });
        });
      });
  };
  {
    /* Edit Data  */
  }
  const handelEdit = (e) => {
    reset({
      name: e.name,
    });

    setid(e.id);
    setmodelStatus("edit");

    SetModelShow(true);
  };
  {
    /* Delete Data   */
  }
  const handelDelete = (event) => {
    const id = event.currentTarget.getAttribute("data-id");
    confirmPopup({
      target: event.currentTarget,
      message: "Do you want to delete this record?",
      icon: "pi pi-info-circle",
      acceptClassName: "p-button-danger",
      accept() {
        axios
          .delete(route("brand.destroy", id))
          .then((response) => {
            setBrand(response.data.brands);

            toast.current.show({
              severity: "info",
              summary: "Confirmed",
              detail: response.data.success,
              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,
        });
      },
    });
  };
  {
    /* Update Data   */
  }
  const HandelUpdate = (data) => {
    setFormData(data);
    setShowMessage(true);
    axios
      .put(route("brand.update", currentId), data)
      .then((response) => {
        toast.current.show({
          severity: "success",
          summary: response.data.success,
          detail: "Data Insterted ",
          life: 3000,
          className: "custom-toast-class",
        });
        SetModelShow(false);
        reset();
        setBrand(response.data.brands);
      })
      .catch((error) => {
        let errors = error.response.data.errors;
        Object.keys(errors).forEach((field) => {
          setError(field, {
            type: "manual",
            message: errors[field][0],
          });
        });
      });
  };

  return (
    <AuthenticatedLayout
      user={auth.user}
      header={
        <>
          <h2 className="text-skin-header font-medium ">Brands</h2>{" "}
          <p className="text-skin-sub-header font-semibold text-xs">
            {" "}
            Home - Brands
          </p>
        </>
      }
      headerButton={<></>}
    >
      <Toast ref={toast} />
      {/* View Table*/}
      <div className="card">
        <DataTable
          className="defulattable"
          value={showBrand}
          paginator
          showGridlines
          rows={10}
          dataKey="id"
          header={header}
          filters={filters}
          emptyMessage="No category found."
        >
          <Column field="name" header="Brands" />

          <Column
            header="Action"
            body={(rowData) => (
              <>
                {" "}
                <ConfirmPopup />{" "}
                {permission.includes("brand_edit") && (
                  <Button
                    icon="pi pi-pencil"
                    onClick={(e) => {
                      handelEdit(rowData);
                    }}
                    className="p-button-rounded p-button-success mr-2 px-3 py-2  w-10 h-10 font-medium"
                  />
                )}
                {permission.includes("brand_delete") && (
                  <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"
                  />
                )}
              </>
            )}
            className="p-button-rounded p-button-success mr-2 px-3 py-2  w-10 h-10 font-medium"
            bodyClassName="text-center"
            style={{ minWidth: "14rem" }}
          />
        </DataTable>
      </div>
      {/* View Table End*/}

      {/* Create Model*/}
      <Dialog
        header={() => (modelstatus == "create" ? "Create" : "Update")}
        visible={modelShow}
        style={{ width: "450px" }}
        onHide={() => {
          SetModelShow(false);
        }}
        footer={footerContent}
      >
        <form
          onSubmit={
            modelstatus == "create"
              ? handleSubmit(onSubmit)
              : handleSubmit(HandelUpdate)
          }
          className="p-fluid"
          method="POST"
        >
          <div className="field mt-5">
            <label
              htmlFor="name"
              className={classNames({ "p-error": errors.name })}
            >
              Name<span className="text-red-500">*</span>
            </label>
            <span className="p-float-label">
              <Controller
                name="name"
                control={control}
                placeholder="brand name"
                rules={{ required: "Name is required." }}
                render={({ field, fieldState }) => (
                  <InputText
                    id={field.name}
                    {...field}
                    className={
                      classNames({
                        "p-invalid": fieldState.invalid,
                      }) + ` h-11 w-full block`
                    }
                    placeholder="Name"
                  />
                )}
              />
            </span>
            {getFormErrorMessage("name")}
          </div>

          <div className="field mt-2">
            <Button type="submit" label="Submit" className="mt-2" />
          </div>
        </form>
      </Dialog>
      {/* Create Model End*/}
    </AuthenticatedLayout>
  );
}
