import React, { useCallback, useEffect, useState } from 'react';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  Input,
  InputNumber,
  Row,
  Select,
  Space,
  Spin,
  message,
  Divider,
  Tag,
  Popconfirm
} from 'antd';
import {
  ArrowLeftOutlined,
  CheckCircleOutlined,
  PlusOutlined,
  ShoppingCartOutlined,
  WalletOutlined,
  MinusCircleOutlined,
  SyncOutlined,
  CloseCircleOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { useNavigate } from 'react-router-dom';
import { AppContainer } from '../../components/AppContainer';
import jwtAxios from '../../api/axiosInstance';
import { ENDPOINTS } from '../../api/endpoints';

// const { Text } = Typography;

interface Option {
  value: string;
  label: string;
}

interface NamedOption {
  id: string;
  name: string;
}

interface PurchaseMeta {
  purchaseUnits: Option[];
  suppliers: NamedOption[];
  vegetables: NamedOption[];
}

interface LotRow {
  id: string;
  vegetableId?: string;
  lotNo: string;
  unit: string;
  bags?: number;
  quantity?: number;
  ratePerUnit?: number;
  rateType?: 'UNIT' | 'KG';
  extraCharges?: number;
  lastEdited?: 'bags' | 'quantity' | null;
  isDuplicate?: boolean;
}

const makeLot = (): LotRow => ({
  id: Date.now().toString() + Math.random().toString(36).substring(2, 9),
  lotNo: '',
  unit: 'BOX',
  rateType: 'UNIT',
  extraCharges: 0,
  lastEdited: null,
  isDuplicate: false,
});

interface LotRowFormProps {
  lot: LotRow;
  index: number;
  purchaseUnits: Option[];
  vegetables: NamedOption[];
  canDelete: boolean;
  onChange: (id: string, updates: Partial<LotRow>) => void;
  onDelete: (id: string) => void;
  /** Backend field errors keyed by field name e.g. { vegetableId: "...", ratePerUnit: "..." } */
  fieldErrors?: Record<string, string>;
  onFieldErrorClear?: (id: string, field: string) => void;
}

const LotRowForm: React.FC<LotRowFormProps> = ({
  lot, index, purchaseUnits, vegetables, canDelete, onChange, onDelete,
  fieldErrors = {}, onFieldErrorClear,
}) => {
  const { id, unit, bags, quantity, ratePerUnit, rateType, lotNo, vegetableId, extraCharges } = lot;

  const [lotStatus, setLotStatus] = useState<{
    checking: boolean;
    isAvailable: boolean | null;
    message: string;
  }>({ checking: false, isAvailable: null, message: '' });

  useEffect(() => {
    if (!lotNo || !lotNo.trim()) {
      setLotStatus({ checking: false, isAvailable: null, message: '' });
      return;
    }
    const timer = setTimeout(async () => {
      setLotStatus((prev) => ({ ...prev, checking: true }));
      try {
        const res = await jwtAxios.get(ENDPOINTS.PURCHASE_CHECK_LOT, {
          params: { lotNo: lotNo.trim(), vegetableId },
        });
        const data = res.data?.data;
        setLotStatus({
          checking: false,
          isAvailable: data?.isAvailable,
          message: data?.message || '',
        });
      } catch (err: any) {
        setLotStatus({
          checking: false,
          isAvailable: false,
          message: err?.response?.data?.message || 'Could not verify lot status.',
        });
      }
    }, 500);
    return () => clearTimeout(timer);
  }, [lotNo, vegetableId]);

  const handleBagsChange = (val: number | null) => {
    onFieldErrorClear?.(id, 'bags');
    onChange(id, { bags: val ?? undefined, lastEdited: 'bags' });
  };

  const handleQtyChange = (val: number | null) => {
    onFieldErrorClear?.(id, 'quantity');
    onChange(id, { quantity: val ?? undefined, lastEdited: 'quantity' });
  };

  const lotGoodsTotal = (unit === 'KG' || rateType === 'KG')
    ? (quantity ?? 0) * (ratePerUnit ?? 0)
    : (bags ?? 0) * (ratePerUnit ?? 0);

  const lotTotalCost = lotGoodsTotal + (extraCharges ?? 0);
  
  let costPerUnit = 0;
  if (lotTotalCost > 0) {
    if (unit === 'KG' || rateType === 'KG') {
      costPerUnit = quantity ? lotTotalCost / quantity : 0;
    } else {
      costPerUnit = bags ? lotTotalCost / bags : 0;
    }
  }

  // Renders a red inline error below a field
  const FieldError = ({ field }: { field: string }) =>
    fieldErrors[field] ? (
      <div style={{ color: '#ff4d4f', fontSize: 12, marginTop: -10, marginBottom: 12, lineHeight: 1.3 }}>
        {fieldErrors[field]}
      </div>
    ) : null;

  return (
    <Card
      size="small"
      style={{
        marginBottom: 12,
        border: '1px solid #d9d9d9',
        borderRadius: 8,
        background: '#fafafa',
      }}
      title={
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontWeight: 600, color: '#1677ff' }}>Lot {index + 1}</span>
          {lotTotalCost > 0 && (
            <Tag color="green" style={{ marginLeft: 4 }}>
              Total: ₹{lotTotalCost.toFixed(2)}
            </Tag>
          )}
          {costPerUnit > 0 && (
            <Tag color="magenta">
              Cost/Unit: ₹{costPerUnit.toFixed(2)}
            </Tag>
          )}
        </div>
      }
      extra={
        canDelete ? (
          <Popconfirm
            title="Remove Lot"
            description="Are you sure you want to remove this lot?"
            onConfirm={() => onDelete(id)}
            okText="Yes"
            cancelText="No"
            placement="topRight"
          >
            <Button
              type="text"
              danger
              size="small"
              icon={<MinusCircleOutlined />}
            />
          </Popconfirm>
        ) : null
      }
    >
      <Row gutter={16}>
        <Col xs={24} sm={12} md={8}>
          <div style={{ marginBottom: 4 }}>
            <label style={{ fontSize: 12, fontWeight: 500 }}>
              <span style={{ color: '#ff4d4f', marginRight: 4 }}>*</span>Vegetable
            </label>
          </div>
          <Select
            showSearch
            placeholder="Select a vegetable"
            optionFilterProp="label"
            style={{ width: '100%', marginBottom: fieldErrors['vegetableId'] ? 4 : 16 }}
            status={fieldErrors['vegetableId'] ? 'error' : undefined}
            value={lot.vegetableId}
            filterOption={(input, option) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
            }
            options={vegetables.map((v) => ({ label: v.name, value: v.id }))}
            onChange={(val) => {
              onFieldErrorClear?.(id, 'vegetableId');
              const veg = vegetables.find((v) => String(v.id) === String(val));
              const vegName = (veg?.name || '').toLowerCase();
              let defaultUnit = lot.unit;
              let defaultRateType = lot.rateType;
              if (vegName.includes('banana') || vegName.includes('வாழை')) {
                defaultUnit = 'THAAR';
                defaultRateType = 'UNIT';
              } else if (vegName.includes('coconut') || vegName.includes('தேங்காய்')) {
                defaultUnit = 'KG';
                defaultRateType = 'KG';
              } else if (vegName.includes('cabbage') || vegName.includes('முட்டைக்கோஸ்')) {
                defaultUnit = 'BAG';
                defaultRateType = 'UNIT';
              }
              onChange(id, { vegetableId: val, unit: defaultUnit, rateType: defaultRateType });
            }}
          />
          <FieldError field="vegetableId" />
        </Col>

        <Col xs={24} sm={12} md={8}>
          <div style={{ marginBottom: 4 }}>
            <label style={{ fontSize: 12, fontWeight: 500 }}>
              <span style={{ color: '#ff4d4f', marginRight: 4 }}>*</span>Lot No
            </label>
            {lotStatus.checking ? (
              <Tag icon={<SyncOutlined spin />} color="processing" style={{ marginLeft: 8 }}>Checking...</Tag>
            ) : lotStatus.isAvailable === false ? (
              <Tag icon={<CloseCircleOutlined />} color="error" style={{ marginLeft: 8 }}>Unavailable</Tag>
            ) : lotStatus.isAvailable === true && !lot.isDuplicate ? (
              <Tag icon={<CheckCircleOutlined />} color="success" style={{ marginLeft: 8 }}>Available</Tag>
            ) : lot.isDuplicate ? (
              <Tag icon={<CloseCircleOutlined />} color="error" style={{ marginLeft: 8 }}>Duplicate</Tag>
            ) : null}
          </div>
          <Input
            placeholder="LOT-VEG-NAME-XX"
            style={{ marginBottom: (lotStatus.message || lot.isDuplicate || fieldErrors['lotNo']) ? 4 : 16 }}
            status={(lotStatus.isAvailable === false || lot.isDuplicate || fieldErrors['lotNo']) ? 'error' : ''}
            value={lot.lotNo}
            onChange={(e) => { onFieldErrorClear?.(id, 'lotNo'); onChange(id, { lotNo: e.target.value }); }}
          />
          {lotStatus.isAvailable === false && !lot.isDuplicate && (
            <div style={{ color: '#ff4d4f', fontSize: 12, marginBottom: 12, lineHeight: 1.2 }}>
              {lotStatus.message}
            </div>
          )}
          {lot.isDuplicate && (
            <div style={{ color: '#ff4d4f', fontSize: 12, marginBottom: 12, lineHeight: 1.2 }}>
              Lot Number is duplicated in this form.
            </div>
          )}
          {fieldErrors['lotNo'] && !lot.isDuplicate && (
            <div style={{ color: '#ff4d4f', fontSize: 12, marginBottom: 12, lineHeight: 1.2 }}>
              {fieldErrors['lotNo']}
            </div>
          )}
        </Col>

        <Col xs={24} sm={12} md={8}>
          <div style={{ marginBottom: 4 }}>
            <label style={{ fontSize: 12, fontWeight: 500 }}>
              <span style={{ color: '#ff4d4f', marginRight: 4 }}>*</span>Unit
            </label>
          </div>
          <Select
            options={purchaseUnits}
            placeholder="Select a unit"
            style={{ width: '100%', marginBottom: fieldErrors['unit'] ? 4 : 16 }}
            status={fieldErrors['unit'] ? 'error' : undefined}
            value={lot.unit}
            onChange={(val) => { onFieldErrorClear?.(id, 'unit'); onChange(id, { unit: val, bags: undefined, quantity: undefined, lastEdited: null, rateType: val === 'KG' ? 'KG' : 'UNIT' }); }}
          />
          <FieldError field="unit" />
        </Col>

        {unit !== 'KG' && (
          <Col xs={24} sm={12} md={8}>
            <div style={{ marginBottom: 4 }}>
              <label style={{ fontSize: 12, fontWeight: 500 }}>
                <span style={{ color: '#ff4d4f', marginRight: 4 }}>*</span>Rate Type
              </label>
            </div>
            <Select
              style={{ width: '100%', marginBottom: 16 }}
              value={lot.rateType}
              onChange={(val) => { onChange(id, { rateType: val as 'UNIT' | 'KG', quantity: val === 'UNIT' ? undefined : lot.quantity }); }}
              options={[
                { value: 'UNIT', label: `Rate / ${unit === 'BOX' ? 'Box' : (unit === 'THAAR' ? 'Thaar' : (unit === 'PIECES' ? 'Piece' : 'Bag'))}` },
                { value: 'KG', label: 'Rate / Kg' },
              ]}
            />
          </Col>
        )}

        {unit !== 'KG' && (
          <Col xs={24} sm={12} md={8}>
            <div style={{ marginBottom: 4 }}>
              <label style={{ fontSize: 12, fontWeight: 500 }}>
                <span style={{ color: '#ff4d4f', marginRight: 4 }}>*</span>
                {unit === 'THAAR' ? 'Number of Thaar' : (unit === 'PIECES' ? 'Number of Pieces' : 'Number of Boxes/Bags')}
              </label>
            </div>
            <InputNumber
              placeholder={unit === 'THAAR' ? 'Thaar count' : (unit === 'PIECES' ? 'Piece count' : 'Boxes/Bags')}
              style={{ width: '100%', marginBottom: fieldErrors['bags'] ? 4 : 16 }}
              status={fieldErrors['bags'] ? 'error' : undefined}
              min={1}
              step={1}
              value={lot.bags}
              onChange={handleBagsChange}
            />
            <FieldError field="bags" />
          </Col>
        )}

        {(unit === 'KG' || rateType === 'KG') && (
          <Col xs={24} sm={12} md={8}>
            <div style={{ marginBottom: 4 }}>
              <label style={{ fontSize: 12, fontWeight: 500 }}>
                <span style={{ color: '#ff4d4f', marginRight: 4 }}>*</span>Quantity (Kg)
              </label>
            </div>
            <InputNumber
              style={{ width: '100%', marginBottom: fieldErrors['quantity'] ? 4 : 16 }}
              status={fieldErrors['quantity'] ? 'error' : undefined}
              min={0.001}
              step={1}
              value={lot.quantity}
              onChange={handleQtyChange}
            />
            <FieldError field="quantity" />
          </Col>
        )}

        <Col xs={24} sm={12} md={8}>
          <div style={{ marginBottom: 4 }}>
            <label style={{ fontSize: 12, fontWeight: 500 }}>
              <span style={{ color: '#ff4d4f', marginRight: 4 }}>*</span>
              {unit === 'KG' ? 'Rate / Kg' : (rateType === 'KG' ? 'Rate / Kg' : `Rate / ${unit === 'BOX' ? 'Box' : (unit === 'THAAR' ? 'Thaar' : (unit === 'PIECES' ? 'Piece' : 'Bag'))}`)}
            </label>
          </div>
          <InputNumber
            style={{ width: '100%', marginBottom: fieldErrors['ratePerUnit'] ? 4 : 16 }}
            status={fieldErrors['ratePerUnit'] ? 'error' : undefined}
            min={0}
            step={0.01}
            value={lot.ratePerUnit}
            onChange={(val) => { onFieldErrorClear?.(id, 'ratePerUnit'); onChange(id, { ratePerUnit: val ?? undefined }); }}
          />
          <FieldError field="ratePerUnit" />
        </Col>

        <Col xs={24} sm={12} md={8}>
          <div style={{ marginBottom: 4 }}>
            <label style={{ fontSize: 12, fontWeight: 500 }}>Extra Charges</label>
          </div>
          <InputNumber
            style={{ width: '100%', marginBottom: fieldErrors['extraCharges'] ? 4 : 16 }}
            min={0}
            step={0.01}
            value={lot.extraCharges}
            onChange={(val) => { onFieldErrorClear?.(id, 'extraCharges'); onChange(id, { extraCharges: val ?? 0 }); }}
          />
          <FieldError field="extraCharges" />
        </Col>
      </Row>
    </Card>
  );
};

export const QuickPurchase = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(false);
  const [meta, setMeta] = useState<PurchaseMeta>({ purchaseUnits: [], suppliers: [], vegetables: [] });
  const [_suppliers, setSuppliers] = useState<NamedOption[]>([]);
  const [vegetables, setVegetables] = useState<NamedOption[]>([]);
  const [paymentModes, setPaymentModes] = useState<{ label: string; value: string }[]>([]);
  const [lots, setLots] = useState<LotRow[]>([makeLot()]);
  // Backend field errors per lot index: { lotIndex -> { fieldName -> errorMessage } }
  const [lotFieldErrors, setLotFieldErrors] = useState<Record<number, Record<string, string>>>({});

  const clearLotFieldError = useCallback((lotId: string, field: string) => {
    const idx = lots.findIndex(l => l.id === lotId);
    if (idx === -1) return;
    setLotFieldErrors(prev => {
      const current = prev[idx];
      if (!current || !current[field]) return prev;
      const next = { ...current };
      delete next[field];
      return { ...prev, [idx]: next };
    });
  }, [lots]);

  useEffect(() => {
    const counts: Record<string, number> = {};
    lots.forEach(l => {
      const ln = l.lotNo.trim();
      if (ln) {
        counts[ln] = (counts[ln] || 0) + 1;
      }
    });

    setLots(prev => {
      let changed = false;
      const next = prev.map(l => {
        const ln = l.lotNo.trim();
        const isDuplicate = ln ? counts[ln] > 1 : false;
        if (l.isDuplicate !== isDuplicate) {
          changed = true;
          return { ...l, isDuplicate };
        }
        return l;
      });
      return changed ? next : prev;
    });
  }, [lots.map(l => l.lotNo).join('|')]);

  const updateLot = useCallback((id: string, updates: Partial<LotRow>) => {
    setLots((prev) => prev.map((l) => l.id === id ? { ...l, ...updates } : l));
  }, []);

  const addLot = useCallback(() => {
    setLots((prev) => [...prev, makeLot()]);
  }, []);

  const removeLot = useCallback((id: string) => {
    setLots((prev) => prev.filter((l) => l.id !== id));
  }, []);

  const fetchMeta = async () => {
    setLoading(true);
    try {
      const [metaRes, pmRes] = await Promise.all([
        jwtAxios.get(ENDPOINTS.PURCHASE_META).catch(() => ({ data: {} })),
        jwtAxios.get(ENDPOINTS.PAYMENTMODES).catch(() => ({ data: {} }))
      ]);

      const result = metaRes.data?.result || {
        purchaseUnits: [],
        suppliers: [],
        vegetables: [],
      };
      setMeta(result);
      setSuppliers(result.suppliers || []);
      setVegetables(result.vegetables || []);

      if (pmRes.data?.success && pmRes.data?.PaymentMode) {
        const modes = Object.keys(pmRes.data.PaymentMode).map((key) => ({ label: key, value: key }));
        setPaymentModes(modes);
      } else {
        setPaymentModes([{ label: 'CASH', value: 'CASH' }, { label: 'BANK', value: 'BANK' }, { label: 'UPI', value: 'UPI' }]);
      }
    } catch (err: any) {
      message.error(err.response?.data?.message || 'Failed to fetch metadata');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchMeta();
    form.setFieldsValue({
      purchaseDate: dayjs(),
      arrivalDate: dayjs(),
    });
  }, []);

  const handleSubmit = async (values: any) => {
    setLoading(true);
    setLotFieldErrors({});
    try {
      // Validate lots
      // Front-end validation → map errors inline to each lot's fields
      const newLotFieldErrors: Record<number, Record<string, string>> = {};
      lots.forEach((lot, idx) => {
        const lotErrors: Record<string, string> = {};
        if (!lot.vegetableId) lotErrors['vegetableId'] = 'Vegetable is required';
        if (!lot.lotNo?.trim()) lotErrors['lotNo'] = 'Lot No is required';
        if (lot.isDuplicate) lotErrors['lotNo'] = `Lot No '${lot.lotNo}' is duplicated in this form`;
        if (lot.unit !== 'KG' && !lot.bags) lotErrors['bags'] = 'Number of Boxes/Bags is required';
        if (lot.unit === 'KG' && !lot.quantity) lotErrors['quantity'] = 'Quantity is required';
        if (!lot.ratePerUnit) lotErrors['ratePerUnit'] = 'Rate is required';
        if (Object.keys(lotErrors).length > 0) newLotFieldErrors[idx] = lotErrors;
      });
      if (Object.keys(newLotFieldErrors).length > 0) {
        setLotFieldErrors(newLotFieldErrors);
        message.error('Please fix the highlighted fields in each lot');
        setLoading(false);
        return;
      }

      // Build bulk payload — one entry per lot, all sharing header fields
      const purchasesPayload = lots.map((lot) => {
        const lotGoodsTotal = (lot.unit === 'KG' || lot.rateType === 'KG')
          ? (lot.quantity ?? 0) * (lot.ratePerUnit ?? 0)
          : (lot.bags ?? 0) * (lot.ratePerUnit ?? 0);
          
        const lotTotalCost = lotGoodsTotal + (lot.extraCharges ?? 0);

        return {
          purchaseDate: values.purchaseDate?.format('YYYY-MM-DD'),
          arrivalDate: values.arrivalDate?.format('YYYY-MM-DD') || values.purchaseDate?.format('YYYY-MM-DD'),
          billNo: values.billNo,
          supplierId: null,
          cashSupplierName: values.cashSupplierName || 'Cash Supplier (Local Market)',
          remarks: values.remarks ? `[Quick Cash Purchase] ${values.remarks}` : '[Quick Cash Purchase]',
          transportFee: 0,
          loadingUnloadingFee: 0,
          otherCharges: 0,
          thaiyalCharges: 0,
          extraCharges: lot.extraCharges ?? 0,
          advanceAmount: Number(lotTotalCost.toFixed(2)), // full settlement
          expenseAmount: values.expenseAmount ?? 0,
          expensePaymentMode: values.expensePaymentMode,
          vegetableId: lot.vegetableId != null ? String(lot.vegetableId) : undefined,
          lotNo: lot.lotNo,
          unit: lot.unit,
          rateType: lot.rateType,
          bags: lot.bags,
          quantity: lot.quantity,
          ratePerUnit: lot.ratePerUnit,
        };
      });

      const response = await jwtAxios.post(ENDPOINTS.PURCHASE_BULK, {
        purchases: purchasesPayload,
      });

      const { created = [], errors: lotErrors = [] } = response.data?.result ?? {};
      const successCount: number = created.length;

      if (successCount > 0) {
        message.success(`${successCount} lot${successCount > 1 ? 's' : ''} added successfully via Quick Purchase`);
        setLotFieldErrors({});
        navigate('/purchase');
      } else {
        // Map business-logic errors back to the lotNo field of the failing lot
        if (lotErrors.length > 0) {
          const newFieldErrors: Record<number, Record<string, string>> = {};
          lotErrors.forEach((e: { index: number; lotNo: string; message: string }) => {
            newFieldErrors[e.index] = { ...(newFieldErrors[e.index] ?? {}), lotNo: e.message };
          });
          setLotFieldErrors(newFieldErrors);
        }
        message.error('No purchases were saved. Please fix the errors shown on each lot.');
      }
    } catch (err: any) {
      const responseData = err.response?.data;
      const rawErrors: Record<string, string> = responseData?.errors ?? {};

      if (Object.keys(rawErrors).length > 0) {
        // Map Zod field errors (path: purchases.N.fieldName) inline to each lot
        const newLotFieldErrors: Record<number, Record<string, string>> = {};
        Object.entries(rawErrors).forEach(([path, errMsg]) => {
          const lotMatch = path.match(/^purchases\.([0-9]+)\.(.+)$/);
          if (lotMatch) {
            const idx = parseInt(lotMatch[1], 10);
            const field = lotMatch[2];
            newLotFieldErrors[idx] = { ...(newLotFieldErrors[idx] ?? {}), [field]: String(errMsg) };
          }
        });
        if (Object.keys(newLotFieldErrors).length > 0) {
          setLotFieldErrors(newLotFieldErrors);
        }
        message.error(responseData?.message || 'Please fix the highlighted fields');
      } else {
        message.error(responseData?.message || 'Failed to create quick purchase');
      }
    } finally {
      setLoading(false);
    }
  };

  const totalLotsAmount = lots.reduce((acc, lot) => {
    const lotGoodsTotal = (lot.unit === 'KG' || lot.rateType === 'KG')
      ? (lot.quantity ?? 0) * (lot.ratePerUnit ?? 0)
      : (lot.bags ?? 0) * (lot.ratePerUnit ?? 0);
    return acc + lotGoodsTotal + (lot.extraCharges ?? 0);
  }, 0);

  return (
    <Spin spinning={loading}>
      <AppContainer
        title="Quick Purchase (Local Market)"
        headerAction={
          <Space>
            <Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/purchase')}>
              Back to Purchase Orders
            </Button>
            <Button
              type="primary"
              icon={<CheckCircleOutlined />}
              style={{ backgroundColor: '#1677ff' }}
              onClick={() => form.submit()}
            >
              Submit Quick Purchase
            </Button>
          </Space>
        }
      >
        <Row gutter={24}>
          <Col xs={24} lg={24}>
            <Form form={form} layout="vertical" onFinish={handleSubmit}>
              {/* Supplier & Header Card */}
              <Card
                title={
                  <Space>
                    <ShoppingCartOutlined style={{ color: '#1677ff' }} />
                    <span>Supplier & Bill Information</span>
                  </Space>
                }
                style={{ marginBottom: 20 }}
              >
                <Row gutter={16}>
                  <Col xs={24} md={12}>
                    <Form.Item
                      label="Market Supplier Name"
                      name="cashSupplierName"
                      rules={[{ required: true, message: 'Enter market vendor/supplier name' }]}
                    >
                      <Input placeholder="e.g. Local Market Vendor A, Cash Supplier" />
                    </Form.Item>
                  </Col>

                  <Col xs={24} sm={12} md={12}>
                    <Form.Item
                      label="Bill No"
                      name="billNo"
                      rules={[{ required: true, message: 'Please enter Bill No' }]}
                    >
                      <Input placeholder="e.g. CASH-BILL-101" />
                    </Form.Item>
                  </Col>

                  <Col xs={24} sm={12} md={8}>
                    <Form.Item
                      label="Purchase Date"
                      name="purchaseDate"
                      rules={[{ required: true, message: 'Select purchase date' }]}
                    >
                      <DatePicker
                        style={{ width: '100%' }}
                        disabledDate={(current) => current && current > dayjs().endOf('day')}
                      />
                    </Form.Item>
                  </Col>

                  <Col xs={24} sm={12} md={8}>
                    <Form.Item label="Arrival Date" name="arrivalDate">
                      <DatePicker style={{ width: '100%' }} />
                    </Form.Item>
                  </Col>

                  <Col xs={24} md={8}>
                    <Form.Item label="Remarks / Notes" name="remarks">
                      <Input.TextArea rows={1} placeholder="Optional purchase note..." />
                    </Form.Item>
                  </Col>

                  <Col xs={24} sm={12} md={8}>
                    <Form.Item label="Expense Payment Mode" name="expensePaymentMode">
                      <Select options={paymentModes} placeholder="Select Payment Mode" />
                    </Form.Item>
                  </Col>

                  <Col xs={24} sm={12} md={8}>
                    <Form.Item label="Expense Amount" name="expenseAmount">
                      <InputNumber style={{ width: '100%' }} min={0} step={0.01} />
                    </Form.Item>
                  </Col>
                </Row>
              </Card>

              {/* Vegetable & Item Details Section */}
              <Divider orientation="horizontal" titlePlacement="left" style={{ margin: '4px 0 12px', fontSize: 13, color: '#52c41a', fontWeight: 600 }}>
                <Space>
                  <WalletOutlined /> Vegetable & Quantity Details
                </Space>
              </Divider>

              {lots.map((lot, idx) => (
                <LotRowForm
                  key={lot.id}
                  lot={lot}
                  index={idx}
                  purchaseUnits={meta.purchaseUnits}
                  vegetables={vegetables}
                  canDelete={lots.length > 1}
                  onChange={updateLot}
                  onDelete={removeLot}
                  fieldErrors={lotFieldErrors[idx]}
                  onFieldErrorClear={clearLotFieldError}
                />
              ))}

              <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 16 }}>
                <div style={{ padding: '8px 16px', background: '#f6ffed', border: '1px solid #b7eb8f', borderRadius: 8 }}>
                  <span style={{ fontSize: 14, color: '#595959', marginRight: 8 }}>Total Amount:</span>
                  <span style={{ fontSize: 18, fontWeight: 700, color: '#52c41a' }}>₹{totalLotsAmount.toFixed(2)}</span>
                </div>
              </div>

              <Button
                type="dashed"
                block
                icon={<PlusOutlined />}
                onClick={addLot}
                style={{ marginBottom: 16, borderColor: '#52c41a', color: '#52c41a' }}
              >
                Add Another Vegetable
              </Button>

            </Form>
          </Col>

          {/* Live Summary Sidebar */}
          {/* <Col xs={24} lg={8}>
                        <Card
                            title={
                                <Text strong style={{ fontSize: 16 }}>
                                    Purchase Action
                                </Text>
                            }
                            style={{ position: 'sticky', top: 16, borderColor: '#d9d9d9' }}
                        >
                            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                                {lots.length > 0 && (
                                    <div style={{ marginBottom: 16 }}>
                                        <Text type="secondary">Total Lots Added: </Text>
                                        <Text strong style={{ fontSize: 18 }}>{lots.length}</Text>
                                    </div>
                                )}
                                <Button
                                    type="primary"
                                    size="large"
                                    icon={<PlusOutlined />}
                                    style={{ marginTop: 12, width: '100%', backgroundColor: '#1677ff' }}
                                    onClick={() => form.submit()}
                                >
                                    Confirm Quick Purchase
                                </Button>
                            </div>
                        </Card>
                    </Col> */}
        </Row>
      </AppContainer>
    </Spin>
  );
};

export default QuickPurchase;
