import React, { useEffect, useState } from 'react';
import {
  Modal,
  Form,
  Select,
  Input,
  DatePicker,
  Button,
  Table,
  InputNumber,
  Typography,
  Divider,
  message,
  Tooltip,
} from 'antd';
import { PlusOutlined, DeleteOutlined, WarningOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import jwtAxios from '../../../api/axiosInstance';
import { ENDPOINTS } from '../../../api/endpoints';

const { Text } = Typography;

interface RetailSaleModalProps {
  open: boolean;
  onCancel: () => void;
  onSuccess: () => void;
}

// Helper to extract cost price across all possible field structures
const getLotCostPerUnit = (lot: any): number | undefined => {
  if (!lot) return undefined;

  const candidates = [
    lot.costPerUnit,
    lot.ratePerUnit,
    lot.cost,
    lot.unitCost,
    lot.costPrice,
    lot.purchaseCost,
    lot.rate,
    lot.price,
  ];

  for (const c of candidates) {
    if (c !== undefined && c !== null && c !== '' && !isNaN(Number(c)) && Number(c) > 0) {
      return Number(c);
    }
  }

  if (lot.purchase) {
    const purchaseCandidates = [
      lot.purchase.costPerUnit,
      lot.purchase.ratePerUnit,
      lot.purchase.cost,
      lot.purchase.unitCost,
      lot.purchase.costPrice,
      lot.purchase.rate,
      lot.purchase.price,
    ];

    for (const c of purchaseCandidates) {
      if (c !== undefined && c !== null && c !== '' && !isNaN(Number(c)) && Number(c) > 0) {
        return Number(c);
      }
    }
  }

  if (lot.allocation) {
    const allocCandidates = [
      lot.allocation.costPerUnit,
      lot.allocation.ratePerUnit,
      lot.allocation.cost,
      lot.allocation.purchase?.costPerUnit,
      lot.allocation.purchase?.ratePerUnit,
    ];

    for (const c of allocCandidates) {
      if (c !== undefined && c !== null && c !== '' && !isNaN(Number(c)) && Number(c) > 0) {
        return Number(c);
      }
    }
  }

  // Fallback check for 0 value if no positive value was found
  for (const c of candidates) {
    if (c !== undefined && c !== null && c !== '' && !isNaN(Number(c))) {
      return Number(c);
    }
  }

  if (lot.purchase) {
    for (const c of [lot.purchase.costPerUnit, lot.purchase.ratePerUnit, lot.purchase.cost]) {
      if (c !== undefined && c !== null && c !== '' && !isNaN(Number(c))) {
        return Number(c);
      }
    }
  }

  return undefined;
};

export const RetailSaleModal: React.FC<RetailSaleModalProps> = ({ open, onCancel, onSuccess }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [retailLots, setRetailLots] = useState<any[]>([]);
  const [paymentModes, setPaymentModes] = useState<string[]>([]);

  // Line items state for dynamic calculation
  const [items, setItems] = useState<any[]>([
    { key: Date.now(), vegetableId: undefined, lotNo: undefined, saleUnit: 'KG', quantity: 1, bags: undefined, sellingRate: 0, total: 0, costPerUnit: undefined, weightPerBag: null, lotUnit: undefined },
  ]);

  const [discount, setDiscount] = useState<number>(0);
  const [itemErrors, setItemErrors] = useState<Record<string, string[]>>({});

  useEffect(() => {
    if (open) {
      fetchMeta();
      fetchRetailLots();
      form.resetFields();
      setItems([{ key: Date.now(), vegetableId: undefined, lotNo: undefined, saleUnit: 'KG', quantity: 1, bags: undefined, sellingRate: 0, total: 0, costPerUnit: undefined, weightPerBag: null, lotUnit: undefined }]);
      setItemErrors({});
      setDiscount(0);
      form.setFieldsValue({ invoiceDate: dayjs() });
    }
  }, [open]);

  const fetchMeta = async () => {
    try {
      const res = await jwtAxios.get(ENDPOINTS.RETAIL_SALES_META);
      const modes = res.data?.result?.paymentModes || ['CASH', 'UPI'];
      setPaymentModes(modes);
      if (modes.length > 0) {
        form.setFieldValue('paymentMode', modes[0]);
      }
    } catch (err: any) {
      message.error('Failed to fetch customers & payment modes');
    }
  };

  const fetchRetailLots = async () => {
    try {
      // Fetch retail lots along with sales available lots and retail summary for cost cross-referencing
      const [retailRes, salesRes, summaryRes] = await Promise.allSettled([
        jwtAxios.get(ENDPOINTS.RETAIL_STOCK_RETAIL_LOTS),
        jwtAxios.get(ENDPOINTS.SALES_AVAILABLE_LOTS),
        jwtAxios.get(ENDPOINTS.RETAIL_STOCK_SUMMARY),
      ]);

      const rawLots: any[] = retailRes.status === 'fulfilled' ? retailRes.value.data?.result || [] : [];
      const salesLots: any[] = salesRes.status === 'fulfilled' ? salesRes.value.data?.result || [] : [];
      const summaryLots: any[] = summaryRes.status === 'fulfilled' ? summaryRes.value.data?.result || [] : [];

      // Build cost lookup map by lotNo / id / batchLabel / purchaseId
      const costMap = new Map<string, number>();

      salesLots.forEach((l: any) => {
        const cost = getLotCostPerUnit(l);
        if (cost !== undefined) {
          if (l.lotNo) costMap.set(String(l.lotNo).toLowerCase(), cost);
          if (l.batchLabel) costMap.set(String(l.batchLabel).toLowerCase(), cost);
          if (l.id) costMap.set(String(l.id), cost);
        }
      });

      summaryLots.forEach((l: any) => {
        const cost = getLotCostPerUnit(l);
        if (cost !== undefined) {
          if (l.lotNo) costMap.set(String(l.lotNo).toLowerCase(), cost);
          if (l.id) costMap.set(String(l.id), cost);
          if (l.purchaseId) costMap.set(String(l.purchaseId), cost);
        }
      });

      // Enrich retail lots with costPerUnit
      const enrichedLots = rawLots.map((lot: any) => {
        let cost = getLotCostPerUnit(lot);

        if (cost === undefined) {
          const lotKey = lot.lotNo ? String(lot.lotNo).toLowerCase() : undefined;
          const batchKey = lot.batchLabel ? String(lot.batchLabel).toLowerCase() : undefined;
          const purchaseKey = lot.purchaseId ? String(lot.purchaseId) : (lot.purchase?.id ? String(lot.purchase.id) : undefined);
          const idKey = lot.id ? String(lot.id) : undefined;

          if (lotKey && costMap.has(lotKey)) {
            cost = costMap.get(lotKey);
          } else if (batchKey && costMap.has(batchKey)) {
            cost = costMap.get(batchKey);
          } else if (purchaseKey && costMap.has(purchaseKey)) {
            cost = costMap.get(purchaseKey);
          } else if (idKey && costMap.has(idKey)) {
            cost = costMap.get(idKey);
          }
        }

        return {
          ...lot,
          costPerUnit: cost,
        };
      });

      setRetailLots(enrichedLots);
    } catch (err: any) {
      message.error('Failed to fetch available retail lots');
    }
  };

  // Extract unique vegetables from available retail stock
  const vegetableOptions = Array.from(
    new Map(
      retailLots
        .filter((lot) => lot.vegetable?.id)
        .map((lot) => [String(lot.vegetable.id), { id: String(lot.vegetable.id), name: lot.vegetable.name }])
    ).values()
  );

  const updateItem = (index: number, field: string, value: any) => {
    const updated = [...items];
    const row = { ...updated[index], [field]: value };
    
    setItemErrors(prev => {
      const newErrors = { ...prev };
      delete newErrors[`items.${index}.${field}`];
      return newErrors;
    });

    if (field === 'vegetableId') {
      row.lotNo = undefined;
      row.weightPerBag = null;
      row.lotUnit = undefined;
      row.costPerUnit = undefined;
      row.saleUnit = 'KG';
      row.quantity = 1;
      row.bags = undefined;
      row.total = 0;
      if (!value) {
        row.vegetableId = undefined;
      }
    }

    if (field === 'lotNo') {
      if (!value) {
        row.lotNo = undefined;
        row.vegetableId = undefined;
        row.weightPerBag = null;
        row.lotUnit = undefined;
        row.costPerUnit = undefined;
        row.saleUnit = 'KG';
        row.quantity = 1;
        row.bags = undefined;
        row.total = 0;
      } else {
        const selected = retailLots.find((l) => l.lotNo === value);
        if (selected) {
          row.weightPerBag = selected.weightPerBag ? Number(selected.weightPerBag) : null;
          row.lotUnit = selected.unit;
          row.isFlexible = !!selected.isFlexible || !!selected.vegetable?.isFlexible || selected.unit === 'THAAR';
          const isFlexibleLot = row.isFlexible;
          row.saleUnit = isFlexibleLot
            ? (selected.unit === 'THAAR' ? 'THAAR' : 'PIECES')
            : (selected.unit && selected.unit !== 'KG' && Number(selected.remainingBags) > 0 ? selected.unit : 'KG');
          if (row.saleUnit !== 'KG') {
            row.quantity = undefined;
            row.bags = 1;
          } else {
            row.quantity = 1;
            row.bags = undefined;
          }
          row.costPerUnit = getLotCostPerUnit(selected) ?? selected.costPerUnit;
          if (selected.vegetable?.id && String(row.vegetableId) !== String(selected.vegetable.id)) {
            row.vegetableId = String(selected.vegetable.id);
          }
        } else {
          row.weightPerBag = null;
          row.lotUnit = undefined;
          row.isFlexible = false;
          row.costPerUnit = undefined;
        }
      }
    }

    if (field === 'saleUnit') {
      if (value === 'KG') {
        row.bags = undefined;
        row.quantity = row.quantity || 1;
      } else {
        row.quantity = undefined;
        row.bags = row.bags || 1;
      }
    }

    // Calculate line total
    const rate = Number(row.sellingRate) || 0;
    if (row.saleUnit === 'KG') {
      const qty = Number(row.quantity) || 0;
      row.total = Number((qty * rate).toFixed(2));
    } else {
      // BAG / BOX — rate is per bag/box, so total = bags × rate
      const bags = Number(row.bags) || 0;
      row.total = Number((bags * rate).toFixed(2));
    }

    updated[index] = row;
    setItems(updated);
  };

  const addItem = () => {
    setItems([
      ...items,
      { key: Date.now(), vegetableId: undefined, lotNo: undefined, saleUnit: 'KG', quantity: 1, bags: undefined, sellingRate: 0, total: 0, costPerUnit: undefined, weightPerBag: null, lotUnit: undefined },
    ]);
  };

  const removeItem = (index: number) => {
    if (items.length === 1) {
      message.warning('At least one item is required');
      return;
    }
    setItems(items.filter((_, i) => i !== index));
  };

  const subTotal = items.reduce((sum, item) => sum + (Number(item.total) || 0), 0);
  const grandTotal = Math.max(0, subTotal - discount);

  const onFinish = async (values: any) => {
    // Validate items
    for (let i = 0; i < items.length; i++) {
      const it = items[i];
      if (!it.vegetableId) {
        message.error(`Please select a vegetable for item #${i + 1}`);
        return;
      }
      if (!it.lotNo) {
        message.error(`Please select a lot for item #${i + 1}`);
        return;
      }
      if (it.saleUnit === 'KG' && (!it.quantity || it.quantity <= 0)) {
        message.error(`Please enter valid quantity (KG) for item #${i + 1}`);
        return;
      }
      if (it.saleUnit !== 'KG' && (!it.bags || it.bags <= 0)) {
        const unitName = it.saleUnit === 'PIECES' ? 'pieces' : it.saleUnit === 'THAAR' ? 'thaar' : 'bags/boxes';
        message.error(`Please enter valid ${unitName} count for item #${i + 1}`);
        return;
      }
      if (it.sellingRate === undefined || it.sellingRate < 0) {
        message.error(`Please enter valid selling rate for item #${i + 1}`);
        return;
      }
    }

    setLoading(true);
    try {
      const payload = {
        walkInName: values.walkInName,
        walkInMobile: values.walkInMobile,
        invoiceDate: values.invoiceDate.format('YYYY-MM-DD'),
        paymentMode: values.paymentMode,
        discount: Number(discount),
        subTotal: Number(subTotal.toFixed(2)),
        grandTotal: Number(grandTotal.toFixed(2)),
        remarks: values.remarks,
        items: items.map((it) => ({
          lotNo: it.lotNo,
          saleUnit: it.saleUnit,
          quantity: it.saleUnit === 'KG' ? Number(it.quantity) : (it.saleUnit === 'PIECES' ? Number(it.bags) : undefined),
          bags: it.saleUnit !== 'KG' ? Number(it.bags) : undefined,
          sellingRate: Number(it.sellingRate),
        })),
      };

      await jwtAxios.post(ENDPOINTS.RETAIL_SALES, payload);
      message.success('Retail sale recorded successfully!');
      onSuccess();
    } catch (err: any) {
      if (err.response?.status === 422 && err.response?.data?.errors) {
        const fieldErrors = err.response.data.errors;
        const formErrors: { name: string | (string | number)[]; errors: string[] }[] = [];
        const newItemErrors: Record<string, string[]> = {};

        Object.keys(fieldErrors).forEach((fieldName) => {
          const rawErrors = fieldErrors[fieldName];
          const errorMsgs = Array.isArray(rawErrors) ? rawErrors : [rawErrors];

          if (fieldName.startsWith('items.')) {
            newItemErrors[fieldName] = errorMsgs;
          } else {
            let namePath: string | (string | number)[] = fieldName;
            if (fieldName.includes('.')) {
              namePath = fieldName.split('.').map((p) => (!isNaN(Number(p)) ? Number(p) : p));
            }
            formErrors.push({
              name: namePath,
              errors: errorMsgs,
            });
          }
        });
        
        setItemErrors(newItemErrors);

        if (formErrors.length > 0) {
          form.setFields(formErrors);
        }
        
        message.error(err.response?.data?.message || 'Validation failed.');
      } else {
        message.error(err.response?.data?.message || 'Failed to create retail sale');
      }
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      title: 'Vegetable',
      width: 170,
      render: (_: any, record: any, index: number) => (
        <Select
          showSearch
          allowClear
          className="w-full"
          placeholder="Select Vegetable"
          value={record.vegetableId}
          onChange={(val) => updateItem(index, 'vegetableId', val)}
          optionFilterProp="label"
          filterOption={(input, option) =>
            (option?.label ?? '').toString().toLowerCase().includes(input.toLowerCase())
          }
          options={vegetableOptions.map((veg) => ({
            value: veg.id,
            label: veg.name,
          }))}
        />
      ),
    },
    {
      title: 'Retail Lot',
      width: 250,
      render: (_: any, record: any, index: number) => {
        const availableLotsForVeg = record.vegetableId
          ? retailLots.filter((lot) => String(lot.vegetable?.id) === String(record.vegetableId))
          : retailLots;
        return (
          <Select
            showSearch
            allowClear
            className="w-full"
            placeholder="Select or enter lot no"
            value={record.lotNo}
            onChange={(val) => updateItem(index, 'lotNo', val)}
            optionFilterProp="label"
            filterOption={(input, option) => {
              const searchText = input.toLowerCase();
              const label = String(option?.label || '').toLowerCase();
              return label.includes(searchText);
            }}
            onSearch={(value) => {
              if (!value || !value.trim()) return;
              const trimmed = value.trim().toLowerCase();
              const exists = retailLots.some(
                (l) =>
                  l.lotNo?.toLowerCase().includes(trimmed) ||
                  l.vegetable?.name?.toLowerCase().includes(trimmed)
              );
              if (!exists) {
                message.warning(`Lot number "${value.trim()}" is not available or out of stock.`);
              }
            }}
            options={availableLotsForVeg.map((lot) => ({
              value: lot.lotNo,
              label: `${lot.lotNo} ${lot.vegetable?.name ? `(${lot.vegetable.name})` : ''} (Avail: ${Number(lot.remainingQuantity)} KG${lot.remainingBags ? ` / ${lot.remainingBags} ${lot.unit}` : ''})`,
            }))}
          />
        );
      },
    },
    {
      title: 'Unit',
      width: 100,
      render: (_: any, record: any, index: number) => {
        const isLotFlexible = !!record.isFlexible || record.lotUnit === 'THAAR';
        const unitOptions = isLotFlexible
          ? [
              { label: 'PIECES', value: 'PIECES' },
              ...(record.lotUnit === 'THAAR'
                ? [{ label: 'THAAR', value: 'THAAR' }]
                : record.lotUnit === 'BAG'
                  ? [{ label: 'BAG', value: 'BAG' }, { label: 'KG', value: 'KG' }]
                  : record.lotUnit === 'BOX'
                    ? [{ label: 'BOX', value: 'BOX' }, { label: 'KG', value: 'KG' }]
                    : [{ label: 'KG', value: 'KG' }]),
            ]
          : [
              ...(Number(record.remainingQuantity ?? 1) > 0 ? [{ label: 'KG', value: 'KG' }] : []),
              ...(record.lotUnit && record.lotUnit !== 'KG'
                ? [{ label: record.lotUnit, value: record.lotUnit }]
                : (record.weightPerBag ? [{ label: 'BAG', value: 'BAG' }] : [])),
            ];

        const finalOptions = unitOptions.length > 0 ? unitOptions : [{ label: 'KG', value: 'KG' }];

        return (
          <Select
            className="w-full"
            value={record.saleUnit}
            onChange={(val) => updateItem(index, 'saleUnit', val)}
            options={finalOptions}
          />
        );
      },
    },
    {
      title: <span style={{ whiteSpace: 'nowrap' }}>Cost / Unit</span>,
      width: 125,
      render: (_: any, record: any) => {
        let costVal: number | undefined = undefined;
        if (record.costPerUnit !== undefined && record.costPerUnit !== null) {
          if (record.saleUnit !== 'KG' && record.weightPerBag) {
            costVal = record.costPerUnit * Number(record.weightPerBag);
          } else {
            costVal = record.costPerUnit;
          }
        }
        const labelText = record.saleUnit === 'PIECES'
          ? 'Cost / Piece'
          : (record.saleUnit && record.saleUnit !== 'KG'
            ? `Cost / ${record.lotUnit === 'THAAR' ? 'Thaar' : (record.lotUnit || record.saleUnit)}`
            : 'Cost / Kg');
        return (
          <Tooltip title={labelText}>
            <Input
              readOnly
              value={costVal !== undefined ? `₹${costVal.toFixed(2)}` : '-'}
              style={{
                fontWeight: 'bold',
                background: '#f5f5f5',
                color: '#333',
                cursor: 'default',
                borderColor: '#d9d9d9',
                textAlign: 'center',
                paddingLeft: 4,
                paddingRight: 4,
              }}
            />
          </Tooltip>
        );
      },
    },
    {
      title: <span style={{ whiteSpace: 'nowrap' }}>Quantity</span>,
      width: 115,
      render: (_: any, record: any, index: number) => {
        const hasKgError = itemErrors[`items.${index}.quantity`];
        const hasBagError = itemErrors[`items.${index}.bags`];
        if (record.saleUnit === 'KG') {
          return (
            <div>
              <InputNumber
                min={0.001}
                step={0.5}
                className="w-full"
                placeholder="KG"
                value={record.quantity}
                status={hasKgError ? 'error' : ''}
                onChange={(val) => updateItem(index, 'quantity', val)}
              />
              {hasKgError && <div style={{ color: '#ff4d4f', fontSize: '11px', marginTop: '2px', lineHeight: '1.2' }}>{hasKgError[0]}</div>}
            </div>
          );
        }
        const countPlaceholder = record.saleUnit === 'THAAR' ? 'Thaar' : record.saleUnit === 'PIECES' ? 'Pieces' : (record.saleUnit === 'BOX' ? 'Boxes' : 'Bags');
        return (
          <div>
            <InputNumber
              min={1}
              step={1}
              className="w-full"
              placeholder={countPlaceholder}
              value={record.bags}
              status={hasBagError ? 'error' : ''}
              onChange={(val) => updateItem(index, 'bags', val)}
            />
            {hasBagError && <div style={{ color: '#ff4d4f', fontSize: '11px', marginTop: '2px', lineHeight: '1.2' }}>{hasBagError[0]}</div>}
          </div>
        );
      },
    },
    {
      title: <span style={{ whiteSpace: 'nowrap' }}>Rate (per Unit)</span>,
      width: 135,
      render: (_: any, record: any, index: number) => {
        let unitCost: number | undefined = undefined;
        if (record.costPerUnit !== undefined && record.costPerUnit !== null) {
          if (record.saleUnit !== 'KG' && record.weightPerBag) {
            unitCost = record.costPerUnit * Number(record.weightPerBag);
          } else {
            unitCost = record.costPerUnit;
          }
        }
        const sellingRate = Number(record.sellingRate) || 0;
        const isFlexibleLot = !!record.isFlexible || record.lotUnit === 'THAAR' || record.saleUnit === 'PIECES';
        const isBelowCost = !isFlexibleLot && unitCost !== undefined && sellingRate > 0 && sellingRate < unitCost;
        const margin = !isFlexibleLot && unitCost !== undefined && sellingRate > 0 ? sellingRate - unitCost : undefined;
        const hasRateError = itemErrors[`items.${index}.sellingRate`];

        return (
          <div>
            <InputNumber
              min={0}
              step={1}
              className="w-full"
              placeholder="Rate"
              value={record.sellingRate}
              status={hasRateError ? 'error' : ''}
              style={{ borderColor: !hasRateError && isBelowCost ? '#faad14' : undefined }}
              onChange={(val) => updateItem(index, 'sellingRate', val)}
            />
            {hasRateError && <div style={{ color: '#ff4d4f', fontSize: '11px', marginTop: '2px', lineHeight: '1.2' }}>{hasRateError[0]}</div>}
            {isBelowCost && !hasRateError && (
              <Tooltip title={`Selling rate ₹${sellingRate.toFixed(2)} is below cost ₹${unitCost!.toFixed(2)}. Loss: ₹${Math.abs(margin!).toFixed(2)}/unit.`}>
                <div style={{ fontSize: 11, color: '#faad14', marginTop: 2, cursor: 'help', whiteSpace: 'nowrap' }}>
                  <WarningOutlined /> Below cost
                </div>
              </Tooltip>
            )}
            {!isBelowCost && margin !== undefined && margin > 0 && !hasRateError && (
              <div style={{ fontSize: 11, color: '#52c41a', marginTop: 2, whiteSpace: 'nowrap' }}>
                Margin: +₹{margin.toFixed(2)}
              </div>
            )}
          </div>
        );
      },
    },
    {
      title: <span style={{ whiteSpace: 'nowrap' }}>Total (₹)</span>,
      width: 105,
      render: (_: any, record: any) => (
        <Text strong style={{ whiteSpace: 'nowrap' }}>
          ₹{record.total ? record.total.toFixed(2) : '0.00'}
        </Text>
      ),
    },
    {
      title: '',
      width: 45,
      render: (_: any, __: any, index: number) => (
        <Button
          type="text"
          danger
          icon={<DeleteOutlined />}
          onClick={() => removeItem(index)}
        />
      ),
    },
  ];

  return (
    <Modal
      title="New Retail Sale"
      open={open}
      onCancel={onCancel}
      onOk={() => form.submit()}
      confirmLoading={loading}
      width={1120}
      okText="Complete Sale"
    >
      <Form form={form} layout="vertical" onFinish={onFinish}>
        <div className="grid grid-cols-2 gap-4">

          <Form.Item
            name="invoiceDate"
            label="Sale Date"
            rules={[{ required: true, message: 'Select date' }]}
          >
            <DatePicker className="w-full" format="YYYY-MM-DD" />
          </Form.Item>

          <Form.Item
            name="paymentMode"
            label="Payment Mode"
            rules={[{ required: true, message: 'Select payment mode' }]}
          >
            <Select
              placeholder="Select mode"
              options={paymentModes.map((mode) => ({
                value: mode,
                label: mode,
              }))}
            />
          </Form.Item>
        </div>


        <div className="grid grid-cols-2 gap-4">
          <Form.Item
            name="walkInName"
            label="Walk-in Customer Name"
            rules={[{ required: true, message: 'Enter customer name' }]}
          >
            <Input placeholder="Customer name" />
          </Form.Item>
          <Form.Item
            name="walkInMobile"
            label="Mobile Number"
            rules={[
              {
                pattern: /^(?:(?:\+?91)|0)?[6-9]\d{9}$/,
                message: 'Please enter a valid 10-digit mobile number (e.g. 9876543210)',
              },
            ]}
          >
            <Input placeholder="Mobile number (optional)" maxLength={13} />
          </Form.Item>
        </div>

        <Divider children="Sale Items" />

        <Table
          pagination={false}
          columns={columns}
          dataSource={items}
          rowKey="key"
          size="small"
          scroll={{ x: 1000 }}
        />

        <Button
          type="dashed"
          onClick={addItem}
          block
          icon={<PlusOutlined />}
          className="mt-3"
        >
          Add Item Row
        </Button>

        <Divider />

        <div className="flex justify-between items-start">
          <div className="w-1/2 pr-4">
            <Form.Item name="remarks" label="Remarks">
              <Input.TextArea rows={2} placeholder="Optional notes..." />
            </Form.Item>
          </div>

          <div className="w-1/2 pl-4 border-l border-gray-200">
            <div className="flex justify-between mb-2">
              <Text>Sub Total:</Text>
              <Text>₹{subTotal.toFixed(2)}</Text>
            </div>

            {/* <div className="flex justify-between items-center mb-2">
              <Text>Discount (₹):</Text>
              <InputNumber
                min={0}
                value={discount}
                onChange={(val) => setDiscount(val || 0)}
                style={{ width: 120 }}
              />
            </div> */}

            <div className="flex justify-between mb-2 text-lg font-bold">
              <Text type="success">Grand Total:</Text>
              <Text type="success">₹{grandTotal.toFixed(2)}</Text>
            </div>


          </div>
        </div>
      </Form>
    </Modal>
  );
};
