import { DataGrid, GridColDef, GridRenderCellParams } from "@mui/x-data-grid";
import { ruRU } from "@mui/x-data-grid/locales";
import { languageStore, snapshotStore } from "@shared";
import { useEffect, useState } from "react";
import { observer } from "mobx-react-lite";
import { DatabaseBackup, Trash2 } from "lucide-react";
import { CreateButton, DeleteModal, SnapshotRestore } from "@widgets";
import { Box, CircularProgress } from "@mui/material";

export const SnapshotListPage = observer(() => {
  const { snapshots, getSnapshots, deleteSnapshot, restoreSnapshot } =
    snapshotStore;

  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [rowId, setRowId] = useState<string | null>(null); // Lifted state
  const { language } = languageStore;
  const [isRestoreModalOpen, setIsRestoreModalOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    const fetchSnapshots = async () => {
      setIsLoading(true);
      await getSnapshots();
      setIsLoading(false);
    };
    fetchSnapshots();
  }, [language]);

  const columns: GridColDef[] = [
    {
      field: "name",
      headerName: "Название",
      flex: 1,
    },
    {
      field: "parent",
      headerName: "Родитель",
      flex: 1,
    },

    {
      field: "actions",
      headerName: "Действия",
      width: 300,
      headerAlign: "center",

      renderCell: (params: GridRenderCellParams) => {
        return (
          <div className="flex h-full gap-7 justify-center items-center">
            <button
              onClick={() => {
                setIsRestoreModalOpen(true);
                setRowId(params.row.id);
              }}
            >
              <DatabaseBackup size={20} className="text-blue-500" />
            </button>

            <button
              onClick={() => {
                setIsDeleteModalOpen(true);
                setRowId(params.row.id);
              }}
            >
              <Trash2 size={20} className="text-red-500" />
            </button>
          </div>
        );
      },
    },
  ];

  const rows = snapshots.map((snapshot) => ({
    id: snapshot.ID,
    name: snapshot.Name,
    parent: snapshots.find((s) => s.ID === snapshot.ParentID)?.Name,
  }));

  return (
    <>
      <div style={{ width: "100%" }}>
        <div className="flex justify-between items-center mb-10">
          <h1 className="text-2xl ">Снапшоты</h1>
          <CreateButton label="Создать снапшот" path="/snapshot/create" />
        </div>
        <DataGrid
          rows={rows}
          columns={columns}
          hideFooterPagination
          hideFooter
          loading={isLoading}
          localeText={ruRU.components.MuiDataGrid.defaultProps.localeText}
          slots={{
            noRowsOverlay: () => (
              <Box sx={{ mt: 5, textAlign: "center", color: "text.secondary" }}>
                {isLoading ? <CircularProgress size={20} /> : "Нет снапшотов"}
              </Box>
            ),
          }}
        />
      </div>

      <DeleteModal
        open={isDeleteModalOpen}
        onDelete={async () => {
          if (rowId) {
            await deleteSnapshot(rowId);
          }
          setIsDeleteModalOpen(false);
          setRowId(null);
        }}
        onCancel={() => {
          setIsDeleteModalOpen(false);
          setRowId(null);
        }}
      />

      <SnapshotRestore
        open={isRestoreModalOpen}
        loading={isLoading}
        onDelete={async () => {
          setIsLoading(true);
          if (rowId) {
            await restoreSnapshot(rowId);
          }
          setIsRestoreModalOpen(false);
          setRowId(null);
          setIsLoading(false);
        }}
        onCancel={() => {
          setIsRestoreModalOpen(false);
          setRowId(null);
        }}
      />
    </>
  );
});
