// Component that displays and formats printable, itemized commercial customer invoices with multi-tab layouts.
import React, { useState, useEffect } from 'react';
import { useParams, useSearchParams } from 'react-router-dom';import api from "../api"; 
import logo from "../assets/logo.png"; 
const FullInvoice = () => {
  const { id } = useParams();
  const [data, setData] = useState(null);
  const [searchParams] = useSearchParams();

  const [activeInvoiceTab, setActiveInvoiceTab] = useState(0);

  const [extraRows, setExtraRows] = useState([
    { label: "Cleaning Charge", amount: 0 },
    { label: "Damage Charges", amount: 0 },
    { label: "Excess KM Charge", amount: 0 },
    { label: "Toll / Salik", amount: 0 }
  ]);

  const [advancePaid, setAdvancePaid] = useState(0);
const addRow = () => {
  setExtraRows([...extraRows, { label: "New Charge", amount: 0 }]);
};

const removeRow = (index) => {
  setExtraRows(extraRows.filter((_, i) => i !== index));
};

const updateRow = (index, field, val) => {
  const updated = [...extraRows];
  updated[index][field] = val;
  setExtraRows(updated);
};
  // ✅ FETCH DATA
  useEffect(() => {
    api.get(`/bookings/invoice/${id}`).then(res => {
      console.log("API RESPONSE:", res);  // 👈 MUST print
      const d = res.data;
      console.log("FULL DATA:", d); 
      setData(d);
      setAdvancePaid(parseFloat(d.advance_paid || 0));
    }).catch(err => console.error("Invoice Error:", err));
  }, [id]);

  // ✅ DYNAMICALLY POPULATE EXTRAROWS FOR ACTIVE TAB
  useEffect(() => {
    if (!data) return;

    let activeSecCharges = { cleaning: 0, damage: 0, excess_km: 0, salik: 0 };
    if (data.section_charges) {
      try {
        const parsedSec = typeof data.section_charges === "string" ? JSON.parse(data.section_charges) : data.section_charges;
        if (Array.isArray(parsedSec) && parsedSec[activeInvoiceTab]) {
          activeSecCharges = {
            cleaning: parseFloat(parsedSec[activeInvoiceTab].cleaning || 0),
            damage: parseFloat(parsedSec[activeInvoiceTab].damage || 0),
            excess_km: parseFloat(parsedSec[activeInvoiceTab].excess_km || 0),
            salik: parseFloat(parsedSec[activeInvoiceTab].salik || 0)
          };
        } else if (activeInvoiceTab === 0) {
          activeSecCharges = {
            cleaning: parseFloat(data.cleaning_charges || 0),
            damage: parseFloat(data.damage_charges || 0),
            excess_km: parseFloat(data.excess_km_charges || 0),
            salik: parseFloat(data.salik_charges || 0)
          };
        }
      } catch (e) {
        console.error("Error parsing section_charges:", e);
      }
    } else if (activeInvoiceTab === 0) {
      activeSecCharges = {
        cleaning: parseFloat(data.cleaning_charges || 0),
        damage: parseFloat(data.damage_charges || 0),
        excess_km: parseFloat(data.excess_km_charges || 0),
        salik: parseFloat(data.salik_charges || 0)
      };
    }

    const defaultCharges = [
      { label: "Cleaning Charge", amount: activeSecCharges.cleaning },
      { label: "Damage Charges", amount: activeSecCharges.damage },
      { label: "Excess KM Charge", amount: activeSecCharges.excess_km },
      { label: "Toll / Salik", amount: activeSecCharges.salik }
    ];

    let additional = [];
    if (data.additional_charges) {
      try {
        const parsedAdd = typeof data.additional_charges === "string" ? JSON.parse(data.additional_charges) : data.additional_charges;
        if (Array.isArray(parsedAdd) && parsedAdd[activeInvoiceTab]) {
          additional = parsedAdd[activeInvoiceTab].map(item => ({
            label: item.name || item.label || "Extra Charge",
            amount: parseFloat(item.amount || 0)
          }));
        }
      } catch (err) {
        console.error("Additional charges parse error:", err);
      }
    }

    setExtraRows([...defaultCharges, ...additional]);
  }, [data, activeInvoiceTab]);

  let numberOfInvoices = 0;
  let diffDays = 0;

  if (data) {
    const start = new Date(data.start_date);
    const end = new Date(data.end_date);

    diffDays = Math.ceil(Math.abs(end - start) / (1000 * 60 * 60 * 24)) || 1;
    numberOfInvoices = Math.ceil(diffDays / 30);
  }


  useEffect(() => {
    if (!data) return;

    const tabParam = parseInt(searchParams.get("tab"));
    const validTab = isNaN(tabParam) ? 0 : tabParam;

    setActiveInvoiceTab(validTab < numberOfInvoices ? validTab : 0);

  }, [data, searchParams, numberOfInvoices]);

  if (!data) return <div style={{textAlign:'center',marginTop:'50px'}}>Loading...</div>;

  // ✅ MAIN CALCULATIONS
  const start = new Date(data.start_date);
  const end = new Date(data.end_date);

  const startDay = (activeInvoiceTab * 30) + 1;
  const endDay = Math.min((activeInvoiceTab + 1) * 30, diffDays);

  const currentDays = Math.max(0, endDay - startDay + 1);
  const isLastInvoice = activeInvoiceTab === numberOfInvoices - 1;

  const basePerDay = parseFloat(data.base_price || 0);
  const base = basePerDay * currentDays;

  const extraTotal = extraRows.reduce((sum, r) => sum + parseFloat(r.amount || 0), 0);

  const subTotal = base + extraTotal;
  const gstPercent = parseFloat(data.tax_amount || 5);

  const gstAmount = (subTotal * gstPercent) / 100;

  const total = subTotal + gstAmount;
  const finalAdvance = isLastInvoice ? advancePaid : 0;
  const balance = (total - finalAdvance).toFixed(2);
return (
    <div className="invoice-wrapper">
      {/* Control Panel */}
      <div className="no-print" style={{position: 'fixed', top: '20px', right: '20px', display: 'flex', gap: '10px', zIndex: 100}}>
      </div>

      <div className="invoice-container">
        {/* Header Section */}
        <div className="receipt-header-main">
          <div className="header-column side-text left-align">
            <h2 className="brand-eng">AL NAMMUR RENT A CAR LLC</h2>
            <p className="contact-info">Tel: +971 4 458 0610</p>
            <p className="contact-info">Mob: +971 52 142 4234</p>
            <p className="contact-info">Mob: +971 58 197 6064</p>
          </div>
          <div className="header-column center-logo-box">
            <img src={logo} alt="Al Nammur Logo" className="logo-large" />
          </div>
          <div className="header-column side-text right-align">
            <h2 className="brand-ara">النمر لتأجير السيارات ذ.م.م</h2>
            <p className="contact-info-ar">هاتف: ٠٤٤٥٨٠٦١٠ ٩٧١+</p>
            <p className="contact-info-ar">جوال: ٠٥٢١٤٢٤٢٣٤ ٩٧١+</p>
            <p className="contact-info-ar">جوال: ٠٥٨١٩٧٦٠٦٤ ٩٧١+</p>
          </div>
        </div>

        <div className="title-section"><span className="title-text">INVOICE</span></div>
<div className="no-print" style={{ marginBottom: '10px' }}>
  {[...Array(numberOfInvoices)].map((_, i) => (
    <button
      key={i}
      onClick={() => setActiveInvoiceTab(i)}
      style={{
        marginRight: '5px',
        padding: '5px 10px',
        background: activeInvoiceTab === i ? '#b08d57' : '#ddd',
        border: 'none',
        cursor: 'pointer'
      }}
    >
      Invoice {i + 1}
    </button>
  ))}
</div>
        {/* Customer Details */}
        <div className="details-grid">
          <div className="detail-row">
            <label>Customer Name:</label>
            <div className="value-line uppercase">{data.full_name || data.customer_name}</div>
            <label className="label-spacing">Invoice No:</label>
            <div className="value-line" style={{width: '130px'}}>INV-{data.booking_id || data.id}</div>
          </div>
          <div className="detail-row">
            <label>Mobile No:</label>
            <div className="value-line">{data.mobile || data.customer_phone}</div>
            <label className="label-spacing">Date:</label>
            <div className="value-line" style={{width: '130px'}}>{new Date().toLocaleDateString('en-GB')}</div>
          </div>
        </div>

        {/* Booking Info Table */}
        <div className="table-section" style={{ marginTop: "20px" }}>
          <table className="invoice-table">
            <thead>
              <tr>
                <th>Booking Id</th>
                <th>Booking Mode</th>
                <th>Booking status</th>
<th>Start KM</th>
        <th>End KM</th>
        <th>Driven KM</th>
        <th>Start Fuel</th>
        <th>Return Fuel</th>              </tr>
            </thead>
            <tbody>
              <tr>
                <td>{data.booking_id || "N/A"}</td>
                <td>{data.booking_mode || "N/A"}</td>
                <td>{data.status || "N/A"}</td>
<td>{data.starting_kms || '0'}</td>
        
        {/* End KM */}
        <td className="fw-bold">{data.ending_kms || '0'}</td>
        
        {/* Driven KM Calculation */}
        <td className="fw-bold text-info">
          {(parseFloat(data.ending_kms || 0) - parseFloat(data.starting_kms || 0)) > 0 
            ? (parseFloat(data.ending_kms || 0) - parseFloat(data.starting_kms || 0)) 
            : 0} KM
        </td>
        
        {/* Start Fuel */}
        <td>{data.fuel_level || 'N/A'}</td>
        
        {/* Return Fuel */}
        <td className="fw-bold">{data.return_fuel_level || 'N/A'}</td>
                    </tr>
            </tbody>
          </table>
        </div>

        <div className="table-section">
          <table className="invoice-table">
            <thead>
              <tr>
                <th>Brand</th>
                <th>Model</th>
                <th>Year</th>
                <th>Rental Period</th>
                <th>Days</th>
             <th>Base Price</th>
<th>Total (AED)</th>
              </tr>
            </thead>
            <tbody>
              <tr style={{height: '35px'}}>
                <td>{data.brand || "N/A"}</td>
                <td>{data.model || "N/A"}</td>
                <td>{data.year || "N/A"}</td>
                <td style={{fontSize: '11px'}}>{start.toLocaleDateString('en-GB')} to {end.toLocaleDateString('en-GB')}</td>
<td className="fw-bold">{currentDays}</td>              <td className="fw-bold">
  {basePerDay.toFixed(2)}
</td>

<td className="text-right fw-bold">
{basePerDay.toFixed(2)} × {currentDays} = {base.toFixed(2)}</td>
              </tr>

              {/* Extra Dynamic Rows with Default Charges */}
              {extraRows.map((row, index) => (
                <tr key={index} className="extra-charge-row">
                  <td colSpan="6" className="text-right" style={{ padding: '4px 10px' }}>
                    <div style={{display: 'flex', alignItems: 'center', justifyContent: 'flex-end'}}>
                      <input 
                        className="inline-edit-minimal no-print" 
                        value={row.label} 
                        onChange={(e) => updateRow(index, 'label', e.target.value)} 
                      />
                      <span className="print-only" style={{ float: 'left' }}>{row.label}</span>
                    </div>
                  </td>
                  <td className="text-right fw-bold" style={{ width: '150px' }}>
                    <input 
                      type="number" 
                      className="inline-edit-minimal no-print text-right" 
                      style={{ width: '80px' }} 
                      value={row.amount} 
                      onChange={(e) => updateRow(index, 'amount', e.target.value)} 
                    />
                    <span className="print-only">{parseFloat(row.amount || 0).toFixed(2)}</span>
                  </td>
                </tr>
              ))}

           
              

              <tr>
                <td colSpan="6" className="text-right">Base Amount</td>
                <td className="text-right">{subTotal.toFixed(2)}</td>
              </tr>
            {isLastInvoice && (
  <tr>
    <td colSpan="6" className="text-right">VAT ({gstPercent}%)</td>
    <td className="text-right">{gstAmount.toFixed(2)}</td>
  </tr>
)}
              <tr style={{background: '#eee'}}>
                <td colSpan="6" className="text-right fw-bold">Total</td>
                <td className="text-right fw-bold">{total.toFixed(2)}</td>
              </tr>
            </tbody>
          </table>
        </div>

        {/* Footer */}
        <div className="invoice-footer">
          <div className="payment-info">
            <div className="payment-box"><strong>Payment Mode: {data.payment_method || 'Cash'}</strong></div>
            <p className="note-text">* This is a computer-generated document.</p>
          </div>
          <div className="amount-summary-box">
             <div className="summary-line">
                <span>Gross Total:</span>
                <span>{total.toFixed(2)}</span>
             </div>
             <div className="summary-line">
  <span>Advance Received:</span>

  <div style={{ width: "120px", textAlign: "right" }}>
    <input
      type="number"
      value={advancePaid}
      disabled={!isLastInvoice}
      onChange={(e) => setAdvancePaid(e.target.value)}
      className="no-print"
      style={{
        width: "100%",
        textAlign: "right",
        border: "none",
        background: "transparent"
      }}
    />

    <span className="print-only">
     - {isLastInvoice ? parseFloat(advancePaid).toFixed(2) : "0.00"}
    </span>
  </div>
</div>
             <div className="summary-line balance-highlight">
                <span>Net Balance Due:</span>
                <span>AED {balance}</span>
             </div>
          </div>
        </div>

        <div className="signature-area">
          <div className="signature-box"><div className="border-top-black"></div><p>Authorized Signatory</p></div>

  <div 
    onClick={() => window.print()} 
    style={{
      display: 'flex',
      alignItems: 'center',
      gap: '8px',
      cursor: 'pointer',
      color: '#000',
      padding: '8px 12px',
      borderRadius: '20px',
      border: '1px solid #ddd',
      background: '#ece8e8',
      boxShadow: '0 2px 5px rgba(0,0,0,0.1)',
      transition: 'all 0.3s ease'
    }}
   
  >
    {/* Simple SVG Printer Icon */}
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="6 9 6 2 18 2 18 9"></polyline>
      <path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"></path>
      <rect x="6" y="14" width="12" height="8"></rect>
    </svg>
    <span style={{ fontSize: '14px', fontWeight: '600', letterSpacing: '0.5px' }}>PRINT</span>
  </div>

          <div className="signature-box"><div className="border-top-black"></div><p>Customer Signature</p></div>
        </div>
      </div>

      <style>{`
        .invoice-wrapper * { color: #000 !important; font-family: 'Segoe UI', Tahoma, sans-serif; }
        .invoice-wrapper { width: 100%; display: flex; flex-direction: column; align-items: center; background: #f5f5f5; padding: 20px 0; }
        .invoice-container { width: 210mm; background: #fff !important; padding: 12mm; min-height: 297mm; border: 1px solid #ddd; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        .receipt-header-main { display: flex; align-items: center; justify-content: space-between; margin-bottom: 5px; }
        .logo-large { width: 450px; height: auto; object-fit: contain; }
        .brand-eng { margin: 0; font-size: 16px; color: #b08d57 !important; font-weight: 900; }
        .brand-ara { margin: 0; font-size: 20px; font-weight: bold; }
        .contact-info, .contact-info-ar { margin: 1px 0; font-size: 11px; font-weight: 600; }
        .title-section { border-top: 2px solid #000; border-bottom: 2px solid #000; text-align: center; padding: 5px 0; margin: 15px 0; background: #f9f9f9; }
        .title-text { font-weight: 900; font-size: 18px; letter-spacing: 2px; }
        .detail-row { display: flex; align-items: flex-end; margin-bottom: 12px; }
        .detail-row label { font-size: 12px; font-weight: bold; margin-right: 8px; white-space: nowrap; min-width: 100px; }
        .value-line { border-bottom: 1px dotted #000; flex-grow: 1; padding: 0 5px; font-size: 13px; min-height: 18px; }
        .label-spacing { margin-left: 25px; }
        .invoice-table { width: 100%; border-collapse: collapse; margin-top: 15px; border: 1px solid #000; }
        .invoice-table th { background: #eee !important; border: 1px solid #000; padding: 8px; font-size: 11px; text-transform: uppercase; }
        .invoice-table td { border: 1px solid #000; padding: 8px; font-size: 13px; text-align: center; }
        .text-right { text-align: right !important; }
        .fw-bold { font-weight: bold; }
        .invoice-footer { display: flex; justify-content: space-between; margin-top: 30px; }
        .payment-box { border: 1px dashed #000; padding: 5px 10px; display: inline-block; font-size: 12px; margin-bottom: 10px; }
        .amount-summary-box { width: 280px; border: 1px solid #000; padding: 10px; }
        .summary-line { display: flex; justify-content: space-between; padding: 5px 0; font-size: 13px; }
        .balance-highlight { border-top: 2px solid #000; margin-top: 5px; padding-top: 8px; font-size: 18px; font-weight: 900; }
        .note-text { font-size: 10px; color: #444 !important; line-height: 1.5; margin-top: 15px; }
        .signature-area { display: flex; justify-content: space-between; margin-top: 80px; }
        .signature-box { width: 200px; text-align: center; }
        .border-top-black { border-top: 1px solid #000; margin-bottom: 5px; }
        .signature-box p { font-size: 12px; font-weight: bold; }

        /* Compact & Minimal Styles */
        .inline-edit-minimal { border: none; background: transparent; font-size: 12px; text-align: right; width: 80%; outline: none; padding: 2px; }
        .inline-edit-minimal:focus { background: #fffdf5; border-bottom: 1px solid #b08d57; }
        .extra-charge-row td { padding: 4px 10px !important; }
        .delete-btn { color: #ff4d4d; border: none; background: none; cursor: pointer; font-weight: bold; margin-left: 8px; font-size: 16px; }
        .add-btn-round { background: #eee; border: 1px solid #ccc; border-radius: 50%; width: 22px; height: 22px; cursor: pointer; font-weight: bold; line-height: 1; }
        .add-btn-round:hover { background: #ddd; }
        .print-only { display: none; }

        @media print {
          .no-print { display: none !important; }
          .print-only { display: inline-block !important; }
          .invoice-wrapper { background: #fff; padding: 0; }
          .invoice-container { border: none; width: 100%; padding: 5mm; box-shadow: none; }
          .invoice-table th { background-color: #eee !important; -webkit-print-color-adjust: exact; }
        }
      `}</style>
    </div>
  );
};

export default FullInvoice;