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

export const CityListPage = observer(() => {
  const { cities, getCities, deleteCity } = cityStore;
  const navigate = useNavigate();
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [rowId, setRowId] = useState<number | null>(null);
  const { language } = languageStore;

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

  const columns: GridColDef[] = [
    {
      field: "country",
      headerName: "Страна",
      width: 150,
    },
    {
      field: "name",
      headerName: "Название",
      flex: 1,
    },
    {
      field: "actions",
      headerName: "Действия",
      align: "center",
      headerAlign: "center",
      width: 200,

      renderCell: (params: GridRenderCellParams) => {
        return (
          <div className="flex h-full gap-7 justify-center items-center">
            <button onClick={() => navigate(`/city/${params.row.id}/edit`)}>
              <Pencil size={20} className="text-blue-500" />
            </button>
            <button onClick={() => navigate(`/city/${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 = cities[language].map((city) => ({
    id: city.id,
    name: city.name,
    country: city.country,
  }));

  return (
    <>
      <LanguageSwitcher />

      <div className="w-full">
        <div className="flex justify-between items-center mb-10">
          <h1 className="text-2xl">Города</h1>
          <CreateButton label="Создать город" path="/city/create" />
        </div>
        <DataGrid
          rows={rows}
          columns={columns}
          hideFooterPagination
          hideFooter
        />
      </div>

      <DeleteModal
        open={isDeleteModalOpen}
        onDelete={async () => {
          if (rowId) {
            deleteCity(rowId.toString(), language as keyof CashedCities);
          }
          setIsDeleteModalOpen(false);
          setRowId(null);
        }}
        onCancel={() => {
          setIsDeleteModalOpen(false);
          setRowId(null);
        }}
      />
    </>
  );
});
