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

// Schema
const floorSchema = z.object({
  buildingId: z
    .string()
    .refine((val) => val !== "0", { message: "Building is required" }),
  id: z.string().optional(),
  floorName: z.string().min(1, "Floor Name is required"),
});
const defaultValues = {
  id: "0",
  floorName: "",
  buildingId: "0",
};

const FloorModel = ({ project, onClose, onSubmit }) => {
  const selectedProject = useSelector(
    (store) => store.localVariables.projectId
  );
  const [selectedBuilding, setSelectedBuilding] = useState(null);

  const {
    register,
    handleSubmit,
    setValue,
    reset,
    watch,
    formState: { errors },
  } = useForm({
    defaultValues,
    resolver: zodResolver(floorSchema),
  });
  const watchId = watch("id");
  const watchBuildingId = watch("buildingId");
  const { mutate: ManageFloor, isPending } = useManageProjectInfra({
    onSuccessCallback: (data, variables) => {
      showToast(
        watchId != "0"
          ? "Floor updated Successfully"
          : "Floor created Successfully",
        "success"
      );
      reset({ id: "0", floorName: ""});
      // onClose?.();
    },
  });

  useEffect(() => {
    reset(defaultValues);
  }, []);
  useEffect(() => {
    const building = project?.find((b) => b.id === watchBuildingId);
    setSelectedBuilding(building || null);
  }, [watchBuildingId, project]);

  const handleBuildingChange = (e) => {
    const id = e.target.value;
    setValue("buildingId", id, { shouldValidate: true });
    setValue("id", "0");
    setValue("floorName", "");
  };

  const handleFloorChange = (e) => {
    const id = e.target.value;
    setValue("id", id);

    const floor = selectedBuilding?.floors?.find((f) => f.id === id);
    if (floor) {
      setValue("floorName", floor.floorName);
    } else {
      setValue("floorName", "");
    }
  };

  const onFormSubmit = (data) => {
    const isEdit = data.id !== "0";
    const payload = {
      ...data,
      id: isEdit ? data.id : null,
    };
    let infraObject = [
      {
        building: null,
        floor: payload,
        workArea: null,
      },
    ];

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

  return (
    <form className="row g-2" onSubmit={handleSubmit(onFormSubmit)}>
      <div className="text-center mb-1">
        <h5 className="mb-1">Manage Floor</h5>
      </div>
      <div className="col-12">
        <label className="form-label">Select Building</label>
        <select
          {...register("buildingId")}
          className="form-select form-select-sm"
          onChange={handleBuildingChange}
        >
          <option value="0">Select Building</option>
          {project?.length > 0 &&
            project
              .filter((b) => b.buildingName)
              .sort((a, b) => a.buildingName.localeCompare(b.buildingName))
              .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">
            <label className="form-label">Select Floor</label>
            <select
              {...register("id")}
              className="form-select form-select-sm"
              onChange={handleFloorChange}
            >
              <option value="0">Add New Floor</option>
              {selectedBuilding?.floors?.length > 0 &&
                selectedBuilding.floors
                  .filter((f) => f.floorName)
                  .sort((a, b) => a.floorName.localeCompare(b.floorName))
                  .map((f) => (
                    <option key={f.id} value={f.id}>
                      {f.floorName}
                    </option>
                  ))}
            </select>
          </div>

          <div className="col-12">
            <label className="form-label">
              {watchId !== "0" ? "Edit Floor Name" : "New Floor Name"}
            </label>
            <input
              {...register("floorName")}
              className="form-control form-control-sm"
              placeholder="Floor Name"
            />
            {errors.floorName && (
              <p className="danger-text">{errors.floorName.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"
            : watchId !== "0"
            ? "Edit Floor"
            : "Add Floor"}
        </button>
        <button
          type="button"
          className="btn btn-sm btn-label-secondary"
          disabled={isPending}
          onClick={onClose}
        >
          Cancel
        </button>
      </div>
    </form>
  );
};

export default FloorModel;
