import React, { useEffect, useState } from 'react';
import api from '../axios';

const Reportpage = () => {
  const [reports, setReports] = useState([]);
  const [selectedDate, setSelectedDate] = useState(
    new Date().toISOString().split('T')[0]
  );

  const fetchData = async () => {
    try {
      const res = await api.get('/report/all');
      const data = res.data?.reports || res.data?.result || res.data || [];
      setReports(data);
    } catch (err) {
      console.error("Error fetching reports:", err);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  const filtered = reports.filter((r) => {
    if (!r.date) return false;
    return new Date(r.date).toISOString().split('T')[0] === selectedDate;
  });

  const total = filtered.reduce((sum, r) => {
    return sum + (r.payment?.amount || 0);
  }, 0);

  const handlePrint = () => {
    window.print();
  };

  const handleInvoice = (rpt) => {
    const invoiceWindow = window.open('', '_blank');
    
    // Define the HTML for the invoice
    const html = `
      <html>
        <head>
          <title>Invoice - ${rpt.reportCode}</title>
          <style>
            body { font-family: 'Inter', sans-serif; padding: 40px; color: #1e293b; line-height: 1.5; }
            .header { display: flex; justify-content: space-between; border-bottom: 2px solid #f1f5f9; padding-bottom: 20px; margin-bottom: 30px; }
            .company-info h1 { margin: 0; color: #2563eb; font-size: 24px; }
            .invoice-title { text-align: right; }
            .invoice-title h2 { margin: 0; color: #64748b; font-size: 20px; }
            .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 40px; margin-bottom: 40px; }
            .section-title { font-size: 12px; font-weight: 700; color: #94a3b8; text-transform: uppercase; margin-bottom: 10px; }
            table { width: 100%; border-collapse: collapse; margin-bottom: 40px; }
            th { text-align: left; background: #f8fafc; padding: 12px; color: #64748b; font-size: 13px; }
            td { padding: 12px; border-bottom: 1px solid #f1f5f9; font-size: 14px; }
            .total-section { text-align: right; margin-top: 20px; }
            .total-amount { font-size: 24px; font-weight: 800; color: #1e293b; }
            .footer { margin-top: 50px; text-align: center; color: #94a3b8; font-size: 12px; }
            @media print { .no-print { display: none; } }
            .print-btn { background: #2563eb; color: white; border: none; padding: 10px 20px; borderRadius: 6px; cursor: pointer; font-weight: 600; margin-bottom: 20px; }
          </style>
        </head>
        <body>
          <button class="print-btn no-print" onclick="window.print()">Print Invoice</button>
          
          <div class="header">
            <div class="company-info">
              <h1>FixTrack Workshop</h1>
              <p>Kigali, Rwanda</p>
            </div>
            <div class="invoice-title">
              <h2>INVOICE</h2>
              <p># ${rpt.reportCode}</p>
              <p>Date: ${new Date(rpt.date).toLocaleDateString()}</p>
            </div>
          </div>

          <div class="grid">
            <div>
              <div class="section-title">Billing To</div>
              <p><strong>Vehicle:</strong> ${rpt.car?.plateNumber || 'N/A'}</p>
              <p><strong>Payment Method:</strong> MoMo Pay / Cash</p>
            </div>
            <div style="text-align: right;">
              <div class="section-title">Payment Status</div>
              <p style="color: #10b981; font-weight: 600;">PAID</p>
              <p>Transaction ID: ${rpt.payment?.paymentCode || 'N/A'}</p>
            </div>
          </div>

          <table>
            <thead>
              <tr>
                <th>Description</th>
                <th style="text-align: right;">Amount</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>${rpt.servicename?.servicename || 'General Maintenance Service'}</td>
                <td style="text-align: right;">${rpt.payment?.amount?.toLocaleString()} RWF</td>
              </tr>
            </tbody>
          </table>

          <div class="total-section">
            <div class="section-title">Grand Total</div>
            <div class="total-amount">${rpt.payment?.amount?.toLocaleString()} RWF</div>
          </div>

          <div class="footer">
            <p>Thank you for choosing FixTrack! Keep this invoice for your records.</p>
          </div>
        </body>
      </html>
    `;

    invoiceWindow.document.write(html);
    invoiceWindow.document.close();
  };

 
  const containerStyle = { padding: '40px', background: '#f1f5f9', minHeight: '100vh', fontFamily: 'Inter, sans-serif' };
  const headerStyle = { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '30px' };
  const cardStyle = { background: 'white', padding: '25px', borderRadius: '12px', boxShadow: '0 1px 3px rgba(0,0,0,0.1)', marginBottom: '30px' };
  const statCard = { ...cardStyle, display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderLeft: '5px solid #10b981' };
  const inputStyle = { padding: '10px', borderRadius: '8px', border: '1px solid #e2e8f0', fontSize: '14px', outline: 'none' };
  const btnPrint = { padding: '10px 20px', background: 'white', color: '#1e293b', border: '1px solid #e2e8f0', borderRadius: '8px', fontWeight: '600', cursor: 'pointer' };
  const btnInvoice = { padding: '6px 12px', background: '#eff6ff', color: '#2563eb', border: 'none', borderRadius: '6px', fontSize: '12px', fontWeight: '600', cursor: 'pointer' };
  const thStyle = { textAlign: 'left', padding: '15px', color: '#64748b', fontSize: '12px', textTransform: 'uppercase', letterSpacing: '0.05em', borderBottom: '1px solid #f1f5f9' };
  const tdStyle = { padding: '15px', fontSize: '14px', color: '#1e293b', borderBottom: '1px solid #f1f5f9' };

  return (
    <div style={containerStyle}>
    
      <div style={headerStyle}>
        <div>
          <h2 style={{ margin: 0, color: '#0f172a', fontWeight: '800' }}>Performance Reports</h2>
          <p style={{ margin: 0, color: '#64748b', fontSize: '14px' }}>Daily workshop activity and revenue tracking</p>
        </div>
        <button onClick={handlePrint} style={btnPrint}>Print Summary</button>
      </div>

     
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px', marginBottom: '30px' }}>
        <div style={cardStyle}>
          <label style={{ display: 'block', marginBottom: '10px', fontSize: '12px', fontWeight: '600', color: '#94a3b8' }}>FILTER BY DATE</label>
          <input type="date" value={selectedDate} onChange={(e) => setSelectedDate(e.target.value)} style={inputStyle} />
        </div>
        
        <div style={statCard}>
          <div>
            <label style={{ display: 'block', fontSize: '12px', fontWeight: '600', color: '#94a3b8' }}>TOTAL DAILY REVENUE</label>
            <h2 style={{ margin: 0, color: '#10b981', fontWeight: '800' }}>{total.toLocaleString()} RWF</h2>
          </div>
        </div>
      </div>

   
      <div style={{ ...cardStyle, padding: 0, overflow: 'hidden' }}>
        <table width="100%" style={{ borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ background: '#f8fafc' }}>
              <th style={thStyle}>CODE</th>
              <th style={thStyle}>VEHICLE</th>
              <th style={thStyle}>SERVICE</th>
              <th style={thStyle}>AMOUNT</th>
              <th style={thStyle}>ACTIONS</th>
            </tr>
          </thead>
          <tbody>
            {filtered.length === 0 ? (
              <tr>
                <td colSpan="5" style={{ ...tdStyle, textAlign: 'center', padding: '40px', color: '#94a3b8' }}>No reports found for this date.</td>
              </tr>
            ) : (
              filtered.map((r) => (
                <tr key={r._id} style={{ transition: 'background 0.2s' }} onMouseOver={(e) => e.currentTarget.style.background = '#f8fafc'} onMouseOut={(e) => e.currentTarget.style.background = 'transparent'}>
                  <td style={{ ...tdStyle, fontWeight: '600', color: '#2563eb' }}>{r.reportCode}</td>
                  <td style={tdStyle}>{r.car?.plateNumber || '---'}</td>
                  <td style={tdStyle}>
                    <span style={{ padding: '4px 8px', background: '#f1f5f9', borderRadius: '6px', fontSize: '12px' }}>
                      {r.servicename?.servicename || 'N/A'}
                    </span>
                  </td>
                  <td style={{ ...tdStyle, fontWeight: '700' }}>{r.payment?.amount?.toLocaleString()} RWF</td>
                  <td style={tdStyle}>
                    <button onClick={() => handleInvoice(r)} style={btnInvoice}>Invoice</button>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

   
      <style>{`
        @media print {
          button, input, label { display: none !important; }
          div { box-shadow: none !important; background: white !important; padding: 0 !important; }
          h2 { color: black !important; }
          table { width: 100% !important; border: 1px solid #eee; }
        }
      `}</style>
    </div>
  );
};

export default Reportpage;