import { format } from "date-fns";
import React, { useEffect, useState } from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import { useNavigate } from "react-router";

import { apiRequest } from "@api/request";

import { useNotification } from "@hooks/useNotification";

import BaseButton from "@components/Common/BaseButton/BaseButton";

import "./modalTicketToReport.scss";

const ModalTicketToReport = ({ show, onClose, additionalData }) => {
  const [date, setDate] = useState(new Date());
  const [inputValue, setInputValue] = useState(0);
  const [taskDescription, setTaskDescription] = useState("");

  const navigate = useNavigate();
  const { showNotification } = useNotification();

  useEffect(() => {
    if (additionalData.task.description) {
      const parser = new DOMParser();
      const doc = parser.parseFromString(
        additionalData.task.description,
        "text/html"
      );
      setTaskDescription(doc.body.textContent || "");
    }
  }, [additionalData.task.description]);

  useEffect(() => {
    const hoursSpent = additionalData.task.hours_spent;
    setInputValue(hoursSpent);
  }, [additionalData.task.hours_spent]);

  const handleSubmit = async () => {
    const formattedDate = format(date, "yyyy-MM-dd");

    apiRequest("https://back.itguild.info/api/reports/find-or-create", {
      method: "GET",
      params: {
        user_id: additionalData.user_id,
        created_at: formattedDate,
        project_id: additionalData.project_id,
        company_id: additionalData.company_id
      }
    })
      .then((res) => {
        apiRequest("https://back.itguild.info/api/reports/add-task-to-report", {
          method: "POST",
          data: {
            report_id: res[0].id,
            tasks: taskDescription,
            hours_spent: inputValue,
            minutes_spent: additionalData.task.minutes_spent
          }
        })
          .then(() => {
            showNotification({
              show: true,
              text: "Отчет успешно создан",
              type: "true"
            });
          })
          .catch((error) => {
            console.error("Error:", error);
          });
      })
      .catch((error) => {
        console.error("Error:", error);
      });
  };

  const toTheReport = async () => {
    const success = await handleSubmit();
    if (success) {
      navigate(
        `/profile/calendar/view/${additionalData.created_at}/${additionalData.user_id}`
      );
    }
  };

  const handleInputChange = (e) => {
    const value = Number(e.target.value);
    if (value !== 0) {
      setInputValue(value);
    }
  };

  return (
    <div
      className={`modal-report-backdrop ${show ? "show" : ""}`}
      onClick={onClose}
    >
      <div
        className="modal-report-content"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="modal-report-close" onClick={onClose}></div>
        <h2>Выгрузка в отчет</h2>
        <div className="modal-report-date-picker">
          <label htmlFor="date-picker">Дата отчета:</label>
          <DatePicker
            id="date-picker"
            className="datePicker"
            locale="ru"
            selected={date}
            onChange={(date) => setDate(date)}
            dateFormat="dd/MM/yyyy"
          />
        </div>
        <label className="modal-report-input-time">
          Время выполнения:
          <input
            type="number"
            value={inputValue}
            onChange={handleInputChange}
          />
        </label>

        <div className="modal-report__buttons">
          <BaseButton
            styles={"button-add add-person-btn "}
            onClick={handleSubmit}
          >
            Выгрузить в отчет
          </BaseButton>
          <BaseButton
            styles={`button-add add-person-btn ${show ? "" : "disable"}`}
            onClick={toTheReport}
          >
            Выгрузить и перейти в отчет
          </BaseButton>
        </div>
      </div>
    </div>
  );
};

export default ModalTicketToReport;
