// @ts-nocheck
import React from "react";
import { useEffect, useState } from "react";
import { GridColDef, GridSelectionModel, GridToolbar } from "@mui/x-data-grid";
import { Box, Button, IconButton,Tooltip } from "@mui/material";
import BackspaceIcon from "@mui/icons-material/Backspace";
import { enqueueSnackbar } from "notistack";
import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined";

import DataGrid from "@kitUI/datagrid";

import { deleteTariffs, useTariffStore } from "@root/stores/tariffsStore";
import { SERVICE_LIST } from "@root/model/tariff";
import { findPrivilegeById } from "@root/stores/privilegesStore";

import axios from "axios";
import { authStore } from "@root/stores/auth";
import DeleteModal from "@root/pages/dashboard/Content/Tariffs/DeleteModal";
import EditModal from "./EditModal";
import { Tariff } from "@root/model/tariff";
import AutorenewIcon from "@mui/icons-material/Autorenew";

interface Props {
  selectedTariffs: GridSelectionModel;
  handleSelectionChange: (selectionModel: GridSelectionModel) => void;
  requestTariffs: () => Promise<void>;
}

export default function TariffsDG({
  selectedTariffs,
  handleSelectionChange,
  requestTariffs,
}: Props) {
  const tariffs = Object.values(useTariffStore().tariffs);
  const [deletedRows, setDeletedRows] = useState<string[]>([]);
  const [openDeleteModal, setOpenDeleteModal] = useState(false);
  const [changingTariff, setChangingTariff] = useState<Tariff | undefined>();
  const [tariffDelete, setTariffDelete] = useState(false);

  console.log(selectedTariffs);

  const closeDeleteModal = () => {
    setOpenDeleteModal(false);
  };

  const columns: GridColDef[] = [
    { field: "id", headerName: "ID", width: 100 },
    {
      field: "edit",
      headerName: "Изменение",
      width: 60,
      renderCell: ({ row }) => {
        return (
          <IconButton onClick={() => setChangingTariff(row)}>
            <ModeEditOutlineOutlinedIcon />
          </IconButton>
        );
      },
    },
    { field: "name", headerName: "Название тарифа", width: 150 },
    { field: "amount", headerName: "Количество", width: 110 },
    { field: "serviceName", headerName: "Сервис", width: 150 }, //инфо из гитлаба.
    { field: "privilegeName", headerName: "Привилегия", width: 150 },
    { field: "type", headerName: "Единица", width: 100 },
    { field: "pricePerUnit", headerName: "Цена за ед.", width: 100 },
    { field: "customPricePerUnit", headerName: "Кастомная цена", width: 130 },
    { field: "total", headerName: "Сумма", width: 60 },
    {
      field: "delete",
      headerName: "Удаление",
      width: 60,
      renderCell: ({ row }) => {
        return (
          <IconButton
            onClick={() => {
              setOpenDeleteModal(row.id);
            }}
          >
            <BackspaceIcon />
          </IconButton>
        );
      },
    },
  ];

  const gridData = tariffs
    ?.map((tariff) => {
      console.log(tariff);
      const privilege = findPrivilegeById(tariff.privilegeId);
      return {
        id: tariff.id,
        name: tariff.name,
        serviceName:
          privilege?.serviceKey == "templategen"
            ? "Шаблонизатор"
            : privilege?.serviceKey,
        privilegeName: privilege?.name,
        amount: tariff.amount,
        pricePerUnit: tariff.isCustom
          ? (tariff.customPricePerUnit || 0) / 100
          : (tariff?.price || 0) / 100,
        type:
          findPrivilegeById(tariff.privilegeId)?.value === "шаблон"
            ? "штука"
            : findPrivilegeById(tariff.privilegeId)?.value,
        customPricePerUnit: tariff.customPricePerUnit === 0 ? "Нет" : "Да",
        total: tariff.amount
          ? (tariff.amount *
              (tariff.isCustom
                ? tariff.customPricePerUnit || 0 * tariff.amount
                : findPrivilegeById(tariff.privilegeId)?.price || 0)) /
            100
          : 0,
      };
    })
    .sort((item, previous) => (!item?.isFront && previous?.isFront ? 1 : -1));

  // console.log(gridData)

  return (
    <>
      <Tooltip title="обновить список тарифов">
        <IconButton onClick={() => requestTariffs()}>
          <AutorenewIcon sx={{ color: "white" }} />
        </IconButton>
      </Tooltip>
      <DataGrid
        disableSelectionOnClick={true}
        checkboxSelection={true}
        rows={gridData}
        columns={columns}
        getRowId={(row) => row.id}
        components={{ Toolbar: GridToolbar }}
        onSelectionModelChange={handleSelectionChange}
      />
      {selectedTariffs.length ? (
        <Box
          component="section"
          sx={{
            width: "100%",
            display: "flex",
            justifyContent: "start",
            mb: "30px",
          }}
        >
          <Button
            onClick={() => setOpenDeleteModal(true)}
            sx={{ mr: "20px", zIndex: "10000" }}
          >
            Удаление
          </Button>
        </Box>
      ) : (
        <React.Fragment />
      )}
      <DeleteModal
        open={openDeleteModal}
        handleClose={() => {
          closeDeleteModal();
        }}
        selectedTariffs={selectedTariffs}
        requestTariffs={requestTariffs}
      />
      <EditModal tariff={changingTariff} requestTariffs={requestTariffs} />
    </>
  );
}
