import React from 'react';
import { useState } from 'react';
import axios from 'axios';

function Reports(props) {
  var typeState = useState('daily');
  var reportType = typeState[0];
  var setReportType = typeState[1];
  var dataState = useState(null);
  var reportData = dataState[0];
  var setReportData = dataState[1];
  var loadingState = useState(false);
  var loading = loadingState[0];
  var setLoading = loadingState[1];

  var now = new Date();
  var dateStr = now.getFullYear() + '-' + (now.getMonth() + 1 < 10 ? '0' + (now.getMonth() + 1) : now.getMonth() + 1) + '-' + (now.getDate() < 10 ? '0' + now.getDate() : now.getDate());
  var monthStr = now.getFullYear() + '-' + (now.getMonth() + 1 < 10 ? '0' + (now.getMonth() + 1) : now.getMonth() + 1);

  var dateInputState = useState(dateStr);
  var dateInput = dateInputState[0];
  var setDateInput = dateInputState[1];
  var monthInputState = useState(monthStr);
  var monthInput = monthInputState[0];
  var setMonthInput = monthInputState[1];

  var token = props.session ? props.session.token : '';
  var headers = { Authorization: 'Bearer ' + token };

  function fetchReport() {
    setLoading(true);
    setReportData(null);

    var url;
    var params;
    if (reportType === 'daily') {
      url = props.API + '/reports/daily';
      params = { date: dateInput };
    } else if (reportType === 'weekly') {
      url = props.API + '/reports/weekly';
      params = { date: dateInput };
    } else {
      url = props.API + '/reports/monthly';
      var parts = monthInput.split('-');
      params = { year: parts[0], month: parts[1] };
    }

    axios.get(url, { headers: headers, params: params })
      .then(function(res) {
        setReportData(res.data);
      })
      .catch(function(err) {
        console.error('Report error:', err);
      })
      .then(function() {
        setLoading(false);
      });
  }

  function dateText(d) {
    return d ? new Date(d).toLocaleDateString() : '-';
  }

  var types = [
    { key: 'daily', label: 'Daily' },
    { key: 'weekly', label: 'Weekly' },
    { key: 'monthly', label: 'Monthly' },
  ];

  return (
    <main className="page">
      <div className="page-title"><h2>Reports</h2><p>Generate sales reports.</p></div>

      <section className="report-filters">
        {types.map(function(t) {
          return React.createElement('button', {
            key: t.key,
            onClick: function() { setReportType(t.key); },
            style: {
              background: reportType === t.key ? '#1E3A8A' : '#e2e8f0',
              color: reportType === t.key ? 'white' : '#475569'
            }
          }, t.label);
        })}
        {(reportType === 'daily' || reportType === 'weekly') ? React.createElement('input', { type: 'date', value: dateInput, onChange: function(e) { setDateInput(e.target.value); } }) : null}
        {reportType === 'monthly' ? React.createElement('input', { type: 'month', value: monthInput, onChange: function(e) { setMonthInput(e.target.value); } }) : null}
        <button onClick={fetchReport} disabled={loading}>{loading ? 'Generating...' : 'Generate Report'}</button>
        {reportData ? React.createElement('button', { className: 'no-print', onClick: function() { window.print(); } }, '🖨️ Print') : null}
      </section>

      {reportData ? (
        <div>
          <section className="report-summary">
            <div className="report-stat">
              <span>Total Transactions</span>
              <strong>{reportData.totalTransactions}</strong>
            </div>
            <div className="report-stat">
              <span>Total Revenue</span>
              <strong>{reportData.totalRevenue.toLocaleString()} FRW</strong>
            </div>
            <div className="report-stat">
              <span>Average per Sale</span>
              <strong>{reportData.totalTransactions > 0 ? (reportData.totalRevenue / reportData.totalTransactions).toLocaleString() : '0'} FRW</strong>
            </div>
          </section>

          <div className="table-wrap">
            <table>
              <thead>
                <tr>
                  <th>Invoice</th><th>Date</th><th>Customer</th><th>Payment</th><th>Amount</th>
                </tr>
              </thead>
              <tbody>
                {reportData.sales.length === 0 ? (
                  <tr><td colSpan="5" style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}>No sales found</td></tr>
                ) : reportData.sales.map(function(s) {
                  return (
                    <tr key={s._id}>
                      <td>{s.invoiceNumber}</td>
                      <td>{dateText(s.salesDate)}</td>
                      <td>{s.customer ? s.customer.firstName + ' ' + s.customer.lastName : 'N/A'}</td>
                      <td>{s.paymentMethod}</td>
                      <td>{s.totalAmountPaid.toLocaleString()} FRW</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      ) : null}
    </main>
  );
}

export default Reports;
