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

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 defaultModel = {
  id: "0",
  floorName: "",
  buildingId: "0",
};

const FloorModel = ({
  project,
  onClose,
  onSubmit,
  clearTrigger,
  onClearComplete,
}) => {
  const [formData, setFormData] = useState(defaultModel);
  const [selectedBuilding, setSelectedBuilding] = useState({});
  const [buildings, setBuildings] = useState(project?.buildings || []);

  const {
    register,
    handleSubmit,
    setValue,
    reset,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(floorSchema),
    defaultValues: defaultModel,
  });

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

  const handleBuildigChange = (e) => {
    const buildingId = e.target.value;
    const building = buildings.find((b) => b.id === String(buildingId));

    if (building) {
      setSelectedBuilding(building);
      setFormData({
        id: "",
        floorName: "",
        buildingId: building.id,
      });
      setValue("buildingId", building.id, { shouldValidate: true }); // ✅ trigger validation
      setValue("id", "0");
    } else {
      setSelectedBuilding({});
      setFormData({
        id: "",
        floorName: "",
        buildingId: "0",
      });
      setValue("buildingId", "0", { shouldValidate: true }); // ✅ trigger validation
    }
  };

  const handleFloorChange = (e) => {
    const id = e.target.value;
    const floor = selectedBuilding.floors?.find((b) => b.id === String(id));

    if (floor) {
      setFormData({
        id: floor.id,
        floorName: floor.floorName,
        buildingId: selectedBuilding.id,
      });
      setValue("floorName", floor.floorName);
    } else {
      setFormData({
        id: "0",
        floorName: "",
        buildingId: selectedBuilding.id,
      });
      setValue("floorName", "");
    }
  };

  const onFormSubmit = (data) => {
    if (data.id === "0") {
      data.id = null;
    }

    onSubmit(data);
    reset({ floorName: "" });

    if (data.id !== null) {
      showToast("Floor updated successfully.", "success");
    } else {
      showToast("Floor created successfully.", "success");
    }
  };

  return (
    <div className="modal-dialog modal-lg modal-simple modal-edit-user">
      <div className="modal-content">
        <div className="modal-body">
          <div className="row">
            <button
              type="button"
              className="btn-close"
              aria-label="Close"
              onClick={onClose}
            />
            <div className="text-center mb-1">
              <h5 className="mb-1">Manage Floors - {project.name}</h5>
            </div>
            <form className="row g-2" onSubmit={handleSubmit(onFormSubmit)}>
              <div className="col-12 col-md-12">
                <label className="form-label" htmlFor="buildingId">
                  Select Building
                </label>
                <select
                  id="buildingId"
                  className="select2 form-select form-select-sm"
                  aria-label="Select Building"
                  {...register("buildingId")}
                  onChange={handleBuildigChange}
                >
                  <option value="0">Select Building</option>
                  {buildings?.length > 0 &&
                    buildings
                      .filter((building) => building?.name)
                      .sort((a, b) =>
                        (a.name || "")?.localeCompare(b.name || "")
                      )
                      .map((building) => (
                        <option key={building.id} value={building.id}>
                          {building.name}
                        </option>
                      ))}
                  {buildings?.length === 0 && (
                    <option disabled>No buildings found</option>
                  )}
                </select>
                {errors.buildingId && (
                  <p className="text-danger">{errors.buildingId.message}</p>
                )}
              </div>

              {formData.buildingId !== "0" && (
                <>
                  <div className="col-12 col-md-12">
                    <label className="form-label">Select Floor</label>
                    <select
                      id="id"
                      className="select2 form-select form-select-sm"
                      aria-label="Select Floor"
                      {...register("id")}
                      onChange={handleFloorChange}
                    >
                      <option value="0">Add New Floor</option>
                      {selectedBuilding?.floors?.length > 0 &&
                        [...selectedBuilding.floors]
                          .filter((floor) => floor?.floorName)
                          .sort((a, b) =>
                            (a.floorName || "")?.localeCompare(
                              b.floorName || ""
                            )
                          )
                          .map((floor) => (
                            <option key={floor.id} value={floor.id}>
                              {floor.floorName}
                            </option>
                          ))}
                      {selectedBuilding?.floors?.length === 0 && (
                        <option disabled>No floors found</option>
                      )}
                    </select>
                    {errors.id && (
                      <p className="text-danger">{errors.id.message}</p>
                    )}
                  </div>

                  <div className="col-12 col-md-12">
                    <label className="form-label">
                      {formData.id !== "0" ? "Modify " : "Enter "} Floor Name
                    </label>
                    <input
                      type="text"
                      id="floorName"
                      className="form-control form-control-sm me-2"
                      placeholder="Floor Name"
                      {...register("floorName")}
                    />
                    {errors.floorName && (
                      <p className="text-danger">
                        {errors.floorName.message}
                      </p>
                    )}
                  </div>
                </>
              )}

              <div className="col-12 text-center">
                <button type="submit" className="btn btn-sm btn-primary me-3">
                  {formData.id !== "0" && formData.id !== ""
                    ? "Edit Floor"
                    : "Add Floor"}
                </button>
                <button
                  type="button"
                  className="btn btn-sm btn-label-secondary"
                  data-bs-dismiss="modal"
                  aria-label="Close"
                  onClick={onClose}
                >
                  Cancel
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
};

export default FloorModel;
