import React from "react";
import { useEffect, useState } from "react";
import { GridColDef, GridSelectionModel, GridToolbar } from "@mui/x-data-grid";
import { Box, Button, 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";
import DeleteModal from "@root/kitUI/DeleteModal";
import EditModal from "@root/kitUI/EditModal";

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

interface Privilege {
  name: string;
  privilegeId: string;
  serviceKey: string;
  amount: number;
  description: string;
  price: number;
  type: string;
  value: string;
  updatedAt: string;
  _id: string;
}

interface MergedTariff {
  _id: string;
  id: string;
  name: string;
  privilegeId: string;
  serviceName: string;
  price: number;
  isCustom: boolean;
  createdAt: string;
  isDeleted: boolean;
  amount?: number;
  customPricePerUnit?: number;
  privilegies: Privilege[];
}

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

  const [errorEdit, setErrorEdit] = useState(false);
  const [errorDelete, setErrorDelete] = useState(false);

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

  const tariffEdit = async (tarifIid: string, tariffName: string, tariffPrice: string, privilege: Privilege) => {
    try {
      await axios({
        method: "put",
        url: `https://admin.pena.digital/strator/tariff/${tarifIid}`,
        headers: {
          Authorization: `Bearer ${token}`,
        },
        data: {
          name: tariffName,
          price: tariffPrice,
          isCustom: true,
          privilegies: [
            {
              name: privilege.name,
              privilegeId: privilege.privilegeId,
              serviceKey: privilege.serviceKey,
              description: privilege.description,
              type: privilege.type,
              value: privilege.value,
              price: privilege.price,
              amount: privilege.amount,
            },
          ],
        },
      });
    } catch (error: any) {
      setErrorEdit(true);
      enqueueSnackbar(error.message);
    }
  };

  const tariffDelete = async (tarifIid: string) => {
    if (exampleTariffs.find((tariff) => tariff.id === tarifIid)) {
      deleteTariffs(tarifIid);
      return;
    }

    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: any) {
      setErrorDelete(true);
      enqueueSnackbar(error.message);
    }
  };

  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: "privilegeName", 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={() => {
              tariffDelete(row.id);
            }}
          >
            <BackspaceIcon />
          </IconButton>
        );
      },
    },
  ];

  const privilegiesName = (array: Privilege[]) => {
    const name = array.map(({ name }) => name);
    return name[0];
  };

  const gridData = mergeTariffs.map((tariff) => ({
    id: tariff._id ? tariff._id : tariff.id,
    name: tariff.name,
    serviceName: SERVICE_LIST.find(
      (service) => service.serviceKey === findPrivilegeById(tariff.privilegeId)?.serviceKey
    )?.displayName,
    privilegeName: tariff.privilegies
      ? privilegiesName(tariff.privilegies)
      : `(${tariff.privilegeId}) ${findPrivilegeById(tariff.privilegeId)?.description ?? "Привилегия не найдена"}`,
    privilege: tariff.privilegies ? tariff.privilegies : [],
    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,
  }));

  const selectedTariff = gridData.find((tariff) => tariff.id === selectedTariffs[0]);
  const selectedTariffName = selectedTariff ? selectedTariff.name : "";

  const selectedTariffPrivilege = selectedTariff ? selectedTariff.privilege : [];

  return (
    <>
      <DataGrid
        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" }}>
            Удаление
          </Button>
          <Button onClick={() => setOpenEditModal(true)}>Редактирование</Button>
        </Box>
      ) : (
        <React.Fragment />
      )}
      <DeleteModal
        tariffDelete={tariffDelete}
        errorDelete={errorDelete}
        tariffId={String(selectedTariffs[0])}
        tariffName={selectedTariffName}
        open={openDeleteModal}
        handleClose={() => setOpenDeleteModal(false)}
      />
      <EditModal
        tariffEdit={tariffEdit}
        errorEdit={errorEdit}
        tariff={selectedTariff}
        selectedTariffPrivilege={selectedTariffPrivilege}
        open={openEditModal}
        handleClose={() => setOpenEditModal(false)}
      />
    </>
  );
}
