import { Table, message } from 'antd';
import { DefaultModal } from '../../Components/Modal/DefaultModal.jsx';

const QRCodeCopiesModal = ({
  open,
  onClose,
  type = 'stock', // 'stock' or 'product'
  onFinish,
  QrandbarcodeDatas,
  setQrandbarcodeDatas,
}) => {
  const title = type === 'stock' ? 'Stock Wise Qrcode' : 'Product Wise Qrcode';
  const showStockIndication = type === 'stock';
  const totalCopies = QrandbarcodeDatas?.reduce(
    (sum, item) => sum + Number(item?.copiesCount || 0),
    0
  );
  const handleSubmit = () => {
    if (totalCopies == 0) {
      message.error('Please enter copies count');
      return;
    } else {
      onClose();
      onFinish();
    }
  };

  const columns = [
    { title: 'Product Name', dataIndex: 'productName', key: 'productName' },
    {
      title: 'Copies Count',
      dataIndex: 'copiesCount',
      key: 'copiesCount',
      render: (text, record) => (
        <input
          className="inputpwiseQR"
          type="number"
          min="1"
          value={record.copiesCount}
          onChange={(e) => {
            const newValue =
              type === 'product'
                ? parseInt(e.target.value) || 1
                : parseInt(e.target.value);
            setQrandbarcodeDatas((prev) =>
              prev.map((item) =>
                item.key === record.key
                  ? { ...item, copiesCount: newValue }
                  : item
              )
            );
          }}
          style={{ width: '80px' }}
        />
      ),
    },
  ];

  return (
    <DefaultModal
      open={open}
      title={title}
      handleCancel={onClose}
      handleSubmit={handleSubmit}
      footer={true}
      children={
        <>
          <div className="ProductList-pwiseQrcode">
            <Table
              columns={columns}
              dataSource={QrandbarcodeDatas}
              rowKey="ProdId"
              pagination={false}
              size="small"
              rowClassName={
                showStockIndication
                  ? (record) => (record.StockAvailable === 'N' ? 'row-red' : '')
                  : undefined
              }
            />
          </div>
          {showStockIndication && (
            <div className="indicationInfo">
              <p></p>
              <span>Stock is not Maintained</span>
            </div>
          )}
        </>
      }
    />
  );
};

export default QRCodeCopiesModal;
