import { Button, Modal, Spin } from "antd";
import { useState } from "react";
import { useGetPointsToMergeCount, useMergePointsToDb } from "../../api.js";
import { CheckCircleOutlined, InfoCircleOutlined, LoadingOutlined } from "@ant-design/icons";
import { useMode } from "../../stores/useMode.js";

export const MergePointsModal = ({isOpened, onClose}) => {
  const {setImportMode} = useMode();
  const [isLoading, setIsLoading] = useState(false);
  const { data: filteredCount, isInitialLoading: isFilteredLoading } =
    useGetPointsToMergeCount();
  const [isSuccess, setIsSuccess] = useState(false);
  const {mutateAsync: mergePoints} = useMergePointsToDb();

  const onConfirm = async () => {
    setIsLoading(true);

    try {
      await mergePoints();
      setIsSuccess(true);
    } catch (e) {
      //
    } finally {
      setIsLoading(false);
    }
  }

  const getFooter = () => {
    if (isSuccess) return [
      <Button
        key="ok-button"
        type="primary"
        onClick={() => {
          onClose();
          setImportMode(false);
        }}
        disabled={isLoading}
      >
        Хорошо
      </Button>,
    ];
    return [
      <Button
        key="close-button"
        type="default"
        onClick={onClose}
      >
        Назад
      </Button>,
      <Button
        key="ok-button"
        type="primary"
        onClick={() => onConfirm()}
        disabled={isLoading}
      >
        Подтвердить
      </Button>,
    ]
  }

  const getContent = () => {
    if (isFilteredLoading) return <Spin />;
    if (isLoading) return (
      <div className="flex flex-col justify-center gap-2 items-center">
        <Spin indicator={<LoadingOutlined style={{ fontSize: 32}} spin />} />
         Добавляем точки...
      </div>
    );
    if (isSuccess) return (
      <div className="flex items-center justify-center font-bold gap-2">
        <CheckCircleOutlined style={{ fontSize: 24, color: "#52C41A" }} />
        Добавлено {filteredCount} новых точек
      </div>
    );
    return (
      <div className="flex flex-row gap-4">
        <InfoCircleOutlined style={{ fontSize: 24, color: "#FFC53D" }} />
        <div className="flex flex-col gap-2">
          <p className="font-bold mb-0">Подтвердите добавление</p>
          <p>В базу данных будет добавлено {filteredCount} новых точек.</p>
        </div>
      </div>
    );
  }

  return (
    <Modal
      open={isOpened}
      title="Добавить в базу"
      onCancel={onClose}
      width={400}
      footer={getFooter()}
    >
      {getContent()}
    </Modal>
  );
}