import SelectField from "../common/Forms/SelectField";
import { useJobStatus } from "../../hooks/masterHook/useMaster";
import { SpinnerLoader } from "../common/Loader";
import Error from "../common/Error";
import { z } from "zod";
import {
  AppFormController,
  AppFormProvider,
  useAppForm,
} from "../../hooks/appHooks/useAppForm";
import { zodResolver } from "@hookform/resolvers/zod";
import { useDispatch, useSelector } from "react-redux";
import { closePopup } from "../../slices/localVariablesSlice";
import { useUpdateServiceProjectJob } from "../../hooks/useServiceProject";

export const ChangeStatusSchema = z.object({
  statusId: z.string().min(1, { message: "Please select status" }),
});
const ChangeStatus = ({ statusId, projectId, jobId, popUpId }) => {
  const { data, isLoading, isError, error } = useJobStatus(statusId, projectId);
  const dispatch = useDispatch();
  const methods = useAppForm({
    resolver: zodResolver(ChangeStatusSchema),
    defaultValues: { statusId: "" },
  });

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

  const { mutate: UpdateStatus, isPending } = useUpdateServiceProjectJob(() => {
    // handleClose();
  });
  const onSubmit = (formData) => {
    const payload = 
     [
        {
          op: "replace",
          path: "/statusId",
          value: formData.statusId,
        },
      ];
    

    UpdateStatus({ id: jobId, payload });
  };

  const handleClose = () => {
    dispatch(closePopup(popUpId));
  };
  return (
    <AppFormProvider {...methods}>
      <form className="row text-start" onSubmit={handleSubmit(onSubmit)}>
        <div className="mb-2">
          <AppFormController
            name="statusId"
            control={control}
            render={({ field }) => (
              <SelectField
                label="Select Status"
                options={data ?? []}
                placeholder="Choose a Status"
                required
                labelKeyKey="name"
                valueKeyKey="id"
                value={field.value}
                onChange={field.onChange}
                isLoading={isLoading}
                className="m-0"
              />
            )}
          />

          {errors.statusId && (
            <small className="danger-text">{errors.statusId.message}</small>
          )}
        </div>

        <div className="d-flex flex-row justify-content-end gap-3">
          <button
            type="button"
            onClick={handleClose}
            className="btn btn-label-secondary btn-sm"
          >
            Cancel
          </button>

          <button type="submit" className="btn btn-primary btn-sm">
            {isPending ? "Please wait" : "Save"}
          </button>
        </div>
      </form>
    </AppFormProvider>
  );
};

export default ChangeStatus;
