// Component that renders printable billing payment receipts for advances and partial payments with company branding.
import React, { useEffect, useState } from "react";
import { useParams, useLocation } from "react-router-dom";
import api from "../api";
import logo from "../assets/logo.png";

const AdvanceReceipt = () => {
  const { id } = useParams();
  const { search } = useLocation();
  const queryParams = new URLSearchParams(search);
  const txIndex = queryParams.get("index");
  
  const [data, setData] = useState(null);
  const [remarks, setRemarks] = useState("");

  useEffect(() => {
    if (data) {
      setRemarks(data.advance_remarks || "Payment received for booking.");
    }
  }, [data]);
  useEffect(() => {
    api.get(`/bookings/${id}`)
      .then(res => {
        setData(res.data);
      })
      .catch(err => console.error("Fetch Error:", err));
  }, [id]);
  useEffect(() => {
    if (data) {
      setTimeout(() => {
        window.print();
      }, 500); 
    }
  }, [data]);
  if (!data) return <div style={{padding: '50px', textAlign: 'center'}}>Loading Receipt...</div>;

  const total = parseFloat(data.total_price || 0);
  
  // Parse payment history
  let paymentHistory = [];
  try {
    if (data.payment_history) {
      paymentHistory = JSON.parse(data.payment_history);
    }
  } catch (e) {
    console.error(e);
  }

  const advancePaid = parseFloat(data.advance_paid) || 0;
  if (paymentHistory.length === 0 && advancePaid > 0) {
    paymentHistory = [{
      date: data.booking_date || data.created_at || new Date().toISOString(),
      type: 'Advance',
      description: 'Advance Payment',
      amount: advancePaid,
      mode: data.payment_method || 'Cash'
    }];
  }

  // Find targeted transaction
  const parsedIndex = parseInt(txIndex, 10);
  const isSpecificTx = !isNaN(parsedIndex) && parsedIndex >= 0 && parsedIndex < paymentHistory.length;
  
  const currentTx = isSpecificTx ? paymentHistory[parsedIndex] : null;
  const receiptTitle = currentTx ? `${currentTx.type.toUpperCase()} RECEIPT` : "ADVANCE RECEIPT";
  const amountReceived = currentTx ? parseFloat(currentTx.amount || 0) : advancePaid;
  
  // Calculate Balance Due up to the selected transaction
  let balance = (total - advancePaid).toFixed(2);
  if (isSpecificTx) {
    if (currentTx.type === 'Final' || (data.payment_status === 'Paid' && parsedIndex === paymentHistory.length - 1)) {
      balance = (0).toFixed(2);
    } else {
      const totalPaidUpToCurrent = paymentHistory.slice(0, parsedIndex + 1).reduce((sum, tx) => sum + parseFloat(tx.amount || 0), 0);
      balance = Math.max(0, total - totalPaidUpToCurrent).toFixed(2);
    }
  }

  return (
    <div className="receipt-container">
      
      <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>
          <p className="contact-info">Mob: +971 55 695 9765</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>
          <p className="contact-info-ar">جوال: ٠٥٥٦٩٥٩٧٦٥ ٩٧١+</p>
        </div>
      </div>

      <div className="title-section">
        <span className="title-text">{receiptTitle}</span>
      </div>

      <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">Date:</label>
          <div className="value-line" style={{width: '130px'}}>
            {currentTx ? new Date(currentTx.date).toLocaleDateString('en-GB') : (data.booking_date ? new Date(data.booking_date).toLocaleDateString('en-GB') : new Date().toLocaleDateString('en-GB'))}
          </div>
        </div>

        <div className="detail-row">
          <label>Mobile No:</label>
          <div className="value-line">{data.mobile || data.customer_phone}</div>
          <label className="label-spacing">Booking ID:</label>
          <div className="value-line" style={{width: '130px'}}>#{data.booking_id}</div>
        </div>

        <div className="detail-row">
          <label>Vehicle Details:</label>
          <div className="value-line">
            {data.car_brand || data.brand} {data.car_model || data.model} ({data.car_year || data.year})
          </div>
          <label className="label-spacing">License No:</label>
          <div className="value-line" style={{width: '180px'}}>{data.license_number || data.customer_license}</div>
        </div>

        <div className="detail-row">
          <label>Rental Period:</label>
          <div className="value-line">
            {new Date(data.start_date).toLocaleDateString('en-GB')} To {new Date(data.end_date).toLocaleDateString('en-GB')}
          </div>
        </div>

       <div className="detail-row" style={{ alignItems: 'flex-start' }}>
  <label style={{ marginTop: '8px' }}>Remarks:</label>
            <div className="value-line" style={{width: '180px'}}>{data.advance_remarks || " "}</div>

</div>
</div>
      <div className="payment-area" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '40px' }}>
        {balance === '0.00' ? (
          <div style={{
            border: '2px solid #22c55e',
            color: '#22c55e',
            padding: '10px 20px',
            borderRadius: '6px',
            fontWeight: 'bold',
            fontSize: '13px',
            textTransform: 'uppercase',
            letterSpacing: '1px',
            display: 'flex',
            alignItems: 'center',
            gap: '8px'
          }}>
            ✓ Payment Completed Successfully
          </div>
        ) : <div />}
        <div className="payment-box" style={{ marginTop: 0 }}>
          <div className="pay-line">
            <span>Total Rental Amount:</span>
            <span className="fw-700">AED {total.toFixed(2)}</span>
          </div>
          <div className="pay-line">
            <span>{currentTx ? 'Amount Received:' : 'Advance Received:'}</span>
            <span className="fw-700">(-) {amountReceived.toFixed(2)}</span>
          </div>
          <div className="pay-line total-highlight">
            <span>Balance Due:</span>
            <span className="fw-700">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 className="signature-box"><div className="border-top-black"></div><p>Customer Signature</p></div>
      </div>

     

      <style>{`
        .receipt-container { width: 210mm; margin: 0 auto; padding: 15mm; background: #fff; color: #000; font-family: 'Arial', sans-serif; }
        
        /* HEADER LAYOUT */
        .receipt-header-main { 
          display: flex; 
          align-items: center; 
          justify-content: space-between; 
          width: 100%; 
          margin-bottom: 10px;
        }
        .header-column { flex: 1; }
        .side-text { width: 35%; }
        .center-logo-box { 
          width: 30%; 
          display: flex; 
          justify-content: center; 
          align-items: center; 
        }
        
        .logo-large { 
          width: 550px; 
          height: auto; 
          max-height: 120px;
          object-fit: contain; 
        }

        .left-align { text-align: left; }
        .right-align { text-align: right; }

        .brand-eng { margin: 0; font-size: 15px; color: #b08d57; font-weight: bold; line-height: 1.2; }
        .brand-ara { margin: 0; font-size: 20px; font-weight: bold; line-height: 1.2; }
        .contact-info, .contact-info-ar { margin: 2px 0; font-size: 12px; font-weight: 600; }

        .title-section { border-top: 2px solid #000; border-bottom: 2px solid #000; text-align: center; padding: 10px 0; margin: 25px 0; }
        .title-text { font-weight: bold; font-size: 22px; letter-spacing: 1px; }
        
        .details-grid { margin-top: 30px; }
        .detail-row { display: flex; align-items: flex-end; margin-bottom: 25px; width: 100%; }
        .detail-row label { font-size: 14px; font-weight: bold; margin-right: 10px; white-space: nowrap; }
        .value-line { border-bottom: 1px solid #000; flex-grow: 1; padding: 0 5px; font-size: 15px; min-height: 22px; }
        .label-spacing { margin-left: 25px; }
        .uppercase { text-transform: uppercase; }

        .payment-area { display: flex; justify-content: flex-end; margin-top: 40px; }
        .payment-box { width: 320px; border: 2px solid #464646; padding: 15px; }
        .pay-line { display: flex; justify-content: space-between; padding: 6px 0; font-size: 14px; }
        .total-highlight { border-top: 1px solid #000; margin-top: 5px; padding-top: 10px; font-size: 18px; font-weight: bold; }
        .fw-700 { font-weight: 700; }

        .signature-area { display: flex; justify-content: space-between; margin-top: 90px; }
        .signature-box { width: 220px; text-align: center; }
        .border-top-black { border-top: 1px solid #000; margin-bottom: 5px; }
        .signature-box p { font-size: 14px; font-weight: bold; }

        .action-btn { padding: 12px 50px; background: #000; color: #fff; border: none; cursor: pointer; border-radius: 4px; font-weight: bold; font-size: 16px; }

        @media print {
          .no-print { display: none; }
          .receipt-container { padding: 5mm; width: 100%; }
        }
      `}</style>
    </div>
  );
};

export default AdvanceReceipt;