import { useState, useEffect } from 'react';
import { reportsAPI, customersAPI } from '../services/api';
import './Reports.css';

const Reports = () => {
  const [activeTab, setActiveTab] = useState('daily');
  const [customers, setCustomers] = useState([]);
  const [reportData, setReportData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const [dailyDate, setDailyDate] = useState(new Date().toISOString().split('T')[0]);
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [customerId, setCustomerId] = useState('');

  useEffect(() => {
    customersAPI.getAll().then(({ data }) => setCustomers(data)).catch(() => {});
  }, []);

  const formatCurrency = (amount) =>
    new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount);

  const formatDate = (date) =>
    new Date(date).toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });

  const generateDailyReport = async () => {
    setLoading(true);
    setError('');
    try {
      const { data } = await reportsAPI.daily(dailyDate);
      setReportData({ type: 'daily', ...data });
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to generate report.');
      setReportData(null);
    } finally {
      setLoading(false);
    }
  };

  const generateMonthlyReport = async () => {
    if (!startDate || !endDate) {
      setError('Please select both start and end dates.');
      return;
    }
    setLoading(true);
    setError('');
    try {
      const { data } = await reportsAPI.monthly(startDate, endDate);
      setReportData({ type: 'monthly', ...data });
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to generate report.');
      setReportData(null);
    } finally {
      setLoading(false);
    }
  };

  const generateStockReport = async () => {
    setLoading(true);
    setError('');
    try {
      const { data } = await reportsAPI.stock();
      setReportData({ type: 'stock', products: data });
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to generate report.');
      setReportData(null);
    } finally {
      setLoading(false);
    }
  };

  const generateCustomerReport = async () => {
    if (!customerId) {
      setError('Please select a customer.');
      return;
    }
    setLoading(true);
    setError('');
    try {
      const { data } = await reportsAPI.customerPurchases(customerId);
      setReportData({ type: 'customer', ...data });
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to generate report.');
      setReportData(null);
    } finally {
      setLoading(false);
    }
  };

  const tabs = [
    { id: 'daily', label: 'Daily Sales', action: generateDailyReport },
    { id: 'monthly', label: 'Monthly Sales', action: generateMonthlyReport },
    { id: 'stock', label: 'Product Stock', action: generateStockReport },
    { id: 'customer', label: 'Customer Purchases', action: generateCustomerReport },
  ];

  const handleTabChange = (tabId) => {
    setActiveTab(tabId);
    setReportData(null);
    setError('');
  };

  const renderSalesTable = (sales) => (
    <table>
      <thead>
        <tr>
          <th>Sale ID</th>
          <th>Customer</th>
          <th>Product</th>
          <th>Qty</th>
          <th>Unit Price</th>
          <th>Total</th>
          <th>Date</th>
        </tr>
      </thead>
      <tbody>
        {sales.map((sale) => (
          <tr key={sale.sale_id}>
            <td>{sale.sale_id}</td>
            <td>{sale.customer_name}</td>
            <td>{sale.product_name}</td>
            <td>{sale.quantity}</td>
            <td>{formatCurrency(sale.unit_price)}</td>
            <td>{formatCurrency(sale.total_price)}</td>
            <td>{formatDate(sale.sale_date)}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );

  return (
    <div className="reports-page">
      <div className="page-header">
        <h1>Reports & Analytics</h1>
      </div>

      <div className="report-tabs">
        {tabs.map((tab) => (
          <button
            key={tab.id}
            className={`report-tab ${activeTab === tab.id ? 'active' : ''}`}
            onClick={() => handleTabChange(tab.id)}
          >
            {tab.label}
          </button>
        ))}
      </div>

      <div className="card report-filters">
        {activeTab === 'daily' && (
          <div className="filter-row">
            <div className="form-group">
              <label>Select Date</label>
              <input type="date" value={dailyDate} onChange={(e) => setDailyDate(e.target.value)} />
            </div>
            <button className="btn btn-primary" onClick={generateDailyReport} disabled={loading}>
              Generate Report
            </button>
          </div>
        )}

        {activeTab === 'monthly' && (
          <div className="filter-row">
            <div className="form-group">
              <label>Start Date</label>
              <input type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} />
            </div>
            <div className="form-group">
              <label>End Date</label>
              <input type="date" value={endDate} onChange={(e) => setEndDate(e.target.value)} />
            </div>
            <button className="btn btn-primary" onClick={generateMonthlyReport} disabled={loading}>
              Generate Report
            </button>
          </div>
        )}

        {activeTab === 'stock' && (
          <div className="filter-row">
            <p>View current stock levels and sold quantities for all products.</p>
            <button className="btn btn-primary" onClick={generateStockReport} disabled={loading}>
              Generate Report
            </button>
          </div>
        )}

        {activeTab === 'customer' && (
          <div className="filter-row">
            <div className="form-group">
              <label>Select Customer</label>
              <select value={customerId} onChange={(e) => setCustomerId(e.target.value)}>
                <option value="">-- Choose Customer --</option>
                {customers.map((c) => (
                  <option key={c.customer_id} value={c.customer_id}>
                    {c.fullname}
                  </option>
                ))}
              </select>
            </div>
            <button className="btn btn-primary" onClick={generateCustomerReport} disabled={loading}>
              Generate Report
            </button>
          </div>
        )}
      </div>

      {error && <div className="alert alert-error">{error}</div>}

      {loading && <p className="empty-state">Generating report...</p>}

      {reportData && !loading && (
        <div className="card report-results">
          {(reportData.type === 'daily' || reportData.type === 'monthly') && (
            <>
              <div className="report-summary">
                <div className="summary-item">
                  <span>Total Sales</span>
                  <strong>{reportData.summary.totalSales}</strong>
                </div>
                <div className="summary-item">
                  <span>Items Sold</span>
                  <strong>{reportData.summary.totalItems}</strong>
                </div>
                <div className="summary-item">
                  <span>Total Revenue</span>
                  <strong>{formatCurrency(reportData.summary.totalRevenue)}</strong>
                </div>
              </div>
              {reportData.sales.length === 0 ? (
                <p className="empty-state">No sales found for this period.</p>
              ) : (
                renderSalesTable(reportData.sales)
              )}
            </>
          )}

          {reportData.type === 'stock' && (
            <table>
              <thead>
                <tr>
                  <th>Product</th>
                  <th>Category</th>
                  <th>Available Stock</th>
                  <th>Sold Stock</th>
                  <th>Price</th>
                </tr>
              </thead>
              <tbody>
                {reportData.products.map((p) => (
                  <tr key={p.product_id}>
                    <td>{p.product_name}</td>
                    <td>{p.category}</td>
                    <td>
                      <span className={`badge ${p.available_stock <= 5 ? 'badge-warning' : 'badge-success'}`}>
                        {p.available_stock}
                      </span>
                    </td>
                    <td>{p.sold_stock}</td>
                    <td>{formatCurrency(p.price)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}

          {reportData.type === 'customer' && (
            <>
              <div className="customer-report-header">
                <h3>{reportData.customer.fullname}</h3>
                <p>{reportData.customer.email} | {reportData.customer.phone_number}</p>
              </div>
              <div className="report-summary">
                <div className="summary-item">
                  <span>Total Purchases</span>
                  <strong>{reportData.summary.totalPurchases}</strong>
                </div>
                <div className="summary-item">
                  <span>Total Spent</span>
                  <strong>{formatCurrency(reportData.summary.totalSpent)}</strong>
                </div>
              </div>
              {reportData.purchases.length === 0 ? (
                <p className="empty-state">No purchases found for this customer.</p>
              ) : (
                <table>
                  <thead>
                    <tr>
                      <th>Sale ID</th>
                      <th>Product</th>
                      <th>Category</th>
                      <th>Qty</th>
                      <th>Total</th>
                      <th>Date</th>
                    </tr>
                  </thead>
                  <tbody>
                    {reportData.purchases.map((p) => (
                      <tr key={p.sale_id}>
                        <td>{p.sale_id}</td>
                        <td>{p.product_name}</td>
                        <td>{p.category}</td>
                        <td>{p.quantity}</td>
                        <td>{formatCurrency(p.total_price)}</td>
                        <td>{formatDate(p.sale_date)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </>
          )}
        </div>
      )}
    </div>
  );
};

export default Reports;
