import React, { useEffect } from "react";
import {
  useForm,
  FormProvider,
} from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import SelectMultiple from "../common/SelectMultiple";
import { useFeatures } from "../../hooks/useMasterRole";
import { EXPENSE_MANAGEMENT } from "../../utils/constants";
import { useCreateExpenseStatus, useUpdateExpenseStatus } from "../../hooks/masterHook/useMaster";
import { displayName } from "react-quill";
import { AppColorconfig } from "../../utils/appUtils";

const ExpenseStatusSchema = z.object({
  name: z.string().min(1, { message: "Name is required" }),
  displayName: z.string().min(1, { message: "Display Name is required" }),
  description: z.string().min(1, { message: "Description is required" }),
  permissionIds: z.array(z.string()).min(1, {
    message: "At least one permission is required",
  }),
  color: z
    .string()
    .regex(/^#([0-9A-F]{3}){1,2}$/i, { message: "Invalid hex color" }),
});

const ManageExpenseStatus = ({data, onClose }) => {
  const methods = useForm({
    resolver: zodResolver(ExpenseStatusSchema),
    defaultValues: {
      name: "",
      displayName: "",
      description: "",
      permissionIds: [],
      color: AppColorconfig.colors.primary,
    },
  });

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = methods;

  const { masterFeatures, loading } = useFeatures();

  const ExpenseFeature = masterFeatures?.find(
    (appfeature) => appfeature.id === EXPENSE_MANAGEMENT
  );
  const {mutate:CreateExpenseStatus,isPending:isPending} = useCreateExpenseStatus(()=>onClose?.())
  const {mutate:UpdateExpenseStatus,isPending:Updating} = useUpdateExpenseStatus(()=>onClose?.());



  const onSubmit = (payload) => {
  if(data){
        UpdateExpenseStatus({id:data.id,payload:{...payload,id:data.id}})
  }else{
     CreateExpenseStatus(payload)
  }
  };


  useEffect(()=>{
    if(data){
     reset({
        name:data.name ?? "",
        displayName:data.displayName ?? "",
        description:data.description ?? "",
        permissionIds:data.permissionIds ?? [],
        color:data.color ?? AppColorconfig.colors.primary
      })
    }
  },[data])
  return (
    <FormProvider {...methods}>
      {loading ? (
        <div>Loading...</div>
      ) : (
        <form className="row g-2" onSubmit={handleSubmit(onSubmit)}>
          <div className="col-12">
            <label className="form-label">Expense Status Name</label>
            <input
              type="text"
              {...register("name")}
              className={`form-control ${errors.name ? "is-invalid" : ""}`}
            />
            {errors.name && <p className="text-danger">{errors.name.message}</p>}
          </div>

          <div className="col-12">
            <label className="form-label">Status Display Name</label>
            <input
              type="text"
              {...register("displayName")}
              className={`form-control ${errors.displayName ? "is-invalid" : ""}`}
            />
            {errors.displayName && (
              <p className="text-danger">{errors.displayName.message}</p>
            )}
          </div>

          <div className="col-12">
            <SelectMultiple
              name="permissionIds"
              label="Select Permissions"
              options={ExpenseFeature?.featurePermissions || []}
              labelKey="name"
              valueKey="id"
              IsLoading={loading}
            />
            {errors.permissionIds && (
              <p className="text-danger">{errors.permissionIds.message}</p>
            )}
          </div>

          <div className="col-12">
            <label className="form-label">Select Color</label>
            <input
              type="color"
              className={`form-control form-control ${errors.color ? "is-invalid" : ""}`}
              {...register("color")}
            />
            {errors.color && (
              <p className="text-danger">{errors.color.message}</p>
            )}
          </div>

          <div className="col-12">
            <label className="form-label">Description</label>
            <textarea
              rows="3"
              {...register("description")}
              className={`form-control ${errors.description ? "is-invalid" : ""}`}
            />
            {errors.description && (
              <p className="text-danger">{errors.description.message}</p>
            )}
          </div>

          <div className="col-12 text-center">
            <button
              type="submit"
              className="btn btn-sm btn-primary me-3"
              disabled={isPending || Updating}
            >
              {isPending || Updating ? "Please Wait..." : Updating ? "Update" : "Submit"}
            </button>
            <button
              type="button"
              className="btn btn-sm btn-secondary"
              onClick={onClose}
              disabled={isPending || Updating}
            >
              Cancel
            </button>
          </div>
        </form>
      )}
    </FormProvider>
  );
};

export default ManageExpenseStatus;
