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



const currentDate = new Date().toISOString().split('T')[0];
const formatDate = (date) => {
  if (!date) {
    return currentDate; 
  }
  const d = new Date(date);
  if (isNaN(d.getTime())) {
    return currentDate;
  }
  return d.toISOString().split('T')[0];
};
const ManageProjectInfo = ( {project,handleSubmitForm, onClose} ) =>
{
 
  const [CurrentProject,setCurrentProject] = useState()
  const [ isloading, setLoading ] = useState( false )
  
  
  const projectSchema = z.object( {
    ...(project?.id ? { id: z.number().optional() } : {}),
    name: z.string().min( 1, {message: "Project Name is required"} ),
    contactPerson: z.string().min( 1, {message: "Contact Person Name is required"} ),
    projectAddress: z.string().min( 1, {message: "Address is required"} ).max(150, 'Address must not exceed 150 characters'),
    startDate: z.string().min( 1, {message: "Start Date is required"} ).default(currentDate),
    endDate: z.string().min( 1, {message: "End Date is required"} ).default(currentDate),
    projectStatusId: z
    .string()
    .min(1, { message: "Status is required" })
    .transform((val) => {
      const num = Number(val); 
      if (isNaN(num)) {
        throw new Error("Status must be a valid number");
      }
      return num;
    }),
  
  } )


 const {register, control, handleSubmit, formState: {errors}, reset, getValues} = useForm( {
   resolver: zodResolver( projectSchema ),
   defaultValues: {
     id:project?.id || "",
     name:project?.name || "",
     contactPerson:project?.contactPerson || "",
     projectAddress:project?.projectAddress || "",
     startDate: formatDate(project?.startDate )|| currentDate,
     endDate: formatDate(project?.endDate ) || currentDate,
     projectStatusId: String(project?.projectStatusId || "0"),
   
   }
 })
  
  useEffect( () =>
  {
    setCurrentProject(project)
    reset(
     project ? {
        id:project?.id || "",
        name:project?.name || "",
        contactPerson: project?.contactPerson || "",
        projectAddress: project?.projectAddress || "",
        startDate:formatDate(project?.startDate )|| "",
        endDate: formatDate(project?.endDate ) || "",
        projectStatusId:  String(project.projectStatusId) || "0" ,
   
      } :{}
    )
  },[project,reset,])

  

    const onSubmitForm = (updatedProject) => {
      setLoading( true )      
      handleSubmitForm( updatedProject )  
    };

  

  
  return (
    <div className="modal-dialog modal-lg modal-simple edit-project-modal" role="document">
      <div className="modal-content">
        <div className="modal-body">
          <button
            type="button"
            className="btn-close"
          
            onClick={onClose}
            aria-label="Close"
          ></button>
          <div className="text-center mb-2">
            <h5 className="mb-2">
              {project?.id ? "Edit Project" : "Create Project"}
            </h5>
          </div>
          <form className="row g-2" onSubmit={handleSubmit(onSubmitForm)}>
            <div className="col-12 col-md-12">
              <label className="form-label" htmlFor="name">
                Project Name
              </label>
              <input
                type="text"
                id="name"
                name="name"

                className="form-control"
                placeholder="Project Name"
                {...register("name")}
              />
               {errors.name && <div className="danger-text text-start" style={{fontSize:"12px"}}>{errors.name.message}</div>}
            </div>
            <div className="col-12 col-md-12">
              <label className="form-label" htmlFor="contactPerson">
                Contact Person
              </label>
              <input
                type="text"
                id="contactPerson"
                name="contactPerson"
                className="form-control"
                placeholder="Contact Person"
                {...register("contactPerson")}
              />
               {errors.contactPerson && <div className="danger-text text-start" style={{fontSize:"12px"}}>{errors.contactPerson.message}</div>}

            </div>

            <div className="col-12 col-md-6">
              <label className="form-label" htmlFor="startDate">
                Start Date
              </label>
              <input
                className="form-control form-control-sm"
                type="date"
              
                name="startDate"
                {...register("startDate")}
                id="startDate"
              />
               {errors.startDate && <div className="danger-text text-start" style={{fontSize:"12px"}}>{errors.startDate.message}</div>}

            </div>
            <div className="col-12 col-md-6">
              <label className="form-label" htmlFor="endDate">
                End Date
              </label>
              <input
                className="form-control form-control-sm"
                type="date"
              
                name="endDate"
                {...register("endDate")}
                id="endDate"
              />
               {errors.endDate && <div className="danger-text text-start" style={{fontSize:"12px"}}>{errors.endDate.message}</div>}

            </div>
            <div className="col-12 col-md-6">
              <label className="form-label" htmlFor="modalEditUserStatus">
                Status
              </label>
              <select
                id="modalEditUserStatus"
                name="modalEditUserStatus"
                className="select2 form-select"
                aria-label="Default select example"
                {...register("projectStatusId", {
                  required: "Status is required",
                  valueAsNumber: false
                })}
              >
                <option disabled>Status</option>
                <option value="1">Active</option>
                <option value="2">On Hold</option>

                <option value="3">Suspended</option>
                <option value="4">Inactive</option>

                <option value="5">Completed</option>
              </select>
              {errors.projectStatusId && <div className="danger-text text-start" style={{fontSize:"12px"}}>{errors.projectStatusId.message}</div>}

            </div>

            <div className="col-12 col-md-12">
              <label className="form-label" htmlFor="projectAddress">
                Project Address
              </label>
              <div className="input-group">
                <textarea
                  type="text"
                  id="projectAddress"
                  name="projectAddress"
                  className="form-control"
                  {...register( "projectAddress" )}
                  
                />
              </div>
              {errors.projectAddress && <div className="danger-text text-start" style={{fontSize:"12px"}}>{errors.projectAddress.message}</div>}

            </div>
            <div className="col-12 text-center">
              <button type="submit" className="btn btn-sm btn-primary me-3" >
                {isloading ? "Please Wait" : project?.id ? "Update":"Submit"}
              </button>
              <button  
                type="button"
                className="btn btn-sm btn-label-secondary"
                onClick={onClose}
                aria-label="Close"
              >
                Cancel
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default ManageProjectInfo;
