import React, { useEffect, useState, useMemo } from 'react';
import {
  Modal,
  Button,
  Table,
  Input,
  InputNumber,
  DatePicker,
  Card,
  Row,
  Col,
  Tag,
  Typography,
  Spin,
  Popconfirm,
  message,
  Tooltip,
} from 'antd';
import {
  FormOutlined,
  PrinterOutlined,
  SaveOutlined,
  PlusOutlined,
  DeleteOutlined,
  UndoOutlined,
} from '@ant-design/icons';
import dayjs, { Dayjs } from 'dayjs';
import jwtAxios from '../../api/axiosInstance';
import { ENDPOINTS } from '../../api/endpoints';

const { Text } = Typography;

export interface CustomLineItem {
  id: string;
  date: string;
  invoiceNo: string;
  channel: string;
  buyer: string;
  quantity: number;
  rate: number;
  total: number;
}

interface CustomPattiModalProps {
  open: boolean;
  onClose: () => void;
  purchaseId: string | null;
  lotNo?: string;
  onSuccess?: () => void;
}

export const CustomPattiModal: React.FC<CustomPattiModalProps> = ({
  open,
  onClose,
  purchaseId,
  lotNo,
  onSuccess,
}) => {
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [downloading, setDownloading] = useState(false);
  const [isCustomSaved, setIsCustomSaved] = useState(false);

  // Header & arrival info
  const [arrivalInfo, setArrivalInfo] = useState<any>(null);
  const [pattiNo, setPattiNo] = useState<string>('');
  const [settlementDate, setSettlementDate] = useState<Dayjs | null>(dayjs());

  // Editable items
  const [items, setItems] = useState<CustomLineItem[]>([]);

  // Deductions
  const [commissionPercent, setCommissionPercent] = useState<number>(4.0);
  const [freightDeducted, setFreightDeducted] = useState<number>(0);
  const [extraFreightDeducted, setExtraFreightDeducted] = useState<number>(0);
  const [unloadingDeducted, setUnloadingDeducted] = useState<number>(0);
  const [associationDeducted, setAssociationDeducted] = useState<number>(0);
  const [miscDeducted, setMiscDeducted] = useState<number>(0);
  const [remarks, setRemarks] = useState<string>('');

  // Stored original and custom data
  const [originalData, setOriginalData] = useState<any>(null);
  const [savedCustomData, setSavedCustomData] = useState<any>(null);
  const [activeDataSource, setActiveDataSource] = useState<'original' | 'saved_custom'>('original');

  const populateFields = (sourceData: any) => {
    if (!sourceData) return;
    const arrival = sourceData.arrival || sourceData.purchase;
    setArrivalInfo(arrival);

    setPattiNo(sourceData.pattiNo || (arrival?.lotNo ? `PATTI-${arrival.lotNo}` : ''));
    setSettlementDate(
      sourceData.settlementDate
        ? dayjs(sourceData.settlementDate)
        : arrival?.arrivalDate
          ? dayjs(arrival.arrivalDate)
          : dayjs()
    );

    // Parse items
    let loadedItems: CustomLineItem[] = [];
    let rawItems = sourceData.items;
    if (typeof rawItems === 'string') {
      try {
        rawItems = JSON.parse(rawItems);
      } catch {
        rawItems = [];
      }
    }

    if (Array.isArray(rawItems)) {
      loadedItems = rawItems.map((it: any, idx: number) => ({
        id: it.id || `item-${idx + 1}`,
        date: it.date
          ? dayjs(it.date).format('YYYY-MM-DD')
          : it.invoiceDate
            ? dayjs(it.invoiceDate).format('YYYY-MM-DD')
            : dayjs().format('YYYY-MM-DD'),
        invoiceNo: it.invoiceNo || it.sale?.invoiceNo || '-',
        channel: it.channel === 'RETAIL' ? 'Retail' : (it.channel || 'Wholesale'),
        buyer: it.buyer || it.buyerName || it.sale?.customer?.name || it.sale?.walkInName || '',
        quantity: Number(it.quantity ?? it.netQuantity ?? 0),
        rate: Number(it.rate !== undefined ? it.rate : (it.sellingRate ?? 0)),
        total: Number(it.total !== undefined ? it.total : (it.netTotal ?? 0)),
      }));
    }
    setItems(loadedItems);

    // Deductions
    setCommissionPercent(Number(sourceData.commissionPercent ?? 4.0));
    setFreightDeducted(Number(sourceData.freightDeducted ?? 0));
    setExtraFreightDeducted(Number(sourceData.extraFreightDeducted ?? 0));
    setUnloadingDeducted(Number(sourceData.unloadingDeducted ?? 0));
    setAssociationDeducted(Number(sourceData.associationDeducted ?? 0));
    setMiscDeducted(Number(sourceData.miscDeducted ?? 0));
    setRemarks(sourceData.remarks || '');
  };

  // Fetch data on open
  useEffect(() => {
    if (!open || !purchaseId) return;
    loadCustomPattiData();
  }, [open, purchaseId]);

  const loadCustomPattiData = async () => {
    if (!purchaseId) return;
    setLoading(true);
    try {
      const res = await jwtAxios.get(ENDPOINTS.ARRIVALS_CUSTOM_PATTI_BY_PURCHASE(purchaseId));
      if (res.data?.success) {
        const responseData = res.data;
        // Unwrap whether returned flattened or nested in res.data.data
        const inner =
          responseData.data &&
            typeof responseData.data === 'object' &&
            ('originalData' in responseData.data || 'items' in responseData.data)
            ? responseData.data
            : null;

        const isSaved = Boolean(responseData.isCustomSaved ?? inner?.isCustomSaved);
        const orig =
          responseData.originalData ||
          inner?.originalData ||
          (inner?.items ? inner : null) ||
          responseData.data;
        const custom = responseData.savedCustomData || inner?.savedCustomData || null;
        const preview = responseData.preview || inner?.preview || null;

        if (orig) {
          if (!orig.arrival && (preview?.arrival || inner?.arrival)) {
            orig.arrival = preview?.arrival || inner?.arrival;
          }
        }

        setIsCustomSaved(isSaved);
        setOriginalData(orig);
        setSavedCustomData(custom);

        // Always load the original data so the user begins editing from the original records!
        if (orig) {
          populateFields(orig);
        }
        setActiveDataSource('original');
      }
    } catch (err: any) {
      console.error('Failed to load custom patti data:', err);
      message.error(err?.response?.data?.message || 'Failed to load custom patti data.');
    } finally {
      setLoading(false);
    }
  };

  const switchToOriginal = () => {
    if (originalData) {
      populateFields(originalData);
      setActiveDataSource('original');
      message.info('Loaded original data into editor.');
    }
  };

  const switchToSavedCustom = () => {
    if (savedCustomData) {
      populateFields(savedCustomData);
      setActiveDataSource('saved_custom');
      message.info('Loaded previously saved modified version.');
    }
  };

  // Real-time calculations
  const { totalWeightSold, grossSalesTotal, commissionAmount, totalDeductions, netPayable } = useMemo(() => {
    let weight = 0;
    let gross = 0;
    items.forEach((it) => {
      weight += Number(it.quantity || 0);
      gross += Number(it.total || 0);
    });

    const comm = Number(((gross * (commissionPercent || 0)) / 100).toFixed(2));
    const deductions = Number(
      (
        comm +
        Number(freightDeducted || 0) +
        Number(extraFreightDeducted || 0) +
        Number(unloadingDeducted || 0) +
        Number(associationDeducted || 0) +
        Number(miscDeducted || 0)
      ).toFixed(2)
    );
    const net = Number((gross - deductions).toFixed(2));

    return {
      totalWeightSold: weight,
      grossSalesTotal: gross,
      commissionAmount: comm,
      totalDeductions: deductions,
      netPayable: net,
    };
  }, [
    items,
    commissionPercent,
    freightDeducted,
    extraFreightDeducted,
    unloadingDeducted,
    associationDeducted,
    miscDeducted,
  ]);

  // Update a field on a specific item
  const handleItemChange = (id: string, field: keyof CustomLineItem, value: any) => {
    setItems((prev) =>
      prev.map((item) => {
        if (item.id !== id) return item;
        const updated = { ...item, [field]: value };
        if (field === 'quantity' || field === 'rate') {
          const q = field === 'quantity' ? Number(value || 0) : item.quantity;
          const r = field === 'rate' ? Number(value || 0) : item.rate;
          updated.total = Number((q * r).toFixed(2));
        }
        return updated;
      })
    );
  };

  // Add new item row
  const handleAddItem = () => {
    const newItem: CustomLineItem = {
      id: `new-${Date.now()}`,
      date: dayjs().format('YYYY-MM-DD'),
      invoiceNo: `INV-MANUAL-${items.length + 1}`,
      channel: 'Wholesale',
      buyer: '',
      quantity: 0,
      rate: 0,
      total: 0,
    };
    setItems((prev) => [...prev, newItem]);
  };

  // Delete item row
  const handleDeleteItem = (id: string) => {
    setItems((prev) => prev.filter((it) => it.id !== id));
  };

  // Save modified version to backend
  const handleSave = async (silent = false) => {
    if (!purchaseId) return false;
    setSaving(true);
    try {
      const payload = {
        purchaseId: Number(purchaseId),
        pattiNo: pattiNo.trim(),
        settlementDate: settlementDate ? settlementDate.format('YYYY-MM-DD') : dayjs().format('YYYY-MM-DD'),
        items,
        commissionPercent,
        freightDeducted,
        extraFreightDeducted,
        associationDeducted,
        unloadingDeducted,
        miscDeducted,
        advanceAdjusted: 0,
        remarks,
      };

      const res = await jwtAxios.post(ENDPOINTS.ARRIVALS_CUSTOM_PATTI, payload);
      if (res.data?.success) {
        setIsCustomSaved(true);
        if (!silent) {
          message.success(res?.data?.message || 'Modified Patti version stored successfully without changing original records!');
        }
        onSuccess?.();
        return true;
      }
      return false;
    } catch (err: any) {
      message.error(err?.response?.data?.message || 'Failed to save modified patti.');
      return false;
    } finally {
      setSaving(false);
    }
  };

  // Download / Print PDF of custom patti
  const handleDownloadPdf = async () => {
    if (!purchaseId) return;
    setDownloading(true);
    try {
      // First save changes so PDF has latest data
      await handleSave(true);

      const res = await jwtAxios.get(ENDPOINTS.ARRIVALS_CUSTOM_PATTI_PDF(purchaseId), {
        responseType: 'blob',
      });
      const url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/pdf' }));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `Modified-Patti-${pattiNo || lotNo || purchaseId}.pdf`);
      document.body.appendChild(link);
      link.click();
      link.remove();
      message.success('Modified Patti PDF generated and downloaded!');
    } catch (err: any) {
      message.error('Failed to download Modified Patti PDF.');
    } finally {
      setDownloading(false);
    }
  };

  // Reset to original data
  const handleResetToOriginal = async () => {
    if (!purchaseId) return;
    setLoading(true);
    try {
      // If custom version was already saved in DB, delete it
      if (isCustomSaved) {
        await jwtAxios.delete(ENDPOINTS.ARRIVALS_CUSTOM_PATTI_BY_PURCHASE(purchaseId));
      }
      message.success('Reverted to original accounting records.');
      setIsCustomSaved(false);
      await loadCustomPattiData();
      onSuccess?.();
    } catch (err: any) {
      message.error(err?.response?.data?.message || 'Failed to reset.');
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      title: '#',
      key: 'index',
      width: 45,
      render: (_: any, __: any, idx: number) => <span className="text-gray-400 text-xs font-semibold">{idx + 1}</span>,
    },
    {
      title: 'Date',
      dataIndex: 'date',
      key: 'date',
      width: 130,
      render: (d: string, record: CustomLineItem) => (
        <DatePicker
          size="small"
          className="w-full text-xs"
          format="DD/MM/YYYY"
          value={d ? dayjs(d) : null}
          onChange={(val) => handleItemChange(record.id, 'date', val ? val.format('YYYY-MM-DD') : '')}
        />
      ),
    },
    {
      title: 'Invoice #',
      dataIndex: 'invoiceNo',
      key: 'invoiceNo',
      width: 140,
      render: (inv: string, record: CustomLineItem) => (
        <Input
          size="small"
          className="text-xs"
          value={inv}
          onChange={(e) => handleItemChange(record.id, 'invoiceNo', e.target.value)}
        />
      ),
    },
    {
      title: 'Channel',
      dataIndex: 'channel',
      key: 'channel',
      width: 110,
      render: (ch: string, record: CustomLineItem) => (
        <Input
          size="small"
          className="text-xs"
          value={ch}
          onChange={(e) => handleItemChange(record.id, 'channel', e.target.value)}
        />
      ),
    },
    {
      title: 'Buyer Name',
      dataIndex: 'buyer',
      key: 'buyer',
      width: 160,
      render: (buyer: string, record: CustomLineItem) => (
        <Input
          size="small"
          className="text-xs font-medium"
          placeholder="Buyer name"
          value={buyer}
          onChange={(e) => handleItemChange(record.id, 'buyer', e.target.value)}
        />
      ),
    },
    {
      title: 'Qty (KG)',
      dataIndex: 'quantity',
      key: 'quantity',
      width: 110,
      render: (qty: number, record: CustomLineItem) => (
        <InputNumber
          size="small"
          className="w-full text-xs font-semibold"
          min={0}
          step={1}
          value={qty}
          onChange={(val) => handleItemChange(record.id, 'quantity', val ?? 0)}
        />
      ),
    },
    {
      title: 'Rate / KG (₹)',
      dataIndex: 'rate',
      key: 'rate',
      width: 110,
      render: (rate: number, record: CustomLineItem) => (
        <InputNumber
          size="small"
          className="w-full text-xs font-semibold"
          min={0}
          step={0.5}
          value={rate}
          onChange={(val) => handleItemChange(record.id, 'rate', val ?? 0)}
        />
      ),
    },
    {
      title: 'Total (₹)',
      dataIndex: 'total',
      key: 'total',
      width: 120,
      render: (tot: number, record: CustomLineItem) => (
        <InputNumber
          size="small"
          className="w-full text-xs font-bold text-emerald-800"
          min={0}
          value={tot}
          onChange={(val) => handleItemChange(record.id, 'total', val ?? 0)}
        />
      ),
    },
    {
      title: '',
      key: 'actions',
      width: 45,
      render: (_: any, record: CustomLineItem) => (
        <Tooltip title="Remove line item">
          <Button
            type="text"
            danger
            size="small"
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteItem(record.id)}
          />
        </Tooltip>
      ),
    },
  ];

  return (
    <Modal
      title={
        <div className="flex items-center justify-between pr-6 border-b pb-3">
          <div className="flex items-center gap-2.5">
            <div className="w-8 h-8 rounded-full bg-purple-100 flex items-center justify-center text-purple-700 font-bold text-base">
              <FormOutlined />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <h3 className="text-base font-bold text-gray-900 leading-tight m-0">
                  Custom / Modified Commission Patti
                </h3>
                {activeDataSource === 'original' ? (
                  <Tag color="cyan" className="font-semibold text-[11px] m-0">
                    Original Records Loaded for Editing
                  </Tag>
                ) : (
                  <Tag color="purple" className="font-semibold text-[11px] m-0">
                    Saved Modified Version Loaded
                  </Tag>
                )}
              </div>
              <span className="text-xs text-gray-500 font-normal">
                Edit and share custom patti slips with clients/third parties without affecting original books
              </span>
            </div>
          </div>
          {(arrivalInfo?.lotNo || lotNo) && (
            <Tag color="geekblue" className="text-sm font-bold px-3 py-1 rounded-full m-0">
              Lot {arrivalInfo?.lotNo || lotNo}
            </Tag>
          )}
        </div>
      }
      open={open}
      onCancel={onClose}
      footer={null}
      width={1040}
      centered
      destroyOnHidden
      styles={{
        body: {
          maxHeight: 'calc(88vh - 80px)',
          overflowY: 'auto',
          padding: '16px 20px',
        },
      }}
    >
      {loading ? (
        <div className="py-20 text-center">
          <Spin size="large" />
          <div className="mt-3 text-gray-600 font-medium">Loading lot details & sales lines...</div>
        </div>
      ) : (
        <div>
          {/* DATA SOURCE SWITCHER BAR */}
          <div className="flex items-center justify-between mb-3 bg-slate-50 border border-slate-200 rounded-lg px-3 py-1.5">
            <span className="text-xs text-slate-700 font-semibold flex items-center gap-1.5">
              <span className={`w-2 h-2 rounded-full ${activeDataSource === 'original' ? 'bg-cyan-500' : 'bg-purple-500'}`} />
              Active Baseline: {activeDataSource === 'original' ? 'Original Sales & Deductions' : 'Previously Saved Custom Copy'}
            </span>
            <div className="flex items-center gap-2">
              <Button
                size="small"
                type={activeDataSource === 'original' ? 'primary' : 'default'}
                onClick={switchToOriginal}
                className={activeDataSource === 'original' ? 'bg-cyan-600 text-xs font-medium' : 'text-xs'}
              >
                Reload Original Data
              </Button>
              {savedCustomData && (
                <Button
                  size="small"
                  type={activeDataSource === 'saved_custom' ? 'primary' : 'default'}
                  onClick={switchToSavedCustom}
                  className={activeDataSource === 'saved_custom' ? 'bg-purple-600 text-xs font-medium' : 'text-xs'}
                >
                  Load Saved Custom Draft
                </Button>
              )}
            </div>
          </div>

          {/* LOT OVERVIEW CARDS */}
          <div className="bg-gradient-to-r from-purple-50/80 to-indigo-50/50 border border-purple-200/80 rounded-xl p-3.5 mb-4 shadow-xs">
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
              <div>
                <span className="text-xs font-semibold text-gray-500 uppercase tracking-wider block">Vegetable Item</span>
                <span className="text-sm font-bold text-gray-900 block mt-0.5">
                  {arrivalInfo?.vegetable?.name || '—'}
                </span>
                {(arrivalInfo?.supplier?.name || arrivalInfo?.cashSupplierName || arrivalInfo?.agentName) && (
                  <span className="text-xs text-purple-900 font-medium truncate block mt-0.5">
                    {arrivalInfo?.supplier?.name || arrivalInfo?.cashSupplierName || arrivalInfo?.agentName}
                  </span>
                )}
              </div>
              <div>
                <span className="text-xs font-semibold text-gray-500 uppercase tracking-wider block">Inward Quantity</span>
                <span className="text-sm font-bold text-gray-900 block mt-0.5">
                  {Number(arrivalInfo?.quantity || 0).toFixed(2)} KG
                </span>
                {arrivalInfo?.bags && Number(arrivalInfo.bags) > 0 && (
                  <span className="text-xs text-gray-500 block">({Number(arrivalInfo.bags)} Bags)</span>
                )}
              </div>
              <div>
                <span className="text-xs font-semibold text-gray-500 uppercase tracking-wider block">Patti Slip Number</span>
                <Input
                  size="small"
                  className="font-bold text-xs mt-1"
                  value={pattiNo}
                  onChange={(e) => setPattiNo(e.target.value)}
                  placeholder="Patti Slip #"
                />
              </div>
              <div>
                <span className="text-xs font-semibold text-gray-500 uppercase tracking-wider block">Settlement Date</span>
                <DatePicker
                  size="small"
                  className="w-full text-xs mt-1"
                  format="DD/MM/YYYY"
                  value={settlementDate}
                  onChange={(val) => setSettlementDate(val)}
                />
              </div>
            </div>
          </div>

          {/* EDITABLE SALES REALIZATION BREAKDOWN */}
          <div className="mb-4 bg-white border border-gray-200 rounded-xl p-3.5 shadow-xs">
            <div className="flex items-center justify-between mb-2.5">
              <div className="flex items-center gap-2">
                <span className="font-bold text-sm text-gray-800">Sales Realization Line Items (Editable)</span>
                <Tag color="purple" className="rounded-full px-2 text-xs font-semibold">
                  {items.length} Rows
                </Tag>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-xs text-gray-600 mr-2">
                  Total Sold: <strong className="text-gray-900">{totalWeightSold.toFixed(2)} KG</strong> | Gross:{' '}
                  <strong className="text-emerald-800">
                    ₹ {grossSalesTotal.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                  </strong>
                </span>
                <Button
                  size="small"
                  type="dashed"
                  icon={<PlusOutlined />}
                  onClick={handleAddItem}
                  className="text-purple-700 border-purple-300 font-medium"
                >
                  Add Row
                </Button>
              </div>
            </div>

            <Table
              size="small"
              columns={columns}
              dataSource={items}
              rowKey="id"
              scroll={{ y: 220, x: 800 }}
              pagination={false}
              locale={{ emptyText: 'No line items. Click "Add Row" to create custom realization entries.' }}
            />
          </div>

          {/* DEDUCTIONS & COMMISSION EDITABLE CARD */}
          <Card size="small" className="bg-gray-50/80 mb-4 border border-gray-200 rounded-xl shadow-xs">
            <Row gutter={16}>
              <Col xs={24} md={12}>
                <div className="space-y-2 text-sm pr-2">
                  <div className="flex justify-between py-1 border-b border-gray-200/60 font-semibold text-gray-800">
                    <span>Gross Sales Total:</span>
                    <span>₹ {grossSalesTotal.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
                  </div>

                  <div className="flex justify-between items-center text-red-600">
                    <span className="flex items-center gap-1.5 font-medium">
                      Commission (
                      <InputNumber
                        size="small"
                        min={0}
                        max={100}
                        step={0.5}
                        value={commissionPercent}
                        style={{ width: 65 }}
                        className="font-semibold text-center"
                        onChange={(val) => setCommissionPercent(val ?? 0)}
                      />
                      %):
                    </span>
                    <span className="font-semibold">- ₹ {commissionAmount.toFixed(2)}</span>
                  </div>

                  <div className="flex justify-between items-center text-red-600">
                    <span>Freight:</span>
                    <InputNumber
                      size="small"
                      min={0}
                      step={10}
                      value={freightDeducted}
                      style={{ width: 100 }}
                      className="text-right"
                      onChange={(val) => setFreightDeducted(val ?? 0)}
                    />
                  </div>

                  <div className="flex justify-between items-center text-red-600">
                    <span>Unloading / Coolie:</span>
                    <InputNumber
                      size="small"
                      min={0}
                      step={10}
                      value={unloadingDeducted}
                      style={{ width: 100 }}
                      className="text-right"
                      onChange={(val) => setUnloadingDeducted(val ?? 0)}
                    />
                  </div>

                  <div className="flex justify-between items-center text-red-600">
                    <span>Association Fee:</span>
                    <InputNumber
                      size="small"
                      min={0}
                      step={10}
                      value={associationDeducted}
                      style={{ width: 100 }}
                      className="text-right"
                      onChange={(val) => setAssociationDeducted(val ?? 0)}
                    />
                  </div>

                  <div className="flex justify-between items-center text-red-600">
                    <span>Extra Freight:</span>
                    <InputNumber
                      size="small"
                      min={0}
                      step={10}
                      value={extraFreightDeducted}
                      style={{ width: 100 }}
                      className="text-right"
                      onChange={(val) => setExtraFreightDeducted(val ?? 0)}
                    />
                  </div>

                  <div className="flex justify-between items-center text-red-600">
                    <span>Misc Fee:</span>
                    <InputNumber
                      size="small"
                      min={0}
                      step={10}
                      value={miscDeducted}
                      style={{ width: 100 }}
                      className="text-right"
                      onChange={(val) => setMiscDeducted(val ?? 0)}
                    />
                  </div>

                  <div className="flex justify-between pt-1 border-t border-gray-200 font-semibold text-gray-700 text-xs">
                    <span>Total Deductions:</span>
                    <span>- ₹ {totalDeductions.toFixed(2)}</span>
                  </div>
                </div>
              </Col>

              <Col xs={24} md={12} className="mt-3 md:mt-0 md:border-l md:pl-4 flex flex-col justify-center">
                <div className="bg-gradient-to-br from-emerald-100 to-teal-50 p-5 rounded-xl text-center border border-emerald-300 shadow-xs mb-3">
                  <Text type="secondary" className="text-xs uppercase font-bold text-emerald-800 tracking-wider">
                    Calculated Net Payable
                  </Text>
                  <div className="text-3xl font-extrabold text-emerald-950 mt-1.5 tracking-tight">
                    ₹ {netPayable.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                  </div>
                </div>

                <div className="bg-white p-3 rounded-lg border border-gray-200">
                  <label className="text-xs font-semibold text-gray-600 block mb-1">Custom Patti Notes / Remarks</label>
                  <Input.TextArea
                    rows={2}
                    placeholder="Optional notes to appear or save with this modified patti"
                    value={remarks}
                    onChange={(e) => setRemarks(e.target.value)}
                  />
                </div>
              </Col>
            </Row>
          </Card>

          {/* FOOTER ACTIONS */}
          <div className="flex items-center justify-between pt-3 border-t">
            <Popconfirm
              title="Reset to Original Records?"
              description="This will clear custom edits and restore the numbers from original accounting records."
              okText="Yes, Reset"
              cancelText="Cancel"
              okButtonProps={{ danger: true }}
              onConfirm={handleResetToOriginal}
            >
              <Button icon={<UndoOutlined />} danger type="text">
                Reset to Original
              </Button>
            </Popconfirm>

            <div className="flex items-center gap-2">
              <Button onClick={onClose}>Close</Button>

              <Button
                icon={<PrinterOutlined />}
                loading={downloading}
                onClick={handleDownloadPdf}
                className="text-emerald-700 border-emerald-400 hover:bg-emerald-50 font-semibold"
              >
                Print / Download Modified PDF
              </Button>

              <Button
                type="primary"
                icon={<SaveOutlined />}
                loading={saving}
                onClick={() => handleSave(false)}
                className="bg-purple-600 hover:bg-purple-500 font-semibold px-5"
              >
                Save Modified Version
              </Button>
            </div>
          </div>
        </div>
      )}
    </Modal>
  );
};

export default CustomPattiModal;
