import React, { useEffect, useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useDispatch, useSelector } from "react-redux";

import {
  useActivitiesMaster,
  useWorkCategoriesMaster,
} from "../../../hooks/masterHook/useMaster";
import { useManageTask } from "../../../hooks/useProjects";
import { cacheData, getCachedData } from "../../../slices/apiDataManager";
import { refreshData } from "../../../slices/localVariablesSlice";
import showToast from "../../../services/toastService";

const taskSchema = z
  .object({
    activityID: z.string().min(1, "Activity is required"),
    workCategoryId: z.string().min(1, "Work Category is required"),
    plannedWork: z.number().min(1, "Planned Work must be greater than 0"),
    completedWork: z.number().min(0, "Completed Work must be ≥ 0"),
    comment: z.string(),
  })
  .refine((data) => data.completedWork <= data.plannedWork, {
    message: "Completed Work cannot be greater than Planned Work",
    path: ["completedWork"],
  });

const EditActivityModal = ({
  workItem,
  workArea,
  building,
  floor,
  onClose,
} ) =>
{
  
  const { activities, loading: loadingActivities } = useActivitiesMaster();
  const { categories, loading: loadingCategories } = useWorkCategoriesMaster();
  const [selectedActivity, setSelectedActivity] = useState(null);

  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
    setValue,
    getValues,
    watch,
  } = useForm({
    resolver: zodResolver(taskSchema),
    defaultValues: {
      activityID: "",
      workCategoryId: "",
      plannedWork: 0,
      completedWork: 0,
      comment: "",
    },
  });
const { mutate: UpdateTask, isPending } = useManageTask({
  onSuccessCallback: () => onClose?.()
});

  const activityID = watch("activityID");

  const sortedActivities = useMemo(
    () =>
      [...(activities || [])].sort((a, b) =>
        a.activityName?.localeCompare(b.activityName)
      ),
    [activities]
  );

  const sortedCategories = useMemo(
    () => [...(categories || [])].sort((a, b) => a.name?.localeCompare(b.name)),
    [categories]
  );

  useEffect(() => {
    reset({
      activityID: String(
        workItem?.workItem?.activityId || workItem?.activityId || ""
      ),
      workCategoryId: String(
        workItem?.workItem?.workCategoryId || workItem?.workCategoryId || ""
      ),
      plannedWork:
        workItem?.workItem?.plannedWork || workItem?.plannedWork || 0,
      completedWork:
        workItem?.workItem?.completedWork || workItem?.completedWork || 0,
      comment: workItem?.workItem?.description || workItem?.description || "",
    });
  }, [workItem, activities]);

  useEffect(() => {
    const selected = activities?.find((a) => a.id === activityID);
    setSelectedActivity(selected || null);
  }, [activityID, activities]);

  const onSubmitForm = (data) =>
  {
      const payload = {
      ...data,
      id: workItem?.workItem?.id ?? workItem?.id,
      buildingID: building?.id,
      floorId: floor?.id,
      workAreaId: workArea?.id,
    };
   UpdateTask([payload])
 }
  return (
    <form className="row g-2 p-2 p-md-1" onSubmit={handleSubmit(onSubmitForm)}>
      <div className="text-center mb-1">
        <h5 className="mb-1">Manage Task</h5>
      </div>

      <div className="row g-2">
        <div className="col-12 col-md-6">
          <label className="form-label">Select Building</label>
          <input
            className="form-control form-control-sm"
            value={building?.buildingName}
            disabled
          />
        </div>

        <div className="col-12 col-md-6">
          <label className="form-label">Select Floor</label>
          <input
            className="form-control form-control-sm"
            value={floor?.floorName}
            disabled
          />
        </div>
      </div>

      <div className="col-12">
        <label className="form-label">Select Work Area</label>
        <input
          className="form-control form-control-sm"
          value={workArea?.areaName}
          disabled
        />
      </div>

      <div className="col-12">
        <label className="form-label">Select Activity</label>
        <select
          {...register("activityID")}
          className="form-select form-select-sm"
        >
          <option disabled>Select Activity</option>
          {loadingActivities ? (
            <option>Loading...</option>
          ) : (
            sortedActivities.map((a) => (
              <option key={a.id} value={a.id}>
                {a.activityName}
              </option>
            ))
          )}
        </select>
        {errors.activityID && (
          <p className="danger-text">{errors.activityID.message}</p>
        )}
      </div>

      <div className="col-12">
        <label className="form-label">Select Work Category</label>
        <select
          {...register("workCategoryId")}
          className="form-select form-select-sm"
        >
          <option disabled>Select Category</option>
          {loadingCategories ? (
            <option>Loading...</option>
          ) : (
            sortedCategories.map((c) => (
              <option key={c.id} value={c.id}>
                {c.name}
              </option>
            ))
          )}
        </select>
        {errors.workCategoryId && (
          <p className="danger-text">{errors.workCategoryId.message}</p>
        )}
      </div>

      <div className="col-5">
        <label className="form-label">Planned Work</label>
        <input
          {...register("plannedWork", { valueAsNumber: true })}
          type="number"
          className="form-control form-control-sm"
        />
        {errors.plannedWork && (
          <p className="danger-text">{errors.plannedWork.message}</p>
        )}
      </div>

      <div className="col-5">
        <label className="form-label">Completed Work</label>
        <input
          {...register("completedWork", { valueAsNumber: true })}
          type="number"
          disabled={getValues("completedWork") > 0}
          className="form-control form-control-sm"
        />
        {errors.completedWork && (
          <p className="danger-text">{errors.completedWork.message}</p>
        )}
      </div>

      <div className="col-2">
        <label className="form-label">Unit</label>
        <input
          className="form-control form-control-sm"
          disabled
          value={selectedActivity?.unitOfMeasurement || ""}
        />
      </div>

      <div className="col-12">
        <label className="form-label">Comment</label>
        <textarea {...register("comment")} rows="2" className="form-control" />
        {errors.comment && (
          <div className="danger-text">{errors.comment.message}</div>
        )}
      </div>

      <div className="col-12 text-center">
        <button
          type="submit"
          className="btn btn-sm btn-primary me-2"
          disabled={isPending}
        >
          {isPending ? "Please Wait..." : "Edit Task"}
        </button>
        <button
          type="button"
          className="btn btn-sm btn-label-secondary"
          onClick={onClose}
          disabled={isPending}
        >
          Cancel
        </button>
      </div>
    </form>
  );
};

export default EditActivityModal;
