import { DataGrid, GridColDef, GridRenderCellParams } from "@mui/x-data-grid";
import { ruRU } from "@mui/x-data-grid/locales";
import {
  cityStore,
  languageStore,
  sightsStore,
  selectedCityStore,
} from "@shared";
import { useEffect, useState, useMemo } 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 { Box, CircularProgress } from "@mui/material";

export const SightListPage = observer(() => {
  const { sights, getSights, deleteListSight } = sightsStore;
  const { cities, getCities } = cityStore;
  const navigate = useNavigate();
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [isBulkDeleteModalOpen, setIsBulkDeleteModalOpen] = useState(false);
  const [rowId, setRowId] = useState<string | null>(null);
  const [ids, setIds] = useState<number[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const { language } = languageStore;

  useEffect(() => {
    const fetchSights = async () => {
      setIsLoading(true);
      await getCities(language);
      await getSights();

      setIsLoading(false);
    };
    fetchSights();
  }, [language]);

  const columns: GridColDef[] = [
    {
      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: "city_id",
      headerName: "Город",
      flex: 1,
      renderCell: (params: GridRenderCellParams) => {
        return (
          <div className="w-full h-full flex items-center">
            {params.value ? (
              cities[language].data.find((el) => el.id == params.value)?.name
            ) : (
              <Minus size={20} className="text-red-500" />
            )}
          </div>
        );
      },
    },
    {
      field: "actions",
      headerName: "Действия",
      align: "center",
      headerAlign: "center",
      sortable: false,

      renderCell: (params: GridRenderCellParams) => {
        return (
          <div className="flex h-full gap-7 justify-center items-center">
            <button onClick={() => navigate(`/sight/${params.row.id}/edit`)}>
              <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 filteredSights = useMemo(() => {
    const { selectedCityId } = selectedCityStore;
    if (!selectedCityId) {
      return sights;
    }
    return sights.filter((sight: any) => sight.city_id === selectedCityId);
  }, [sights, selectedCityStore.selectedCityId]);

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

  return (
    <>
      <LanguageSwitcher />

      <div className="w-full">
        <div className="flex justify-between items-center mb-10">
          <h1 className="text-2xl">Достопримечательности</h1>
          <CreateButton
            label="Создать достопримечательность"
            path="/sight/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}
          hideFooter
          checkboxSelection
          loading={isLoading}
          localeText={ruRU.components.MuiDataGrid.defaultProps.localeText}
          onRowSelectionModelChange={(newSelection) => {
            setIds(Array.from(newSelection.ids as unknown as number[]));
          }}
          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 deleteListSight(Number(rowId));
          }
          setIsDeleteModalOpen(false);
          setRowId(null);
        }}
        onCancel={() => {
          setIsDeleteModalOpen(false);
          setRowId(null);
        }}
      />

      <DeleteModal
        open={isBulkDeleteModalOpen}
        onDelete={async () => {
          await Promise.all(ids.map((id) => deleteListSight(id)));
          getSights();
          setIsBulkDeleteModalOpen(false);
          setIds([]);
        }}
        onCancel={() => {
          setIsBulkDeleteModalOpen(false);
        }}
      />
    </>
  );
});
