import { DataGrid, GridColDef, GridRenderCellParams } from "@mui/x-data-grid";
import { ruRU } from "@mui/x-data-grid/locales";
import { authStore, languageStore, snapshotStore, SearchInput } from "@shared";
import { useEffect, useState, useMemo } 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 canWriteDevices = authStore.canWrite("devices");
  const canCreateSnapshot = authStore.hasRole("snapshot_create") && canWriteDevices;
  const canManageSnapshots = authStore.canWrite("snapshot") && canWriteDevices;

  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [rowId, setRowId] = useState<string | null>(null);
  const { language } = languageStore;
  const [isRestoreModalOpen, setIsRestoreModalOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [paginationModel, setPaginationModel] = useState({
    page: 0,
    pageSize: 50,
  });

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

  const formatCreationTime = (isoString: string | undefined) => {
    if (!isoString) return "";
    const [datePart, timePartWithMs] = isoString.split("T");
    if (!datePart || !timePartWithMs) return isoString;
    const timePart = timePartWithMs.split(".")[0];
    return `${datePart} - ${timePart}`;
  };

  const columns: GridColDef[] = [
    {
      field: "name",
      headerName: "Название",
      flex: 1,
    },
    {
      field: "parent",
      headerName: "Родитель",
      flex: 1,
    },
    {
      field: "created_at",
      headerName: "Дата создания",
      flex: 1,
      renderCell: (params: GridRenderCellParams) => {
        return <div>{params.value ? params.value : "-"}</div>;
      },
    },
    ...(canManageSnapshots ? [{
      field: "actions",
      headerName: "Действия",
      width: 300,
      headerAlign: "center" as const,
      sortable: false,
      renderCell: (params: GridRenderCellParams) => (
        <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 = useMemo(() => {
    const query = searchQuery.trim().toLowerCase();
    return snapshots
      .filter(
        (snapshot) =>
          !query ||
          (snapshot.Name ?? "").toLowerCase().includes(query) ||
          (snapshots.find((s) => s.ID === snapshot.ParentID)?.Name ?? "").toLowerCase().includes(query)
      )
      .map((snapshot) => ({
        id: snapshot.ID,
        name: snapshot.Name,
        parent: snapshots.find((s) => s.ID === snapshot.ParentID)?.Name,
        created_at: formatCreationTime(snapshot.CreationTime),
      }));
  }, [snapshots, searchQuery]);

  return (
    <>
      <div style={{ width: "100%" }}>
        <div className="flex justify-between items-center mb-10">
          <h1 className="text-2xl ">Экспорт Медиа</h1>

          {canCreateSnapshot && (
            <CreateButton label="Создать экспорт медиа" path="/snapshot/create" />
          )}
        </div>
        <SearchInput value={searchQuery} onChange={setSearchQuery} />

        <DataGrid
          rows={rows}
          columns={columns}
          loading={isLoading}
          paginationModel={paginationModel}
          onPaginationModelChange={setPaginationModel}
          pageSizeOptions={[50]}
          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);
        }}
      />
    </>
  );
});
