import { DataGrid, GridColDef, GridRenderCellParams } from "@mui/x-data-grid";
import { ruRU } from "@mui/x-data-grid/locales";
import { carrierStore, languageStore, routeStore } from "@shared";
import { useEffect, useState } from "react";
import { observer } from "mobx-react-lite";
import { Map, 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 RouteListPage = observer(() => {
  const { routes, getRoutes, deleteRoute } = routeStore;
  const { carriers, getCarriers } = carrierStore;
  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 [isLoading, setIsLoading] = useState(false);
  const { language } = languageStore;

  useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);
      await getCarriers("ru");
      await getCarriers("en");
      await getCarriers("zh");
      await getRoutes();
      setIsLoading(false);
    };
    fetchData();
  }, [language]);

  const columns: GridColDef[] = [
    {
      field: "carrier_id",
      headerName: "Перевозчик",
      width: 250,
      renderCell: (params: GridRenderCellParams) => {
        return (
          <div className="w-full h-full flex items-center">
            {params.value ? (
              carriers[language].data.find(
                (carrier) => carrier.id == params.value
              )?.short_name
            ) : (
              <Minus size={20} className="text-red-500" />
            )}
          </div>
        );
      },
    },
    {
      field: "route_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: "route_number",
      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: "route_direction",
      headerName: "Направление",
      flex: 1,
      renderCell: (params: GridRenderCellParams) => {
        return (
          <p
            className={
              params.row.route_direction === "Прямой"
                ? "text-green-500"
                : "text-red-500"
            }
          >
            {params.row.route_direction}
          </p>
        );
      },
    },
    {
      field: "actions",
      headerName: "Действия",
      width: 250,
      align: "center",
      headerAlign: "center",
      sortable: false,
      renderCell: (params: GridRenderCellParams) => {
        return (
          <div className="flex h-full gap-7 justify-center items-center">
            <button onClick={() => navigate(`/route/${params.row.id}/edit`)}>
              <Pencil size={20} className="text-blue-500" />
            </button>
            <button onClick={() => navigate(`/route-preview/${params.row.id}`)}>
              <Map size={20} className="text-purple-500" />
            </button>

            <button
              onClick={() => {
                setIsDeleteModalOpen(true);
                setRowId(params.row.id);
              }}
            >
              <Trash2 size={20} className="text-red-500" />
            </button>
          </div>
        );
      },
    },
  ];

  const rows = routes.data.map((route) => ({
    id: route.id,
    carrier_id: route.carrier_id,
    route_number: route.route_number,
    route_direction: route.route_direction ? "Прямой" : "Обратный",
    route_name: route.route_name,
  }));

  return (
    <>
      <LanguageSwitcher />

      <div style={{ width: "100%" }}>
        <div className="flex justify-between items-center mb-10">
          <h1 className="text-2xl">Маршруты</h1>
          <CreateButton label="Создать маршрут" path="/route/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) {
            deleteRoute(rowId);
          }
          setIsDeleteModalOpen(false);
          setRowId(null);
        }}
        onCancel={() => {
          setIsDeleteModalOpen(false);
          setRowId(null);
        }}
      />

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