import { Button, TextField } from "@mui/material";
import { snapshotStore } from "@shared";
import { observer } from "mobx-react-lite";
import { ArrowLeft, Loader2, Save } from "lucide-react";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import { runInAction } from "mobx";

export const SnapshotCreatePage = observer(() => {
  const { createSnapshot, getSnapshotStatus, getStorageInfo, snapshotStatus } = snapshotStore;
  const navigate = useNavigate();
  const [name, setName] = useState("");
  const [isLoading, setIsLoading] = useState(false);

  return (
    <div className="w-full h-[400px] flex justify-center items-center">
      <div className="w-full h-full p-3 flex flex-col gap-10">
        <div className="flex justify-between items-center">
          <button
            className="flex items-center gap-2"
            onClick={() => navigate(-1)}
          >
            <ArrowLeft size={20} />
            Назад
          </button>
        </div>
        <h1 className="text-2xl font-bold">Создание экспорта медиа</h1>
        <div className="flex flex-col gap-10 w-full items-end">
          <TextField
            className="w-full"
            label="Название"
            required
            value={name}
            onChange={(e) => setName(e.target.value)}
          />

          <Button
            variant="contained"
            color="primary"
            className="w-min flex gap-2 items-center"
            startIcon={<Save size={20} />}
            onClick={async () => {
              try {
                setIsLoading(true);
                const id = await createSnapshot(name);

                await getSnapshotStatus(id);

                while (snapshotStore.snapshotStatus?.Status != "done") {
                  await new Promise((resolve) => setTimeout(resolve, 1000));
                  await getSnapshotStatus(id);
                }

                if (snapshotStore.snapshotStatus?.Status === "done") {
                  toast.success("Экспорт медиа успешно создан");

                  runInAction(() => {
                    snapshotStore.snapshotStatus = null;
                  });

                  await getStorageInfo();
                  navigate(-1);
                }
              } catch (error) {
                console.error(error);
                toast.error("Ошибка при создании экспорта медиа");
              } finally {
                setIsLoading(false);
              }
            }}
            disabled={isLoading || !name.trim()}
          >
            {isLoading ? (
              <div className="flex items-center gap-2">
                <Loader2 size={20} className="animate-spin" />
                <span>
                  {snapshotStatus?.Progress
                    ? (snapshotStatus.Progress * 100).toFixed(2)
                    : 0}
                  %
                </span>
              </div>
            ) : (
              "Сохранить"
            )}
          </Button>
        </div>
      </div>
    </div>
  );
});
