import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Table, Input, Select, Button } from 'antd';
import { PlusOutlined, DeleteOutlined, SaveOutlined, PrinterOutlined } from '@ant-design/icons';
import { Tables } from '../../../../Components/Tables/Table.jsx';
import { useDispatch } from 'react-redux';
import { postProductData, getDirectSaleProducts, getAllProductShortCodes, deleteProductData, getDirectSaleSearchedProduct } from '../../../../Features/ProductPage/ProductPage.js';
import { getSession, printDiv } from '../../../../Services/Others.js';
import { Messages } from '../../../../Components/Notifications/Messages.jsx';
import { FaStarOfLife } from "react-icons/fa6";
import { IoMdRefresh } from "react-icons/io";
import StickerPrintModel from '../../../Product/StickerPrintModal.jsx';
import { getPageStyle, style } from '../../../Product/Printstyles.js';
import { getBarcodeSessionsIDs, getBarcodeTemplate } from '../../../../Features/Barcode/Barcode.js';
import { generateBarcode, generateQRCode, generateQRCodeCopy } from '../../../../Services/utils.js';
import StickerPrintTemplates from '../../../Product/StickerTemplates.jsx';
import useBarcodeGenerator from './useBarcodeQRGenerator.js';
const DirectSale = ({ UomData = [], TaxData = [], ProductTypeData = [], ProdCatData = [], ProdSubCatData = [], SupplierData = [], activeTab = null }) => {
const formRef = useRef();
const tableRef = useRef();
const searchInputRef = useRef();
const dispatch = useDispatch();
const [messageType, setMessageType] = useState(null);
const [messageData, setMessageData] = useState(null);
const [currentPage, setCurrentPage] = useState(1);
const CompId = getSession('CompId');
const BranchId = getSession('BranchId');
const AppId = getSession('AppId');
const UserId = getSession('UserId');
const [dataSource, setDataSource] = useState([]);
const [editingKey, setEditingKey] = useState(null);
const [copies, setCopies] = useState(null);
const [dropdownValue, setDropdownValue] = useState(null);
const [multiProduct, setMultiProduct] = useState(false);
const [printReady, setPrintReady] = useState(false);
const [printProductName, setPrintProductName] = useState(false);
const [productShortCodes, setAllProductShortCodes] = useState([]);
const [searchText, setSearchText] = useState('');
console.log(searchText, "searchText")
const [stickerPrintModalOpen, setStickerPrintModalOpen] = useState(false);
const [barcodeTemplateDetails, setBarcodeTemplateDetails] = useState([]);
const [filteredProducts, setFilteredProducts] = useState([]);
const [labelPrintData, setLabelPrintData] = useState(null);
const [prodId, setProdId] = useState(null);
const [nickName, setNickName] = useState(null);
const [crossData, setCrossData] = useState(null);
const [triggerState, setTriggerState] = useState(1);
const [templateOptions, setTemplateOptions] = useState({
mrp: false,
barcode: false,
color: false,
eDate: false,
mDate: false,
sellingPrice: false,
productName: false,
value: '',
secondValue: '',
qrcode: false,
codeType: '',
});
console.log((searchText != null && searchText != ''), "filteredProducts")
const { qrBase64, barcodeBase64 } = useBarcodeGenerator(prodId);
const handleAdd = () => {
setDataSource([{
key: dataSource.length + 1,
productName: '',
shortCode: '',
sellingPrice: '',
uom: null,
tax: null,
prodId: null,
size: null,
uomName: null,
activeStatus: 'A'
}, ...dataSource]);
};
const handleDelete = async (record) => {
if (record?.prodId) {
if (searchText != null && searchText !== '') {
setSearchText('')
setCurrentPage(1);
if (searchInputRef.current) {
searchInputRef.current.value = '';
}
}
const deleteData = {
ProdId: record.prodId,
ActiveStatus: record.activeStatus === 'A' ? 'D' : 'A',
UpdatedBy: UserId,
};
const response = await dispatch(deleteProductData(deleteData))?.unwrap();
if (response?.data?.statusCode === 1) {
setMessageData(record.activeStatus === 'A' ? 'Product De-Activated Successfully' : 'Product Activated Successfully');
setMessageType('success');
await fetchDirectSaleProducts();
} else {
setMessageData(response?.data?.response || 'Failed to update status');
setMessageType('error');
}
return;
} else {
// const { key } = record;
// setDataSource(dataSource.filter(item => item.key !== key));
setMessageData('Atleast one empty row should be in table.');
setMessageType('warning');
}
};
const handleChange = useCallback((key, field, value) => {
if (searchText) {
setFilteredProducts(prev =>
prev.map(item =>
item.key === key ? { ...item, [field]: value } : item
)
);
} else {
setDataSource(prev =>
prev.map(item =>
item.key === key ? { ...item, [field]: value } : item
)
);
}
}, [searchText]);
const handleSave = async (record) => {
if (!record.productName || !record.sellingPrice || !record.uom || !record.tax || !record?.shortCode) {
setMessageData('Please fill all the required fields!');
setMessageType('warning');
return;
}
const exists = isShortCodeDuplicate(record?.shortCode, record?.prodId);
if (exists) {
setMessageData('Short code already exists for another product');
setMessageType('error');
return;
}
const postData = {
ProdName: record.productName,
Size: '1',
UOM: record.uom,
MRP: record.sellingPrice,
SellPrice: record.sellingPrice,
TaxId: record.tax,
CompId: CompId,
BranchId: BranchId,
AppId: AppId,
ProdType: ProductTypeData?.find(item => item.ConfigName === 'Product')?.ConfigId,
ProdCat: ProdCatData?.find(item => item.ConfigName === 'General')?.ConfigId,
ProdSubCat: ProdSubCatData?.find(item => item.ConfigName === 'General')?.ConfigId,
QtyBasedPrice: 'N',
ProdQtywisePriceDetails: [],
StockAvailable: 'N',
TokenAvailable: 'N',
InwardDate: new Date().toJSON(),
SuppId: SupplierData?.find(item => item.SuppName?.toLowerCase() === 'self')?.SuppId,
AutoGenerateQr: 'N',
QRCode: null,
CreatedBy: UserId,
ProdLogo: '',
Cess: 0,
ProdShortCode: record?.shortCode
};
try {
if (record?.prodId) {
console.log('Updating Product')
} else {
const response = await dispatch(postProductData(postData)).unwrap();
if (response?.data?.statusCode === 1) {
const prodId = response?.data?.ProductDetails?.[0]?.ProdId;
const size = response?.data?.ProductDetails?.[0]?.Size;
const uomName = response?.data?.ProductDetails?.[0]?.UomName;
const totalProducts = response?.data?.ProductDetails?.[0]?.TotalCount;
setSearchText(currentSearchText => {
if (currentSearchText != null && currentSearchText !== '') {
setCurrentPage(1);
setTriggerState(prev => prev + 1);
if (searchInputRef.current) {
searchInputRef.current.value = '';
}
return '';
} else {
setDataSource(prev => prev.map(item =>
item.key === record.key ? { ...item, prodId, size, uomName, totalProducts } : { ...item, totalProducts }
));
}
return currentSearchText;
});
setMessageData('Product saved successfully!');
setMessageType('success');
return;
}
}
} catch (error) {
console.error('Error saving product:', error);
}
};
const handlePrint = async (record) => {
const exists = isShortCodeDuplicate(record?.shortCode, record?.prodId);
if (exists) {
setMessageData('Short code already exists for another product. Cannot print.');
setMessageType('error');
return;
}
setStickerPrintModalOpen(true);
setLabelPrintData({ ...record, MRP: record?.sellingPrice || 0, SellPrice: record?.sellingPrice || 0 });
setProdId(record?.shortCode + '' + record?.sellingPrice)
}
const columns = useMemo(() => [
{
title: 'SL.No',
width: 50,
align: 'center',
render: (_, __, index) => (currentPage - 1) * 10 + index + 1
},
{
title: () =>
Product Name
,
dataIndex: 'productName',
width: 150,
render: (text, record) => (
record.prodId && editingKey !== record.key ?
{text}
:
handleChange(record.key, 'productName', e.target.value)}
placeholder="Enter product name"
/>
)
},
{
title: () => Short Code
,
dataIndex: 'shortCode',
width: 100,
render: (text, record) => (
record.prodId && editingKey !== record.key ?
{text}
:
{
const originalValue = e.target.value;
const hasNonAlpha = /[^a-zA-Z]/.test(originalValue);
if (hasNonAlpha) {
setMessageData('Enter Alphabet Characters only');
setMessageType('warning');
}
}}
onChange={(e) => {
const value = e.target.value.replace(/[^a-zA-Z]/g, '').toUpperCase();
const exists = isShortCodeDuplicate(value, record?.prodId);
if (exists && value) {
setMessageData('Short code already exists for another product');
setMessageType('error');
}
handleChange(record.key, 'shortCode', value);
}}
placeholder="Short Code"
/>
)
},
{
title: () => Selling Price
,
dataIndex: 'sellingPrice',
width: 120,
render: (text, record) => (
record.prodId && editingKey !== record.key ?
{text}
:
{
const value = e.target.value.replace(/[^0-9.]/g, '');
const parts = value.split('.');
const formatted = parts.length > 2 ? `${parts[0]}.${parts.slice(1).join('')}` : value;
handleChange(record.key, 'sellingPrice', formatted);
}}
placeholder="0.00"
/>
)
},
{
title: () => UOM
,
dataIndex: 'uom',
width: 60,
render: (text, record) => (
record.prodId && editingKey !== record.key ?
{UomData?.find(item => item.ConfigId === text)?.ConfigName || '-'}
: