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

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

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

  const columns: GridColDef[] = [
    {
      field: "country",
      headerName: "Страна",
      width: 150,
      renderCell: (params: GridRenderCellParams) => {
        return (
          <div className="w-full h-full flex items-center">
            {params.value ? (
              params.value
            ) : (
              <Minus size={20} className="text-red-500" />
            )}
          </div>
        );
      },
    },
    {
      field: "name",
      headerName: "Название",
      flex: 1,
      renderCell: (params: GridRenderCellParams) => {
        return (
          <div className="w-full h-full flex items-center">
            {params.value ? (
              params.value
            ) : (
              <Minus size={20} className="text-red-500" />
            )}
          </div>
        );
      },
    },
    {
      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={(e) => {
                e.stopPropagation();
                setIsDeleteModalOpen(true);
                setRowId(params.row.id);
              }}
            >
              <Trash2 size={20} className="text-red-500" />
            </button>
          </div>
        );
      },
    },
  ];

  const rows = cities[language]?.data?.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>

        <div
          className="flex justify-end mb-5 duration-300"
          style={{ opacity: ids.length > 0 ? 1 : 0 }}
        >
          <button
            className="px-4 py-2 bg-red-500 text-white rounded flex gap-2 items-center"
            onClick={() => setIsBulkDeleteModalOpen(true)}
          >
            <Trash2 size={20} className="text-white" /> Удалить выбранные (
            {ids.length})
          </button>
        </div>

        <DataGrid
          rows={rows}
          columns={columns}
          hideFooterPagination
          hideFooter
          checkboxSelection
          onRowSelectionModelChange={(newSelection) => {
            setIds(Array.from(newSelection.ids as unknown as number[]));
          }}
        />
      </div>

      <DeleteModal
        open={isDeleteModalOpen}
        onDelete={async () => {
          if (rowId) {
            await deleteCity(rowId.toString());
            toast.success("Город успешно удален");
          }
          setIsDeleteModalOpen(false);
          setRowId(null);
        }}
        onCancel={() => {
          setIsDeleteModalOpen(false);
          setRowId(null);
        }}
      />

      <DeleteModal
        open={isBulkDeleteModalOpen}
        onDelete={async () => {
          await Promise.all(ids.map((id) => deleteCity(id.toString())));
          toast.success("Города успешно удалены");
          getCities(language);
          setIsBulkDeleteModalOpen(false);
          setIds([]);
        }}
        onCancel={() => {
          setIsBulkDeleteModalOpen(false);
        }}
      />
    </>
  );
});
