import React 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 { ConfirmPopup, confirmPopup } from "primereact/confirmpopup";
import { useState } from "react";
import { useForm, Controller, useFieldArray } from "react-hook-form";
import { useEffect } from "react";
import axios from "axios";
import { Toast } from "primereact/toast";
import { useRef } from "react";
import { authUser } from "@/Components/AuthProvider";
import { useContext } from "react";

import { InputTextarea } from "primereact/inputtextarea";
import { Dropdown } from "primereact/dropdown";

function ExpanceCategory({ auth }) {
  const { permission } = useContext(authUser);
  const [status, setStatus] = useState("create");
  const [visible, setVisible] = useState(false);

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

  const [id, setId] = useState();

  const [category, setCategory] = useState([]);

  const {
    register,
    control,
    handleSubmit,
    formState: { errors },
    setValue,
    watch,
    reset,
  } = useForm({
    category: "",
    description: "",
    type: "expense",
    status: "1",
  });

  useEffect(() => {
    axios.get(route("expance-category.view")).then((response) => {
      setCategory(response.data.category);
    });
  }, []);

  const TableHeader = () => {
    return (
      <div
        className={`w-100% flex ${permission.includes("expanse_category_create")
          ? "justify-between"
          : "justify-end"
          } `}
      >
        {permission.includes("expanse_category_create") && (
          <Button
            type="button"
            icon={<span className="pi pi-plus text-sm pr-1" />}
            label="Add"
            onClick={() => {
              setVisible(true);
              setStatus("create");
              formReset();
            }}
            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" />
        </span>
      </div>
    );
  };

  const getFormErrorMessageSingel = (name) => {
    return errors[name] ? (
      <small className="p-error ">{errors[name]["message"]}</small>
    ) : (
      ""
    );
  };
  // form Reset
  const formReset = () => {
    reset({
      category: "",
      description: "",
      type: "expense",
      status: "1",
    });
  };

  const footerContent = (
    <div className="grid  grid-cols-12 ">
      <div className="col-span-12">
        <Button
          label="Cancel"
          icon="pi pi-times"
          onClick={() => {
            setVisible(false);
            formReset();
          }}
          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>
  );

  // Data Store
  const DataStore = (data) => {
    axios.post(route("expance-category.store", data)).then((response) => {
      reset({
        category: "",
        description: "",
        type: "expense",
        status: "1",
      });
      setCategory(response.data.category);
      setVisible(false);

      toast.current.show({
        severity: "success",
        summary: response.data.success,
        detail: "Data Insterted ",
        life: 3000,
        className: "custom-toast-class",
      });
    });
  };

  // Prodcut Edit
  const handelEdit = async (data) => {
    setVisible(true);
    setStatus("update");
    setId(data.id);
    reset({
      category: data.category,
      description: data.description,
      type: data.type || "expense",
      status: data.status || "1",
    });
  };
  //  Product Update
  const DataUpdate = (data) => {
    axios
      .put(route("expance-category.update", id), data)
      .then((response) => {
        setCategory(response.data.category);
        toast.current.show({
          severity: "success",
          summary: response.data.success,
          detail: "Data Insterted ",
          life: 3000,
          className: "custom-toast-class",
        });
        setVisible(false);
        reset({
          category: "",
          description: "",
          type: "expense",
          status: "1",
        });
      });
  };

  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("expance-category.destroy", id))
          .then((response) => {
            setCategory(response.data.category);
            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,
        });
      },
    });
  };

  return (
    <AuthenticatedLayout
      user={auth.user}
      header={
        <>
          <h2 className="text-skin-header font-medium ">
            Category
          </h2>{" "}
          <p className="text-skin-sub-header font-semibold text-xs">
            {" "}
            Home - Category{" "}
          </p>
        </>
      }
      headerButton={<></>}
    >
      <Toast ref={toast} />
      {/* View Table*/}
      <div className="card">
        <DataTable
          className="defulattable"
          value={category}
          paginator
          showGridlines
          rows={10}
          dataKey="id"
          header={TableHeader}
          emptyMessage="No Category found."
        >
          <Column field="category" header="Category" />
          <Column field="type" header="Type" />
          <Column
            field="status"
            header="Status"
            body={(rowData) => (
              <span className={`px-2 py-1 rounded text-xs ${rowData.status === "1"
                ? "bg-green-100 text-green-800"
                : "bg-red-100 text-red-800"
                }`}>
                {rowData.status === "1" ? "Active" : "Inactive"}
              </span>
            )}
          />
          <Column field="description" header="Description" />

          <Column
            header="Action"
            body={(rowData) => (
              <>
                {" "}
                <ConfirmPopup />{" "}
                {permission.includes("expanse_category_edit") && (
                  <Button
                    icon="pi pi-pencil"
                    className="p-button-rounded p-button-success  px-3 py-2  w-10 h-10 font-medium"
                    onClick={() => {
                      handelEdit(rowData);
                    }}
                  />
                )}
                {permission.includes("expanse_category_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"
                  />
                }

              </>
            )}
            dataType="boolean"
            bodyClassName="text-center"
            style={{ minWidth: "8rem" }}
            className="space-x-1"
          />
        </DataTable>
      </div>
      {/* View Table End*/}

      <Dialog
        header={() => (status == "create" ? "Create" : "Update")}
        visible={visible}
        style={{ width: "25vw" }}
        onHide={() => {
          setVisible(false);
          formReset();
        }}
        footer={footerContent}
      >
        <form
          onSubmit={
            status == "create"
              ? handleSubmit(DataStore)
              : handleSubmit(DataUpdate)
          }
          ref={FormSubmit}
          onKeyPress={(event) => {
            if (event.key === "Enter") {
              event.preventDefault();
            }
          }}
        >
          <div className=" grid grid-cols-12 gap-6 mt-6 ">
            <div className="field col-span-12 md:col-span-12">
              <Controller
                name="category"
                control={control}
                rules={{
                  required: "Category field is required",
                }}
                render={({ field, fieldState }) => (
                  <span className="p-float-label">
                    <InputText
                      id={field.name}
                      {...field}
                      className={"w-full h-11"}
                    />
                    <label htmlFor="calendar">
                      Category Name
                    </label>
                  </span>
                )}
              />
              {getFormErrorMessageSingel("category")}
            </div>
            <div className="field col-span-12 md:col-span-12">
              <Controller
                name="type"
                control={control}
                rules={{
                  required: "Type field is required",
                }}
                render={({ field, fieldState }) => (
                  <span className="p-float-label">
                    <Dropdown
                      id={field.name}
                      {...field}
                      options={[
                        { label: "Income", value: "income" },
                        { label: "Expense", value: "expense" },
                        { label: "Other", value: "other" },
                      ]}
                      optionLabel="label"
                      optionValue="value"
                      className="w-full h-11"
                      placeholder="Select Type"
                    />
                    <label htmlFor={field.name}>
                      Category Type
                    </label>
                  </span>
                )}
              />
              {getFormErrorMessageSingel("type")}
            </div>
            <div className="field col-span-12 md:col-span-12">
              <Controller
                name="status"
                control={control}
                rules={{
                  required: "Status field is required",
                }}
                render={({ field, fieldState }) => (
                  <span className="p-float-label">
                    <Dropdown
                      id={field.name}
                      {...field}
                      options={[
                        { label: "Active", value: "1" },
                        { label: "Inactive", value: "0" },
                      ]}
                      optionLabel="label"
                      optionValue="value"
                      className="w-full h-11"
                      placeholder="Select Status"
                    />
                    <label htmlFor={field.name}>
                      Status
                    </label>
                  </span>
                )}
              />
              {getFormErrorMessageSingel("status")}
            </div>
            <div className="field col-span-12 md:col-span-12">
              <Controller
                name="description"
                control={control}
                render={({ field, fieldState }) => (
                  <span className="p-float-label">
                    <InputTextarea
                      id="textarea"
                      {...field}
                      rows={3}
                      className="w-full"
                    />
                    <label htmlFor="textarea">
                      Description
                    </label>
                  </span>
                )}
              />
              {getFormErrorMessageSingel("description")}
            </div>
          </div>
        </form>
      </Dialog>
    </AuthenticatedLayout>
  );
}

export default ExpanceCategory;
