import React, { useState } from "react";
import { formatDate } from "../../utils/dateUtils";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import showToast from "../../services/toastService";
import { TasksRepository } from "../../repositories/TaskRepository";

export const ReportTask = ({ report,closeModal,refetch }) => {
  const [ loading, setloading ] = useState( false );
  

  const schema = z.object({
    completedTask: z
      .number()
      .min(1, "Completed Work must be at least 1")
      .max(
        report?.plannedTask,
        `Completed Work cannot exceed ${report?.plannedTask}`
      )
      .int("Completed Work must be an integer")
      .positive("Completed Work must be a positive number")
      .optional(),
    comment: z.string().min(1, "Comment cannot be empty"),
  });
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(schema),
  });

  const onSubmit = async (data) => {
    try
    {
      setloading(true)
        const reportData = {
          ...data,
        id: report?.id,
        reportedDate: new Date().toISOString(),
        };
    
      
      let response = await TasksRepository.reportTsak( reportData )
      showToast( "succesfully", "success" )
      refetch()
      closeModal()
     
    } catch (error) {
      showToast("Somthing wrog", "error");
    }
  };
  const handleClose = () => {
    closeModal();  
  };

  return (


    <div className="modal-dialog modal-md modal-simple report-task-modal" role="document">
    <div className="modal-content">
      <div className="modal-body px-1">
        <button
          type="button"
          className="btn-close"
        
          onClick={handleClose}
          aria-label="Close"
        ></button>
       
    <div className="container  m-0">
      <div className="d-flex justify-content-between">
     
              <figure class="text-start p-0 m-0">
          <blockquote class="blockquote">
            <small>  Assigned Date : {formatDate(report?.assignmentDate)}</small>
                </blockquote>
                </figure>
        <figure class="text-end p-0 m-0">
          <blockquote class="blockquote">
            <small>Assigned By</small>
          </blockquote>
          <figcaption className="blockquote-footer mb-0">
            {/* <div className="d-flex avatar avatar-xs">
            <span className="avatar-initial rounded-circle bg-label-primary">
              {report?.assignedBy?.firstName.slice(0, 1)}
            </span> */}
            <cite title="Source Title m-0">{` ${report?.assignedBy.firstName} ${report?.assignedBy.lastName}`}</cite>
            {/* </div> */}
          </figcaption>
        </figure>
      </div>

      <div className="d-flex  p-0 m-0">
        <div className="flex-shrink-0 mt-1 mx-sm-0 px-2  mx-auto">
          <i class="bx bx-buildings"></i>
        </div>
        <p class="lead">{report?.workItem?.workArea?.floor?.building?.name}</p>
        <p class="lead ms-12">{report?.workItem?.workArea?.floor?.floorName}</p>
      </div>
      <dl class="row text-start ms-3">
        <dt class="col-sm-6">
          Work Area : {report?.workItem?.workArea?.areaName}
        </dt>
        <dd class="col-sm-6">
          <small> {report?.workItem?.activityMaster.activityName}</small>
        </dd>
      </dl>
      <dl class="row text-start ms-3">
        <dt class="col-sm-4">Team</dt>

        <dd class="col-sm-4 d-flex align-items-center avatar-group justify-content-start">
          {report?.teamMembers.map((member) => (
            <>
              <div
                data-bs-toggle="tooltip"
                data-bs-html="true"
                data-popup="tooltip-custom"
                data-bs-placement="top"
                title={`${member.firstName} ${member.lastName}`}
                className="avatar avatar-xs"
              >
                {/* <img src="..." alt="Avatar" class="rounded-circle pull-up" /> */}
                <span className="avatar-initial rounded-circle bg-label-primary">
                  {member?.firstName.slice(0, 1)}
                </span>
              </div>
            </>
          ))}
        </dd>
        <dt class="col-sm-4 text-start">Planned : {report?.plannedTask}</dt>
      </dl>
      <form onSubmit={handleSubmit(onSubmit)}>
        <div className="row p-0">
          <div className="col-4">
            <input
              {...register("completedTask", { valueAsNumber: true })}
              id="smallInput"
              className="form-control form-control-sm"
              type="number"
              placeholder="Completed Work"
            />
            {errors.completedTask && (
              <div className="text-danger">{errors.completedTask.message}</div>
            )}
          </div>
          <div className="col-8">
            <textarea
              {...register("comment")}
              className="form-control"
              id="exampleFormControlTextarea1"
              rows="1"
              placeholder="Enter comment"
            />
            {errors.comment && (
              <div className="text-danger">{errors.comment.message}</div>
            )}
          </div>
        </div>

        <div className="col-12 text-center my-2">
          <button type="submit" className="btn btn-sm btn-primary me-3">
            {loading ? "Please wait":"Submit Report"}
          </button>
          <button
            type="button"
            className="btn btn-sm btn-label-secondary"
            onClick={handleClose}
          >
            Cancel
          </button>
        </div>
      </form>
          </div>
        </div>
      </div>
      </div>
  );
};
