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

// Zod validation schema
const floorSchema = z.object({
  buildingId: z.string().min(1, "Building is required"),
  id: z.string().min(1, "Floor is required").optional(),
  floorName: z.string().min(1, "Floor Name is required"),
});

// Default model
const defaultModel = {
  id: "0",
  floorName: "",
  buildingId: "0",
};

const FloorModel = ({
  project,
  onClose,
  onSubmit,
  clearTrigger,
  onClearComplete,
}) => {
  const [formData, setFormData] = useState(defaultModel);
  const [selectedBuilding, setSelectedBuilding] = useState({});
  
  // Initialize the form with React Hook Form
  const {
    register,
    handleSubmit,
    setValue,
    reset,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(floorSchema),
    defaultValues: defaultModel,
  });

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

  // Handle building selection change
  const handleBuildigChange = (e) => {
    const buildingId = e.target.value;
    const building = project.buildings.find((b) => b.id === Number(buildingId));
    if (building) {
      setSelectedBuilding(building);
      setFormData({
        id: "",
        floorName: "",
        buildingId: building.id,
 
      });
      setValue("buildingId", building.id); // Set value for validation
      setValue("id", "0"); // Reset floorId when changing building
    } else {
      setSelectedBuilding({});
      setFormData({
        id: "",
        floorName: "",
        buildingId: "0",

      });
      setValue("buildingId", "0");
    }
  };

  // Handle floor selection change
  const handleFloorChange = (e) => {
    const id = e.target.value;
    const floor = selectedBuilding.floors.find((b) => b.id === Number(id));
    if (floor) {
      setFormData({
        id: floor.id,
        floorName: floor.floorName,
        buildingId: selectedBuilding.id,
      
      });
      setValue("floorName", floor.floorName); // Set floor name for form
    } else {
      setFormData({
        id: "0",
        floorName: "",
        buildingId: selectedBuilding.id,
    
      });
      setValue("floorName", "");
    }
  };

  // Handle form submission
  const onFormSubmit = (data) => {

    onSubmit(data);
  };

  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>
                  {project.buildings.map((building) => (
                    <option key={building.id} value={building.id}>
                      {building.name}
                    </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?.map((floor) => (
                      <option key={floor.id} value={floor.id}>
                        {floor.floorName}
                      </option>
                    ))}
                  </select>
                  {errors.id && (
                    <p className="text-danger">{errors.id.message}</p>
                  )}
                </div>
              )}

              {formData.buildingId !== "0" && (
                <div className="col-12 col-md-12">
                  <label className="form-label" htmlFor="floorName">
                    {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-primary me-3">
                  {formData.id !== "0" && formData.id !== ""
                    ? "Edit Floor"
                    : "Add Floor"}
                </button>
                <button
                  type="button"
                  className="btn btn-label-secondary"
                  onClick={onClose}
                >
                  Cancel
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
};

export default FloorModel;
