'use client';

import React, { useEffect, useState } from 'react';

export default function ReportsPage() {
  const [data, setData] = useState<any>(null);
  const [products, setProducts] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    Promise.all([
      fetch('/api/reports').then(res => res.json()),
      fetch('/api/products').then(res => res.json())
    ])
    .then(([reportsData, productsData]) => {
      setData(reportsData);
      if (Array.isArray(productsData)) setProducts(productsData);
      setLoading(false);
    })
    .catch(err => {
      console.error(err);
      setLoading(false);
    });
  }, []);

  if (loading) return <div>Loading reports...</div>;
  if (!data) return <div>Error loading reports.</div>;

  return (
    <div>
      <h1>Reports & Analytics</h1>
      
      <div className="grid grid-3" style={{ marginBottom: '2rem' }}>
        <div className="panel">
          <h3>Total Revenue</h3>
          <div style={{ fontSize: '2rem', fontWeight: 'bold', color: 'var(--success)' }}>
            PKR {data.metrics.totalRevenue.toLocaleString(undefined, { minimumFractionDigits: 2 })}
          </div>
        </div>
        <div className="panel">
          <h3>Total Purchases</h3>
          <div style={{ fontSize: '2rem', fontWeight: 'bold', color: 'var(--danger)' }}>
            PKR {data.metrics.totalPurchases.toLocaleString(undefined, { minimumFractionDigits: 2 })}
          </div>
        </div>
        <div className="panel">
          <h3>Current Stock Value</h3>
          <div style={{ fontSize: '2rem', fontWeight: 'bold', color: 'var(--accent)' }}>
            PKR {data.metrics.totalStockValue.toLocaleString(undefined, { minimumFractionDigits: 2 })}
          </div>
        </div>
      </div>

      <div className="grid grid-2">
        <div className="panel">
          <h2>Low Stock Items</h2>
          {data.lowStockItems.length === 0 ? (
            <p>No low stock items.</p>
          ) : (
            <table className="data-table">
              <thead>
                <tr>
                  <th>Product Name</th>
                  <th>Quantity</th>
                </tr>
              </thead>
              <tbody>
                {data.lowStockItems.map((item: any, i: number) => (
                  <tr key={i}>
                    <td>{item.name}</td>
                    <td style={{ color: 'var(--danger)', fontWeight: 'bold' }}>
                      {item.stock_quantity} {item.unit}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>

        <div className="panel">
          <h2>Recent Sales</h2>
          {data.recentSales.length === 0 ? (
            <p>No recent sales.</p>
          ) : (
            <table className="data-table">
              <thead>
                <tr>
                  <th>Date</th>
                  <th>Customer</th>
                  <th>Amount (PKR)</th>
                </tr>
              </thead>
              <tbody>
                {data.recentSales.map((sale: any) => (
                  <tr key={sale.id}>
                    <td>{new Date(sale.sale_date).toLocaleDateString()}</td>
                    <td>{sale.customer_name || 'Walk-in Customer'}</td>
                    <td style={{ color: 'var(--success)', fontWeight: 'bold' }}>
                      {parseFloat(sale.total_amount).toLocaleString(undefined, { minimumFractionDigits: 2 })}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>

      <div className="panel" style={{ marginTop: '2rem' }}>
        <h2>Full Stock Report</h2>
        {products.length === 0 ? (
          <p>No products available.</p>
        ) : (
          <table className="data-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>Product Name</th>
                <th>Type</th>
                <th>Current Stock</th>
                <th>Unit</th>
                <th>Cost Price</th>
                <th>Selling Price</th>
                <th>Total Value</th>
              </tr>
            </thead>
            <tbody>
              {products.map((p: any) => (
                <tr key={p.id}>
                  <td>{p.id}</td>
                  <td>{p.name}</td>
                  <td style={{ textTransform: 'capitalize' }}>{p.type}</td>
                  <td style={{ fontWeight: 'bold' }}>{p.stock_quantity}</td>
                  <td style={{ textTransform: 'capitalize' }}>{p.unit}</td>
                  <td>{p.cost_price}</td>
                  <td>{p.price}</td>
                  <td style={{ color: 'var(--accent)', fontWeight: 'bold' }}>
                    Rs {(p.stock_quantity * p.price).toLocaleString(undefined, { minimumFractionDigits: 2 })}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
