import React, { useEffect } from "react";
import Breadcrumb from "../common/Breadcrumb";
import Label from "../common/Label";
import { zodResolver } from "@hookform/resolvers/zod";
import { defaultJobValue, jobSchema } from "./ServiceProjectSchema";
import {
  useCreateServiceProjectJob,
  useJobTags,
  useServiceProjectJobDetails,
  useServiceProjects,
} from "../../hooks/useServiceProject";
import { ITEMS_PER_PAGE } from "../../utils/constants";
import DatePicker from "../common/DatePicker";
import PmsEmployeeInputTag from "../common/PmsEmployeeInputTag";
import TagInput from "../common/TagInput";
import { localToUtc } from "../../utils/appUtils";
import SelectField from "../common/Forms/SelectField";
import {
  AppFormController,
  AppFormProvider,
  useAppForm,
} from "../../hooks/appHooks/useAppForm";
import { useParams } from "react-router-dom";

const ManageJob = ({ Job }) => {
  const { projectId } = useParams();
  const methods = useAppForm({
    resolver: zodResolver(jobSchema),
    defaultValues: defaultJobValue,
  });
  const {
    register,
    control,
    watch,
    handleSubmit,
    reset,
    formState: { errors },
  } = methods;

  const {
    data: JobTags,
    isLoading: isTagLoading,
    isError: isTagError,
    error: tagError,
  } = useJobTags();
  const {
    data: JobData,
    isLoading: isJobLoading,
    isError: isJobError,
    error: jobError,
  } = useServiceProjectJobDetails(Job);
  const { mutate: CreateJob, isPending } = useCreateServiceProjectJob(() => {
    reset();
  });

  const onSubmit = (formData) => {
    formData.assignees = formData.assignees.map((emp) => ({
      employeeId: emp,
      isActive: true,
    }));

    formData.startDate = localToUtc(formData.startDate);
    formData.dueDate = localToUtc(formData.dueDate);
    formData.projectId = projectId;
    CreateJob(formData);
  };

  useEffect(() => {
    if (!JobData && !Job) {
      reset({
        ...defaultJobValue,
        projectId: projectId,
      });
      return;
    }

    if (!JobData || !Job) return;

    const assignedEmployees = (JobData.assignees || []).map((e) => e.id);

    reset({
      title: JobData.title ?? "",
      description: JobData.description ?? "",
      projectId: JobData.project?.id ?? projectId,
      assignees: assignedEmployees,
      startDate: JobData.startDate ?? null,
      dueDate: JobData.dueDate ?? null,
      tags: JobData.tags ?? [],
    });
  }, [JobData, Job, projectId]);

  return (
    <div className="container">
      <AppFormProvider {...methods}>
        <form className="row text-start" onSubmit={handleSubmit(onSubmit)}>
          <div className="col-12 col-md-12 mb-2 ">
            <Label required>Title</Label>
            <input
              type="text"
              {...register("title")}
              className="form-control form-control"
              placeholder="Enter Title"
            />
          </div>

          <div className="col-12 col-md-6 mb-2 mb-md-4">
            <Label required>Start Date</Label>
            <DatePicker
              name="startDate"
              control={control}
              placeholder="DD-MM-YYYY"
              className="w-full"
              size="md"
            />
          </div>
          <div className="col-12 col-md-6 mb-2 mb-md-4">
            <Label required>Due Date</Label>
            <DatePicker
              control={control}
              minDate={watch("startDate")}
              name="dueDate"
              className="w-full"
              size="md"
            />
          </div>
          <div className="col-12 col-md-12 mb-2 mb-md-4">
            <Label required>Select Employee</Label>
            <PmsEmployeeInputTag
              control={control}
              name="assignees"
              placeholder="Select employee"
            />
          </div>
          <div className="col-12 col-md-6 mb-2 mb-md-4">
            <TagInput
              options={JobTags?.data}
              name="tags"
              label="Tag"
              placeholder="Enter Tag"
              required
            />
          </div>
          <div className="col-12">
            <Label required>Description</Label>
            <textarea
              {...register("description")}
              className="form-control form-control-sm"
              rows={3}
            />
          </div>
          <div className="d-flex flex-row-reverse my-4">
            <button
              type="submit"
              className="btn btn-sm btn-primary"
              disabled={isPending}
            >
              {isPending ? "Please wait..." : "Submit"}
            </button>
          </div>
        </form>
      </AppFormProvider>
    </div>
  );
};

export default ManageJob;
