import { Button, Modal, Spin } from "antd";
import { useState } from "react";
import { getImportStatus, importPoints } from "../../api.js";
import { LoadingStage } from "./LoadingStage.jsx";
import { ReportStage } from "./ReportStage.jsx";
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  LoadingOutlined
} from "@ant-design/icons";
import { useUpdateLayerCounter } from "../../stores/useUpdateLayerCounter.js";

export const PointsFileUploadModal = ({onClose, isOpened}) => {
  const [fileId, setFileId] = useState();
  const [report, setReport] = useState();
  const [isImporting, setIsImporting] = useState(false);
  const [isReportStage, setIsReportStage] = useState(false);
  const [isError, setIsError] = useState(false);
  const [importStatus, setImportStatus] = useState("Импортируем точки...")
  const { toggleUpdateCounter } = useUpdateLayerCounter();

  const onImportPoints = async () => {
    setIsImporting(true);
    try {
      await importPoints(fileId);
      const myInterval = setInterval(async () => {
        const response = await getImportStatus();
        setImportStatus(response.task_status);
        if (response.task_status === "Перерасчет ML завершен" || !isOpened) {
          setReport(response.data);
          setIsImporting(false);
          toggleUpdateCounter();
          clearInterval(myInterval);
        }
      }, 2000);
      toggleUpdateCounter();
    } catch (e) {
      setIsError(true);
      setIsImporting(false);
    }
  }

  const getFooter = () => {
    if (isError) return [
      <Button
        key="error-button"
        type="primary"
        onClick={onClose}
      >
        Закрыть
      </Button>
    ]
    if (isReportStage) return [
      <Button
        key="finish-button"
        type="primary"
        onClick={onClose}
      >
        Перейти к выбору
      </Button>
    ]
    if (report) return [
      <Button
        key="report-button"
        type="primary"
        onClick={() => setIsReportStage(true)}
      >
        Просмотреть отчет
      </Button>
    ]
    return [
      <Button
        key="ok-button"
        type="primary"
        onClick={() => onImportPoints()}
        disabled={!fileId || isImporting}
      >
        Импортировать
      </Button>,
    ]
  }
  const getContent = () => {
    if (isError) return (
      <div className="flex items-center justify-center font-bold gap-2">
        <CloseCircleOutlined style={{ fontSize: 24, color: "#FF4D4F" }} />
        При импорте точек произошла ошибка
      </div>
    )
    if (isImporting) return (
      <div className="flex flex-col justify-center gap-2 items-center">
        <Spin indicator={<LoadingOutlined style={{ fontSize: 64 }} spin />} />
        {importStatus}
      </div>
    );
    if (isReportStage) return <ReportStage report={report} />;
    if (report) return (
      <div className="flex items-center justify-center font-bold gap-2">
        <CheckCircleOutlined style={{ fontSize: 24, color: "#52C41A" }} />
        Точки успешно импортированы
      </div>
    );
    return <LoadingStage setFileId={setFileId} />;
  }

  return (
    <Modal
      open={isOpened}
      title="Импорт точек"
      onCancel={() => {if (!isImporting) onClose()}}
      width={400}
      footer={getFooter()}
    >
      {getContent()}
    </Modal>
  );
}