import * as React from "react";
import { GridColDef, GridSelectionModel, GridToolbar } from "@mui/x-data-grid";

import DataGrid from "@kitUI/datagrid";

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

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: 130 },
];

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

export default function TariffsDG({ handleSelectionChange }: Props) {
  const tariffs = useTariffStore((state) => state.tariffs);

  const gridData = tariffs.map((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 ?? findPrivilegeById(tariff.privilegeId)?.pricePerUnit,
    isCustomPrice: tariff.customPricePerUnit === undefined ? "Нет" : "Да",
    total: tariff.amount * (tariff.customPricePerUnit ?? findPrivilegeById(tariff.privilegeId)?.pricePerUnit ?? 0),
  }));

  return (
    <DataGrid
      checkboxSelection={true}
      rows={gridData}
      columns={columns}
      components={{ Toolbar: GridToolbar }}
      onSelectionModelChange={handleSelectionChange}
    />
  );
}
