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

// Zod schema for form validation
const workAreaSchema = z.object( {
  id:z.string().nonempty("Floor is required"),
  
  buildingId: z.string().nonempty("Building is required"),
  floorId: z.string().nonempty("Floor is required"),
  areaName: z.string().nonempty( "Work Area Name is required" ).min( 3, "Name must be at least 3 characters long" ),
});

// Default form data
const defaultModel = {
  id: "0",
  areaName: "",
  floorId: "0",
};

const WorkAreaModel = ({ project, onSubmit, clearTrigger, onClearComplete, onClose }) => {
  const [selectedBuilding, setSelectedBuilding] = useState(null);
  const [ selectedFloor, setSelectedFloor ] = useState( null );
  const [selectdWorkArea,setWorkArea] = useState()

  const { register, handleSubmit, formState: { errors }, setValue, reset, watch } = useForm({
    resolver: zodResolver(workAreaSchema), // Use Zod resolver for validation
    defaultValues: defaultModel,
  });

  const floorId = watch( "floorId" );  // Watch the floorId for conditional rendering

  useEffect(() => {
    if (clearTrigger) {
      reset(defaultModel); // Reset form to initial state
      setSelectedBuilding(null);
      setSelectedFloor(null);
      onClearComplete();
    }
  }, [clearTrigger, onClearComplete, reset]);

  const handleWorkAreaChange = ( e ) =>
  {
    
    
    const { value } = e.target;

    if (value === "0") {
      setValue("id", "0");  // Create New Work Area
      setValue( "areaName", "" );
 
      setWorkArea(String(0))
    } else {
      const workArea = selectedFloor?.workAreas.find((b) => b.id === Number(value));
      if ( workArea )
      {
        setValue("id", String(workArea.id));  // Set id as a string
        setValue("areaName", workArea.areaName);
        setWorkArea(String(workArea.id))

      }
    }
  };

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

    if (floor) {
      setSelectedFloor(floor);
      setValue("floorId", floor.id);  // Update floorId
      setValue("id", "0");  // Reset Work Area ID for new area creation
      setValue("areaName", ""); // Reset Work Area Name when changing floor
    } else {
      setSelectedFloor(null);
      setValue("floorId", "0");
      setValue("id", "0"); // Reset Work Area ID
      setValue("areaName", ""); // Reset Work Area Name
    }
  };

  const handleBuildingChange = (e) => {
    const { value } = e.target;
    const building = project.buildings.find((b) => b.id === Number(value));
    setSelectedBuilding(building);
    setSelectedFloor(null); // Reset selected floor on building change
    reset(defaultModel); // Reset the form when a new building is selected
  };

  const onSubmitForm = ( data ) =>
  {
    console.log(data)
    let WorkArea = {
      id: data.id,
      areaName: data.areaName,
      floorId: data.floorId,
      buildingId:data.buildingId
    }
    onSubmit(WorkArea);  // Send the final data to the parent
  };

  const handleCancel = () => {
    reset(defaultModel); // Reset the form to initial state
    setSelectedFloor(null);
    setSelectedBuilding(null);
  };

  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 Work Area</h5>
            </div>
            <form className="row g-2" onSubmit={handleSubmit(onSubmitForm)}>
              {/* Building Selection */}
              <div className="col-6 col-md-6">
                <label className="form-label" htmlFor="buildingId">Select Building</label>
                <select
                  id="buildingId"
                  name="buildingId"
                  className="select2 form-select form-select-sm"
                  {...register("buildingId")}
                  onChange={handleBuildingChange}
                >
                  <option value="0">Select Building</option>
                  {project.buildings.map((building) => (
                    <option key={building.id} value={building.id}>
                      {building.name}
                    </option>
                  ))}
                </select>
                {errors.buildingId && <span>{errors.buildingId.message}</span>}
              </div>

              {/* Floor Selection */}
              {selectedBuilding && selectedBuilding.buildingId !== "0" && (
                <div className="col-6 col-md-6">
                  <label className="form-label" htmlFor="floorId">Select Floor</label>
                  <select
                    id="floorId"
                    name="floorId"
                    className="select2 form-select form-select-sm"
                    {...register("floorId")}
                    onChange={handleFloorChange}
                  >
                    <option value="0">Select Floor</option>
                    {selectedBuilding.floors.map((floor) => (
                      <option key={floor.id} value={floor.id}>
                        {floor.floorName}
                      </option>
                    ))}
                  </select>
                  {errors.floorId && <span>{errors.floorId.message}</span>}
                </div>
              )}

              {/* Work Area Selection or Creation */}
              {floorId !== "0" && (
                <>
                  <div className="col-12 col-md-12">
                    <label className="form-label" >Select Work Area</label>
                    <select
                      id="workAreaId"
                      name="workAreaId"
                      className="select2 form-select form-select-sm"
                      {...register("id")}
                      onChange={handleWorkAreaChange}
                    >
                      <option value="0">Create New Work Area</option>
                      {selectedFloor?.workAreas.map((workArea) => (
                        <option key={workArea.id} value={workArea.id}>
                          {workArea.areaName}
                        </option>
                      ))}
                    </select>
                    {errors.id && <span>{errors.id.message}</span>}
                  </div>

                  {/* Work Area Name Input */}
                  <div className="col-12 col-md-12">
                    <label className="form-label" htmlFor="areaName">
                      {watch("id") === "0" ? "Enter Work Area Name" : "Modify Work Area Name"}
                    </label>
                    <input
                      type="text"
                      id="areaName"
                      name="areaName"
                      className="form-control form-control-sm"
                      placeholder="Work Area"
                      {...register("areaName")}
                    />
                    {errors.areaName && <span className="danger-text">{errors.areaName.message}</span>}
                  </div>

                  {/* Submit and Cancel Buttons */}
                  <div className="col-12 text-center">
                    <button type="submit" className="btn btn-primary me-3">
                      {watch("id") === "0" ? "Add Work Area" : "Edit Work Area"}
                    </button>
                    <button type="button" className="btn btn-label-secondary" onClick={handleCancel} data-bs-dismiss="modal" aria-label="Close">
                      Cancel
                    </button>
                  </div>
                </>
              )}
            </form>
          </div>
        </div>
      </div>
    </div>
  );
};

export default WorkAreaModel;
