import React, { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import showToast from "../../../services/toastService";
import { useManageProjectInfra } from "../../../hooks/useProjects";
import { useSelector } from "react-redux";

const workAreaSchema = z.object({
  id: z.string().optional(),
  buildingId: z.string().min(1, "Building is required"),
  floorId: z.string().min(1, "Floor is required"),
  areaName: z.string().min(3, "Work Area Name must be at least 3 characters"),
});

const defaultModel = {
  id: "0",
  buildingId: "0",
  floorId: "0",
  areaName: "",
};

const WorkAreaModel = ({ project, onSubmit, onClose }) => {
  const [selectedBuilding, setSelectedBuilding] = useState(null);
  const [selectedFloor, setSelectedFloor] = useState(null);
 const selectedProject = useSelector((store)=>store.localVariables.projectId)
  const {
    register,
    handleSubmit,
    formState: { errors },
    setValue,
    reset,
    watch,
  } = useForm({
    resolver: zodResolver(workAreaSchema),
    defaultValues: defaultModel,
  });

  const watchBuildingId = watch("buildingId");
  const watchFloorId = watch("floorId");
  const watchWorkAreaId = watch("id");
  const { mutate: ManageWorkArea, isPending } = useManageProjectInfra({
    onSuccessCallback: (data, variables) => {
      showToast(
        watchWorkAreaId != "0"
          ? "Wrok Area updated Successfully"
          : "Work Area created Successfully",
        "success"
      );
      reset({ id: "0", buildingId: "0", areaName: "", floorId: "0" });
      // onClose?.();
    },
  });

  useEffect(() => {
    const building = project?.find((b) => b.id === watchBuildingId);
    setSelectedBuilding(building || null);

    if (building) {
      const floor = building.floors?.find((f) => f.id === watchFloorId);
      setSelectedFloor(floor || null);
      setValue("areaName", "");
    } else {
      setSelectedFloor(null);
      setValue("floorId", "0");
      setValue("areaName", "");
    }
  }, [watchBuildingId, watchFloorId]);

  const handleWrokAreaChange = (e) => {
    const workAreaId = e.target.value;
    setValue("id", workAreaId);
    const area = selectedFloor?.workAreas.find((w) => w.id === workAreaId);
    if (area) {
      setValue("areaName", area.areaName);
    } else {
      setValue("areaName", "");
    }
  };

  useEffect(() => {
    reset(defaultModel);
  }, []);

  const onSubmitForm = ( data ) =>
  {
    const payload = {
      id: data.id === "0" ? null : data.id,
      areaName: data.areaName,
      floorId: data.floorId,
      buildingId: data.buildingId,
    };
    let infraObject = [
      {
        building: null,
        floor: null,
        workArea: payload,
      },
    ];

    ManageWorkArea({ infraObject, projectId: selectedProject });
  };

  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 Work Area</h5>
      </div>
        <div className="col-12 col-sm-6">
          <label className="form-label">Select Building</label>
          <select
            {...register("buildingId")}
            className="form-select form-select-sm"
          >
            <option value="0">Select Building</option>
            {project?.map((b) => (
              <option key={b.id} value={b.id}>
                {b.buildingName}
              </option>
            ))}
          </select>
          {errors.buildingId && (
            <p className="danger-text">{errors.buildingId.message}</p>
          )}
        </div>

        {watchBuildingId !== "0" && (
          <div className="col-12 col-sm-6">
            <label className="form-label">Select Floor</label>
            <select
              {...register("floorId")}
              className="form-select form-select-sm"
            >
              <option value="0">
                {selectedBuilding?.floor?.length > 0
                  ? "NO Floor Found"
                  : "Select Floor"}
              </option>

              {selectedBuilding?.floors?.map((f) => (
                <option key={f.id} value={f.id}>
                  {f.floorName}
                </option>
              ))}
            </select>
            {errors.floorId && (
              <p className="danger-text">{errors.floorId.message}</p>
            )}
          </div>
        )}
      {watchFloorId !== "0" && (
        <>
          <div className="col-12">
            <label className="form-label">Select Work Area</label>
            <select
              {...register("id")}
              className="form-select form-select-sm"
              onChange={handleWrokAreaChange}
            >
              <option value="0">Create New Work Area</option>
              {selectedFloor?.workAreas?.length > 0 &&
                selectedFloor?.workAreas?.map((w) => (
                  <option key={w.id} value={w.id}>
                    {w.areaName}
                  </option>
                ))}
            </select>
          </div>

          <div className="col-12">
            <label className="form-label">
              {watchWorkAreaId === "0"
                ? "Enter Work Area Name"
                : "Edit Work Area Name"}
            </label>
            <input
              type="text"
              className="form-control form-control-sm"
              placeholder="Work Area"
              {...register("areaName")}
            />
            {errors.areaName && (
              <p className="danger-text">{errors.areaName.message}</p>
            )}
          </div>

          <div className="col-12 text-center">
            <button type="submit" className="btn btn-sm btn-primary me-3" disabled={isPending}>
              {isPending ? "Please Wait.." : watchWorkAreaId === "0" ? "Add Work Area" : "Update Work Area"}
            </button>
            <button type="button" className="btn btn-sm btn-label-secondary" disabled={isPending} onClick={onClose}>
              Cancel
            </button>
          </div>
        </>
      )}
    </form>
  );
};

export default WorkAreaModel;
