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";

export const SnapshotCreatePage = observer(() => {
  const { createSnapshot } = 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);
                await createSnapshot(name);
                setIsLoading(false);
                toast.success("Снапшот успешно создан");
                navigate(-1);
              } catch (error) {
                console.error(error);
                toast.error("Ошибка при создании снапшота");
              } finally {
                setIsLoading(false);
              }
            }}
            disabled={isLoading || !name.trim()}
          >
            {isLoading ? (
              <Loader2 size={20} className="animate-spin" />
            ) : (
              "Сохранить"
            )}
          </Button>
        </div>
      </div>
    </div>
  );
});
