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

// Define Zod validation schema
const taskSchema = z.object({
  buildingID: z.string().min(1, "Building is required"),
  floorId: z.string().min(1, "Floor is required"),
  workAreaId: z.number().min(1, "Work Area is required"),
  activityID: z.number().min(1, "Activity is required"),
  plannedWork: z.number().min(1, "Planned Work must be greater than 0"),
  completedWork: z.number().optional(),
});

const defaultModel = {
  id: "0",
  workAreaId: 0,
  activityID: 0,
  plannedWork: 0,
  completedWork: 0,
};

const TaskModel = ({
  project,
  activities,
  onSubmit,
  clearTrigger,
  onClearComplete,onClose
}) => {
  const [formData, setFormData] = useState(defaultModel);
  const [selectedBuilding, setSelectedBuilding] = useState(null);
  const [selectedFloor, setSelectedFloor] = useState(null);
  const [selectedWorkArea, setSelectedWorkArea] = useState(null);
  const [selectedActivity, setSelectedActivity] = useState(null);

  
  const { register, handleSubmit, formState: { errors },reset } = useForm({
    resolver: zodResolver(taskSchema),
    defaultValues: formData,
  });

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

  // Handle input changes
  const handleChange = (e) => {
    const { name, value } = e.target;
    const activity = activities.find((b) => b.id === Number(value));
    setFormData({ ...formData, [name]: value });
  };

  const handleActivityChange = (e) => {
    const { value } = e.target;
    const activity = activities.find((b) => b.id === Number(value));

    setFormData({ ...formData, ["activityID"]: value });
    setSelectedActivity(activity);
  };

  const handleWorkAreaChange = (e) => {
    const { value } = e.target;
    const workArea = selectedFloor.workAreas.find((b) => b.id === Number(value));
    setSelectedWorkArea(workArea);
    setFormData({ ...formData, ["workAreaId"]: value });
  };

  const handleFloorChange = (e) => {
    const { value } = e.target;
    const floor = selectedBuilding.floors.find((b) => b.id === Number(value));
    setSelectedFloor(floor);
    setSelectedWorkArea(null);
    setSelectedActivity(null);
    setFormData(defaultModel);
  };

  const handleBuildingChange = (e) => {
    const { value } = e.target;
    const building = project.buildings.find((b) => b.id === Number(value));
    setSelectedBuilding(building);
    setSelectedFloor(null);
    setSelectedWorkArea(null);
    setSelectedActivity(null);
    setFormData(defaultModel);
  };

  const onSubmitForm = ( data ) =>
  {
    
    
    onSubmit( data ); 
    setSelectedActivity(null),
   selectedWorkArea(null)
    reset( {
      plannedWork: 0,
      completedWork:0
      
    })
  };

  useEffect( () =>
  {
    () =>{
      resetVlaue ()
    }
  },[])
  const resetVlaue = () =>
  {
    setSelectedBuilding( null )
    setSelectedFloor( null )
    setSelectedWorkArea( null )
    setSelectedActivity(null)
    reset( {
      plannedWork: 0,
      completedWork:0
    })
 }
  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 Task</h5>
            </div>
            <form className="row g-2" onSubmit={handleSubmit(onSubmitForm)}>
              {/* Select Building */}
              <div className="col-6 col-md-6">
                <label className="form-label" htmlFor="name">
                  Select Building
                </label>
                <select
                  id="buildingID"
                  name="buildingID"
                  className="select2 form-select form-select-sm"
                  aria-label="Default select example"
                  {...register("buildingID")}
                  onChange={(e) => handleBuildingChange(e)}
                >
                  <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="danger-text">{errors.buildingID.message}</p>}
              </div>

              {/* Select Floor */}
              {selectedBuilding && selectedBuilding.id !== "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"
                    aria-label="Default select example"
                    {...register("floorId")}
                    onChange={(e) => handleFloorChange(e)}
                  >
                    <option value="0">Select Floor</option>
                    {selectedBuilding.floors.map((floor) => (
                      <option key={floor.id} value={floor.id}>
                        {floor.floorName} - ({floor.workAreas.length} Work Areas)
                      </option>
                    ))}
                  </select>
                  {errors.floorId && <p  className="danger-text">{errors.floorId.message}</p>}
                </div>
              )}

              {/* Select Work Area */}
              {selectedFloor && (
                <div className="col-12 col-md-12">
                  <label className="form-label" htmlFor="workAreaId">
                    Select Work Area
                  </label>
                  <select
                    id="workAreaId"
                    name="workAreaId"
                    className="select2 form-select form-select-sm"
                    aria-label="Default select example"
                    {...register("workAreaId",{valueAsNumber:true})}
                    onChange={(e) => handleWorkAreaChange(e)}
                  >
                    <option value="0">Select Work Area</option>
                    {selectedFloor.workAreas.map((workArea) => (
                      <option key={workArea.id} value={workArea.id}>
                        {workArea.areaName}
                      </option>
                    ))}
                  </select>
                  {errors.workAreaId && <p  className="danger-text">{errors.workAreaId.message}</p>}
                </div>
              )}

              {/* Select Activity */}
              {selectedWorkArea && (
                <div className="col-12 col-md-12">
                  <label className="form-label" htmlFor="activityID">
                    Select Activity
                  </label>
                  <select
                    id="activityID"
                    name="activityID"
                    className="select2 form-select form-select-sm"
                    aria-label="Default select example"
                    {...register("activityID",{valueAsNumber:true})}
                    onChange={(e) => handleActivityChange(e)}
                  >
                    <option value="0">Select Activity</option>
                    {activities.map((activity) => (
                      <option key={activity.id} value={activity.id}>
                        {activity.activityName}
                      </option>
                    ))}
                  </select>
                  {errors.activityID && <p className="danger-text">{errors.activityID.message}</p>}
                </div>
              )}

              {/* Planned Work */}
              {selectedActivity && (
                <div className="col-5 col-md-5">
                  <label className="form-label" htmlFor="plannedWork">
                    {formData.id !== "0" ? "Modify " : "Enter "} Planned Work
                  </label>
                  <input
                    {...register("plannedWork", { valueAsNumber: true })}
                    type="number"
                    id="plannedWork"
                    name="plannedWork"
                    className="form-control form-control-sm me-2"
                    placeholder="Planned Work"
                  />
                  {errors.plannedWork && <p className="danger-text">{errors.plannedWork.message}</p>}
                </div>
              )}

              {/* Completed Work */}
              {selectedActivity && (
                <div className="col-5 col-md-5">
                  <label className="form-label" htmlFor="completedWork">
                    {formData.id !== "0" ? "Modify " : "Enter "} Completed Work
                  </label>
                  <input
                    {...register("completedWork", { valueAsNumber: true })}
                    type="number"
                    id="completedWork"
                    name="completedWork"
                    className="form-control form-control-sm me-2"
                    placeholder="Completed Work"
                  />
                  {errors.completedWork && <p className="danger-text">{errors.completedWork.message}</p>}
                </div>
              )}

              {/* Unit */}
              {selectedActivity && (
                <div className="col-2 col-md-2">
                  <label className="form-label" htmlFor="unit">
                    Unit
                  </label>
                  <input
                    type="text"
                    disabled
                    id="unit"
                    name="unit"
                    className="form-control form-control-sm me-2"
                    value={selectedActivity?.unitOfMeasurement || ""}
                  />
                </div>
              )}

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

export default TaskModel;
