import { DataGrid, GridColDef, GridRenderCellParams } from "@mui/x-data-grid";
import { ruRU } from "@mui/x-data-grid/locales";
import { authStore, countryStore, languageStore, SearchInput } from "@shared";
import { useEffect, useState, useMemo } from "react";
import { observer } from "mobx-react-lite";
import { Trash2, Minus } from "lucide-react";

import { CreateButton, DeleteModal, LanguageSwitcher } from "@widgets";
import { Box, CircularProgress } from "@mui/material";

export const CountryListPage = observer(() => {
  const { countries, getCountries, deleteCountry } = countryStore;

  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 canWriteCountries = authStore.canWrite("countries");
  const [searchQuery, setSearchQuery] = useState("");

  useEffect(() => {
    const fetchCountries = async () => {
      setIsLoading(true);
      await getCountries(language);
      setIsLoading(false);
    };
    fetchCountries();
  }, [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>
        );
      },
    },
    ...(authStore.canWrite("countries") ? [{
      field: "actions",
      headerName: "Действия",
      align: "center" as const,
      headerAlign: "center" as const,
      width: 200,
      sortable: false,
      renderCell: (params: GridRenderCellParams) => (
        <div className="flex h-full gap-7 justify-center items-center">
          <button
            onClick={(e) => {
              e.stopPropagation();
              setIsDeleteModalOpen(true);
              setRowId(params.row.code);
            }}
          >
            <Trash2 size={20} className="text-red-500" />
          </button>
        </div>
      ),
    }] : []),
  ];

  const rows = useMemo(() => {
    const query = searchQuery.trim().toLowerCase();
    return (countries[language]?.data ?? [])
      .filter((country) => !query || (country.name ?? "").toLowerCase().includes(query))
      .map((country) => ({
        id: country.code,
        code: country.code,
        name: country.name,
      }));
  }, [countries[language]?.data, searchQuery]);

  return (
    <>
      <LanguageSwitcher />

      <div className="w-full">
        <div className="flex justify-between items-center mb-10">
          <h1 className="text-2xl">Страны</h1>
          {canWriteCountries && (
            <CreateButton
              label="Добавить страну"
              path="/country/add"
            />
          )}
        </div>

        {canWriteCountries && 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}
          checkboxSelection={canWriteCountries}
          disableRowSelectionExcludeModel
          disableRowSelectionOnClick
          loading={isLoading}
          paginationModel={paginationModel}
          onPaginationModelChange={setPaginationModel}
          pageSizeOptions={[50]}
          localeText={ruRU.components.MuiDataGrid.defaultProps.localeText}
          onRowSelectionModelChange={
            canWriteCountries
              ? (newSelection: any) => {
                  if (Array.isArray(newSelection)) {
                    const selectedIds = newSelection.map(
                      (id: string | number) => Number(id)
                    );
                    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(
                      (id: string | number) => Number(id)
                    );
                    setIds(selectedIds);
                  } else {
                    setIds([]);
                  }
                }
              : undefined
          }
          slots={{
            noRowsOverlay: () => (
              <Box sx={{ mt: 5, textAlign: "center", color: "text.secondary" }}>
                {isLoading ? (
                  <CircularProgress size={20} />
                ) : (
                  "Нет стран"
                )}
              </Box>
            ),
          }}
        />
      </div>

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

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