import { DataGrid, GridColDef, GridRenderCellParams } from "@mui/x-data-grid";
import { languageStore, sightsStore } from "@shared";
import { useEffect, useState } from "react";
import { observer } from "mobx-react-lite";
import { Pencil, Trash2 } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { DeleteModal, LanguageSwitcher } from "@widgets";

export const SightListPage = observer(() => {
  const { sights, getSights, deleteListSight } = sightsStore;
  const navigate = useNavigate();
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [rowId, setRowId] = useState<string | null>(null); // Lifted state
  const { language } = languageStore;

  useEffect(() => {
    getSights();
  }, [language]);

  const columns: GridColDef[] = [
    {
      field: "name",
      headerName: "Имя",
      flex: 1,
    },
    {
      field: "city",
      headerName: "Город",
      flex: 1,
    },

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

      renderCell: (params: GridRenderCellParams) => {
        return (
          <div className="flex h-full gap-7 justify-center items-center">
            <button onClick={() => navigate(`/sight/${params.row.id}`)}>
              <Pencil size={20} className="text-blue-500" />
            </button>
            {/* <button onClick={() => navigate(`/sight/${params.row.id}`)}>
              <Eye size={20} className="text-green-500" />
            </button> */}
            <button
              onClick={() => {
                setIsDeleteModalOpen(true);
                setRowId(params.row.id);
              }}
            >
              <Trash2 size={20} className="text-red-500" />
            </button>
          </div>
        );
      },
    },
  ];

  const rows = sights.map((sight) => ({
    id: sight.id,
    name: sight.name,
    city: sight.city,
  }));

  return (
    <>
      <LanguageSwitcher />

      <div className="w-full">
        <DataGrid
          rows={rows}
          columns={columns}
          hideFooterPagination
          hideFooter
        />
      </div>

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