import { DataGrid, GridColDef, GridRenderCellParams } from "@mui/x-data-grid";
import { ruRU } from "@mui/x-data-grid/locales";
import {
  authStore,
  cityStore,
  languageStore,
  sightsStore,
  selectedCityStore,
  SearchInput,
} 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 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 [paginationModel, setPaginationModel] = useState({
    page: 0,
    pageSize: 50,
  });
  const { language } = languageStore;
  const canReadCities = authStore.canRead("cities");
  const [searchQuery, setSearchQuery] = useState("");

  useEffect(() => {
    const fetchSights = async () => {
      setIsLoading(true);
      if (!authStore.me) {
        await authStore.getMeAction().catch(() => undefined);
      }
      if (authStore.canRead("cities")) {
        await cityStore.getCities(language);
      } else {
        await authStore.fetchMeCities().catch(() => undefined);
      }
      await getSights();
      setIsLoading(false);
    };
    fetchSights();
  }, [language, selectedCityStore.cityVersion]);

  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: "short_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) => {
        const lang = language as "ru" | "en" | "zh";
        const cityName = canReadCities
          ? cityStore.cities[lang]?.data.find((c) => c.id === params.value)?.name
          : authStore.meCities[lang]?.find((c) => c.city_id === params.value)?.name;
        return (
          <div className="w-full h-full flex items-center">
            {cityName ?? <Minus size={20} className="text-red-500" />}
          </div>
        );
      },
    },
    ...(authStore.canWrite("sights") ? [{
      field: "actions",
      headerName: "Действия",
      align: "center" as const,
      headerAlign: "center" as const,
      sortable: false,
      renderCell: (params: GridRenderCellParams) => (
        <div className="flex h-full gap-7 justify-center items-center">
          <button title="Редактировать" onClick={() => navigate(`/sight/${params.row.id}/edit`)}>
            <Pencil size={20} className="text-blue-500" />
          </button>
          <button
            title="Удалить"
            onClick={() => {
              setIsDeleteModalOpen(true);
              setRowId(params.row.id);
            }}
          >
            <Trash2 size={20} className="text-red-500" />
          </button>
        </div>
      ),
    }] : []),
  ];

  const { selectedCityId } = selectedCityStore;
  const filteredSights = useMemo(() => {
    if (!selectedCityId) {
      return [];
    }
    const allowedCityIds = canReadCities
      ? null
      : authStore.meCities["ru"].map((c) => c.city_id);

    return sights.filter((sight: any) => {
      if (allowedCityIds && !allowedCityIds.includes(sight.city_id)) {
        return false;
      }
      if (sight.city_id !== selectedCityId) {
        return false;
      }
      return true;
    });
  }, [sights, selectedCityId, canReadCities, authStore.meCities]);

  const query = searchQuery.trim().toLowerCase();
  const rows = filteredSights
    .filter((sight: any) => !query || (sight.name ?? "").toLowerCase().includes(query) || (sight.short_name ?? "").toLowerCase().includes(query))
    .map((sight: any) => ({
      id: sight.id,
      name: sight.name,
      short_name: sight.short_name,
      city_id: sight.city_id,
    }));

  const canWriteSights = authStore.canWrite("sights");

  return (
    <>
      <LanguageSwitcher />

      <div className="w-full">
        <div className="flex justify-between items-center mb-10">
          <h1 className="text-2xl">Достопримечательности</h1>
          {canWriteSights && (
            <CreateButton
              label="Создать достопримечательность"
              path="/sight/create"
            />
          )}
        </div>

        {canWriteSights && ids.length > 0 && (
          <div className="flex justify-end mb-5 duration-300">
            <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>
        )}

        {rows.length > 0 && (
          <SearchInput value={searchQuery} onChange={setSearchQuery} />
        )}

        <DataGrid
          rows={rows}
          columns={columns}
          onRowDoubleClick={(params) => canWriteSights && navigate(`/sight/${params.row.id}/edit`)}
          checkboxSelection={canWriteSights}
          disableRowSelectionExcludeModel
          disableRowSelectionOnClick
          loading={isLoading}
          paginationModel={paginationModel}
          onPaginationModelChange={setPaginationModel}
          pageSizeOptions={[50]}
          localeText={ruRU.components.MuiDataGrid.defaultProps.localeText}
          onRowSelectionModelChange={
            canWriteSights
              ? (newSelection: any) => {
                  if (Array.isArray(newSelection)) {
                    const selectedIds = newSelection.map(Number);
                    setIds(selectedIds);
                  } else if (
                    newSelection &&
                    typeof newSelection === "object" &&
                    "ids" in newSelection
                  ) {
                    const idsSet = newSelection.ids as Set<string | number>;
                    const selectedIds = Array.from(idsSet).map(Number);
                    setIds(selectedIds);
                  } else {
                    setIds([]);
                  }
                }
              : undefined
          }
          slots={{
            noRowsOverlay: () => (
              <Box sx={{ mt: 5, textAlign: "center", color: "text.secondary" }}>
                {isLoading ? (
                  <CircularProgress size={20} />
                ) : !selectedCityId ? (
                  "Выберите город"
                ) : (
                  "Нет достопримечательностей"
                )}
              </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);
        }}
      />
    </>
  );
});
