import { useEffect, useState } from "react";
import { GridColDef, GridSelectionModel, GridToolbar } from "@mui/x-data-grid";
import { IconButton } from "@mui/material";
import BackspaceIcon from "@mui/icons-material/Backspace";
import { enqueueSnackbar } from "notistack";

import DataGrid from "@kitUI/datagrid";

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

import axios from "axios";
import { authStore } from "@root/stores/auth";

interface Props {
  handleSelectionChange: (selectionModel: GridSelectionModel) => void;
}

export default function TariffsDG({ handleSelectionChange }: Props) {
  const exampleTariffs = useTariffStore((state) => state.tariffs);
  const [tariffs, setTariffs] = useState<any>();
  const [deletedRows, setDeletedRows] = useState<string[]>([]);
  const { token } = authStore();

  const mergeTariffs = [...exampleTariffs, ...(tariffs?.tariffs ?? [])];

  console.log(mergeTariffs);

  const tariffsDelete = async (tarifIid: string) => {
    try {
      await axios({
        method: "delete",
        url: "https://admin.pena.digital/strator/tariff",
        headers: {
          Authorization: `Bearer ${token}`,
        },
        data: { id: tarifIid },
      });
      setDeletedRows((prevDeletedRows) => [...prevDeletedRows, tarifIid]);
    } catch (error) {
      enqueueSnackbar("Ошибка удаления тарифов");
    }
  };

  useEffect(() => {
    const axiosTariffs = async () => {
      try {
        const { data } = await axios({
          method: "get",
          url: "https://admin.pena.digital/strator/tariff",
        });
        setTariffs(data);
        console.log(data);
      } catch (error) {
        enqueueSnackbar("Ошибка получения тарифов");
      }
    };

    axiosTariffs();
  }, [deletedRows]);

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

  const gridData = mergeTariffs.map(
    (tariff: {
      _id: string;
      id: string;
      name: string;
      privilegeId: string;
      amount: number;
      price: number;
      isDeleted: boolean;
      customPricePerUnit: number;
    }) => ({
      id: tariff._id ? tariff._id : tariff.id,
      name: tariff.name,
      serviceName: SERVICE_LIST.find(
        (service) => service.serviceKey === findPrivilegeById(tariff.privilegeId)?.serviceKey
      )?.displayName,
      privilege: `(${tariff.privilegeId}) ${
        findPrivilegeById(tariff.privilegeId)?.description ?? "Привилегия не найдена"
      }`,
      amount: tariff.amount,
      type: findPrivilegeById(tariff.privilegeId)?.type === "count" ? "день" : "шт.",
      pricePerUnit: tariff.customPricePerUnit
        ? tariff.customPricePerUnit ?? findPrivilegeById(tariff.privilegeId)?.price
        : tariff.price,
      isCustomPrice: tariff.customPricePerUnit === undefined ? "Нет" : "Да",
      isDeleted: tariff.isDeleted,
      total: tariff.amount
        ? tariff.amount * (tariff.customPricePerUnit ?? findPrivilegeById(tariff.privilegeId)?.price ?? 0)
        : 0,
    })
  );
  return (
    <DataGrid
      checkboxSelection={true}
      rows={gridData}
      columns={columns}
      getRowId={(row) => row.id}
      components={{ Toolbar: GridToolbar }}
      onSelectionModelChange={handleSelectionChange}
    />
  );
}
