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";
import Label from "../../common/Label";
import { AppFormController, AppFormProvider } from "../../../hooks/appHooks/useAppForm";
import SelectField from "../../common/Forms/SelectField";

const workAreaSchema = z.object({
  id: z.string().optional(),
  buildingId: z.string().refine((val) => val !== "0", {
    message: "Building is required",
  }),
  floorId: z.string().refine((val) => val !== "0", { message: "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 methods = useForm({
    defaultValues: defaultModel,
    resolver: zodResolver(workAreaSchema),
  });

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

  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"
      );
      setValue("id", "0");
      setValue("areaName", "");
    },
  });

  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 (
    <AppFormProvider {...methods}>
      <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 text-start">
          <AppFormController
            name="buildingId"
            control={control}
            render={({ field }) => (
              <SelectField
                label="Select Building"
                options={project ?? []}
                placeholder="Select Building"
                required
                labelKey="buildingName"
                valueKey="id"
                value={field.value}
                onChange={field.onChange}
                className="m-0"
              />
            )}
          />

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


        {watchBuildingId !== "0" && (
          <div className="col-12 col-sm-6 text-start">
            <AppFormController
              name="floorId"
              control={control}
              render={({ field }) => (
                <SelectField
                  label="Select Floor"
                  options={selectedBuilding?.floors ?? []}
                  placeholder={
                    selectedBuilding?.floors?.length > 0
                      ? "Select Floor"
                      : "No Floor Found"
                  }
                  required
                  labelKey="floorName"
                  valueKey="id"
                  value={field.value}
                  onChange={(value) => {
                    field.onChange(value);
                    setValue("areaName", ""); // reset Work Area name when floor changes
                  }}
                  className="m-0"
                />
              )}
            />
            {errors.floorId && (
              <small className="danger-text">{errors.floorId.message}</small>
            )}
          </div>
        )}

        {watchFloorId !== "0" && (
          <>
            <div className="col-12 text-start">
              <AppFormController
                name="id"
                control={control}
                render={({ field }) => (
                  <SelectField
                    label="Select Work Area"
                    options={selectedFloor?.workAreas ?? []}
                    placeholder="Create New Work Area"
                    required={false}
                    labelKey="areaName"
                    valueKey="id"
                    value={field.value}
                    onChange={(value) => {
                      field.onChange(value);
                      handleWrokAreaChange({ target: { value } }); // preserve your existing handler
                    }}
                    className="m-0"
                  />
                )}
              />
            </div>

            <div className="col-12 text-start">
              <Label className="form-label" required>
                {watchWorkAreaId === "0"
                  ? "Enter Work Area Name"
                  : "Edit Work Area Name"}
              </Label>
              <input
                type="text"
                className="form-control"
                placeholder="Work Area"
                {...register("areaName")}
              />
              {errors.areaName && (
                <p className="danger-text">{errors.areaName.message}</p>
              )}
            </div>
          </>
        )}
        <div className="col-12 text-end mt-6 my-2">
          <button type="button" className="btn btn-sm btn-label-secondary me-3" disabled={isPending} onClick={onClose}>
            Cancel
          </button>
          <button type="submit" className="btn btn-sm btn-primary" disabled={isPending}>
            {isPending ? "Please Wait.." : watchWorkAreaId === "0" ? "Add Work Area" : "Update Work Area"}
          </button>

        </div>
      </form>
    </AppFormProvider>
  );
};

export default WorkAreaModel;
