import React, { useState, useEffect } from 'react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import api from '../utils/api';

const today = new Date().toISOString().split('T')[0];
const firstOfMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().split('T')[0];

export default function Reports() {
  const [tab, setTab] = useState('date');
  const [customers, setCustomers] = useState([]);

  // Date range
  const [dateRange, setDateRange] = useState({ start_date: firstOfMonth, end_date: today });
  const [dateResult, setDateResult] = useState(null);
  const [dateLoading, setDateLoading] = useState(false);

  // Monthly
  const [monthRange, setMonthRange] = useState({ start_date: '2024-01-01', end_date: today });
  const [monthResult, setMonthResult] = useState([]);
  const [monthLoading, setMonthLoading] = useState(false);

  // Stock
  const [stockResult, setStockResult] = useState([]);
  const [stockLoading, setStockLoading] = useState(false);

  // Customer purchase
  const [custId, setCustId] = useState('');
  const [custResult, setCustResult] = useState(null);
  const [custLoading, setCustLoading] = useState(false);

  useEffect(() => {
    api.get('/customers').then(r => setCustomers(r.data));
  }, []);

  const runDateReport = async () => {
    setDateLoading(true);
    try {
      const r = await api.get('/reports/sales-by-date', { params: dateRange });
      setDateResult(r.data);
    } catch (e) { alert('Failed to load report.'); }
    finally { setDateLoading(false); }
  };

  const runMonthReport = async () => {
    setMonthLoading(true);
    try {
      const r = await api.get('/reports/monthly', { params: monthRange });
      setMonthResult(r.data);
    } catch (e) { alert('Failed to load report.'); }
    finally { setMonthLoading(false); }
  };

  const runStockReport = async () => {
    setStockLoading(true);
    try {
      const r = await api.get('/reports/stock');
      setStockResult(r.data);
    } catch (e) { alert('Failed to load report.'); }
    finally { setStockLoading(false); }
  };

  const runCustReport = async () => {
    if (!custId) return alert('Please select a customer.');
    setCustLoading(true);
    try {
      const r = await api.get(`/reports/customer/${custId}`);
      setCustResult(r.data);
    } catch (e) { alert('Failed to load report.'); }
    finally { setCustLoading(false); }
  };

  const tabs = [
    { id: 'date', label: '📅 Sales by Date' },
    { id: 'monthly', label: '📆 Monthly Report' },
    { id: 'stock', label: '📦 Stock Report' },
    { id: 'customer', label: '👤 Customer Purchases' },
  ];

  return (
    <div>
      <div className="page-header">
        <div>
          <h1 className="page-title">Reports & Analytics</h1>
          <p className="page-subtitle">View detailed reports and insights</p>
        </div>
      </div>

      {/* Tab Bar */}
      <div style={{ display: 'flex', gap: 6, marginBottom: 24, flexWrap: 'wrap' }}>
        {tabs.map(t => (
          <button
            key={t.id}
            onClick={() => setTab(t.id)}
            className={`btn ${tab === t.id ? 'btn-primary' : 'btn-ghost'}`}
            style={{ fontSize: 13 }}
          >
            {t.label}
          </button>
        ))}
      </div>

      {/* ====== Date Range Report ====== */}
      {tab === 'date' && (
        <div>
          <div className="card" style={{ marginBottom: 20 }}>
            <div className="card-header"><span className="card-title">📅 Filter Sales by Date Range</span></div>
            <div className="card-body">
              <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'flex-end' }}>
                <div className="form-group">
                  <label>Start Date</label>
                  <input type="date" value={dateRange.start_date} onChange={e => setDateRange(d => ({ ...d, start_date: e.target.value }))} />
                </div>
                <div className="form-group">
                  <label>End Date</label>
                  <input type="date" value={dateRange.end_date} onChange={e => setDateRange(d => ({ ...d, end_date: e.target.value }))} />
                </div>
                <button className="btn btn-primary" onClick={runDateReport} disabled={dateLoading}>
                  {dateLoading ? '⏳ Loading...' : '🔍 Generate Report'}
                </button>
              </div>
            </div>
          </div>

          {dateResult && (
            <div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14, marginBottom: 16 }}>
                {[
                  { label: 'Total Sales', value: dateResult.count, icon: '🛒', color: 'var(--primary)' },
                  { label: 'Total Revenue', value: `${Number(dateResult.total_revenue).toLocaleString()} RWF`, icon: '💰', color: 'var(--success)' },
                  { label: 'Period', value: `${dateRange.start_date} → ${dateRange.end_date}`, icon: '📅', color: 'var(--accent)' },
                ].map((s, i) => (
                  <div key={i} className="card" style={{ padding: 16 }}>
                    <div style={{ fontSize: 22, marginBottom: 6 }}>{s.icon}</div>
                    <div style={{ fontSize: 18, fontWeight: 800, color: s.color }}>{s.value}</div>
                    <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{s.label}</div>
                  </div>
                ))}
              </div>
              <div className="card">
                <div className="table-wrapper">
                  {dateResult.sales.length === 0 ? (
                    <div className="empty-state" style={{ padding: 30 }}>
                      <div className="empty-title">No sales in this date range</div>
                    </div>
                  ) : (
                    <table>
                      <thead>
                        <tr><th>ID</th><th>Customer</th><th>Product</th><th>Qty</th><th>Unit Price</th><th>Total</th><th>Date</th></tr>
                      </thead>
                      <tbody>
                        {dateResult.sales.map(s => (
                          <tr key={s.sale_id}>
                            <td>#{s.sale_id}</td>
                            <td style={{ fontWeight: 600 }}>{s.customer_name}</td>
                            <td>{s.product_name}</td>
                            <td>{s.quantity}</td>
                            <td>{Number(s.unit_price).toLocaleString()} RWF</td>
                            <td style={{ fontWeight: 700, color: 'var(--success)' }}>{Number(s.total_price).toLocaleString()} RWF</td>
                            <td style={{ color: 'var(--text-muted)' }}>{new Date(s.sale_date).toLocaleDateString()}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  )}
                </div>
              </div>
            </div>
          )}
        </div>
      )}

      {/* ====== Monthly Report ====== */}
      {tab === 'monthly' && (
        <div>
          <div className="card" style={{ marginBottom: 20 }}>
            <div className="card-header"><span className="card-title">📆 Monthly Revenue Report</span></div>
            <div className="card-body">
              <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'flex-end' }}>
                <div className="form-group">
                  <label>Start Date</label>
                  <input type="date" value={monthRange.start_date} onChange={e => setMonthRange(d => ({ ...d, start_date: e.target.value }))} />
                </div>
                <div className="form-group">
                  <label>End Date</label>
                  <input type="date" value={monthRange.end_date} onChange={e => setMonthRange(d => ({ ...d, end_date: e.target.value }))} />
                </div>
                <button className="btn btn-primary" onClick={runMonthReport} disabled={monthLoading}>
                  {monthLoading ? '⏳ Loading...' : '📊 Generate Report'}
                </button>
              </div>
            </div>
          </div>

          {monthResult.length > 0 && (
            <div>
              <div className="card" style={{ marginBottom: 16 }}>
                <div className="card-header"><span className="card-title">Monthly Revenue Chart</span></div>
                <div className="card-body">
                  <ResponsiveContainer width="100%" height={260}>
                    <BarChart data={monthResult.map(m => ({ month: m.month, revenue: parseFloat(m.total_revenue) }))}>
                      <CartesianGrid strokeDasharray="3 3" stroke="#F0F2F5" />
                      <XAxis dataKey="month" tick={{ fontSize: 11 }} />
                      <YAxis tick={{ fontSize: 11 }} tickFormatter={v => `${(v / 1000).toFixed(0)}K`} />
                      <Tooltip formatter={v => [`${Number(v).toLocaleString()} RWF`, 'Revenue']} />
                      <Bar dataKey="revenue" fill="#0052FF" radius={[4, 4, 0, 0]} />
                    </BarChart>
                  </ResponsiveContainer>
                </div>
              </div>
              <div className="card">
                <div className="table-wrapper">
                  <table>
                    <thead>
                      <tr><th>Month</th><th>Total Sales</th><th>Items Sold</th><th>Revenue (RWF)</th></tr>
                    </thead>
                    <tbody>
                      {monthResult.map((m, i) => (
                        <tr key={i}>
                          <td style={{ fontWeight: 600 }}>{m.month}</td>
                          <td>{m.total_sales}</td>
                          <td>{m.total_quantity}</td>
                          <td style={{ fontWeight: 700, color: 'var(--success)' }}>{Number(m.total_revenue).toLocaleString()}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          )}
        </div>
      )}

      {/* ====== Stock Report ====== */}
      {tab === 'stock' && (
        <div>
          <div style={{ marginBottom: 16 }}>
            <button className="btn btn-primary" onClick={runStockReport} disabled={stockLoading}>
              {stockLoading ? '⏳ Loading...' : '📦 Load Stock Report'}
            </button>
          </div>

          {stockResult.length > 0 && (
            <div className="card">
              <div className="card-header"><span className="card-title">📦 Product Stock Report</span></div>
              <div className="table-wrapper">
                <table>
                  <thead>
                    <tr><th>ID</th><th>Product Name</th><th>Category</th><th>Price (RWF)</th><th>Available Stock</th><th>Sold Stock</th><th>Status</th></tr>
                  </thead>
                  <tbody>
                    {stockResult.map(p => (
                      <tr key={p.product_id}>
                        <td>#{p.product_id}</td>
                        <td style={{ fontWeight: 600 }}>{p.product_name}</td>
                        <td><span className={`badge badge-${p.category.toLowerCase()}`}>{p.category}</span></td>
                        <td>{Number(p.price).toLocaleString()}</td>
                        <td style={{ fontWeight: 700, color: p.available_stock === 0 ? 'var(--danger)' : p.available_stock < 5 ? 'var(--warning)' : 'var(--success)' }}>
                          {p.available_stock}
                        </td>
                        <td style={{ fontWeight: 600, color: 'var(--primary)' }}>{p.sold_stock}</td>
                        <td>
                          {p.available_stock === 0
                            ? <span className="badge" style={{ background: 'var(--danger-light)', color: 'var(--danger)' }}>Out of Stock</span>
                            : p.available_stock < 5
                            ? <span className="badge" style={{ background: 'var(--warning-light)', color: 'var(--warning)' }}>Low Stock</span>
                            : <span className="badge" style={{ background: 'var(--success-light)', color: 'var(--success)' }}>In Stock</span>
                          }
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      )}

      {/* ====== Customer Purchase Report ====== */}
      {tab === 'customer' && (
        <div>
          <div className="card" style={{ marginBottom: 20 }}>
            <div className="card-header"><span className="card-title">👤 Customer Purchase History</span></div>
            <div className="card-body">
              <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'flex-end' }}>
                <div className="form-group" style={{ minWidth: 260 }}>
                  <label>Select Customer</label>
                  <select value={custId} onChange={e => { setCustId(e.target.value); setCustResult(null); }}>
                    <option value="">-- Choose Customer --</option>
                    {customers.map(c => <option key={c.customer_id} value={c.customer_id}>{c.full_name} ({c.phone_number})</option>)}
                  </select>
                </div>
                <button className="btn btn-primary" onClick={runCustReport} disabled={custLoading}>
                  {custLoading ? '⏳ Loading...' : '🔍 View Purchases'}
                </button>
              </div>
            </div>
          </div>

          {custResult && (
            <div>
              <div className="card" style={{ marginBottom: 16, padding: 20 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                  <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--primary-light)', color: 'var(--primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 20 }}>
                    {custResult.customer.full_name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2)}
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontFamily: 'Syne', fontWeight: 700, fontSize: 18 }}>{custResult.customer.full_name}</div>
                    <div style={{ color: 'var(--text-muted)', fontSize: 13 }}>{custResult.customer.phone_number} · {custResult.customer.email || 'No email'}</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--success)' }}>{Number(custResult.total_spent).toLocaleString()} RWF</div>
                    <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>Total Spent · {custResult.purchases.length} purchases</div>
                  </div>
                </div>
              </div>

              <div className="card">
                <div className="table-wrapper">
                  {custResult.purchases.length === 0 ? (
                    <div className="empty-state" style={{ padding: 30 }}>
                      <div className="empty-title">No purchases recorded for this customer</div>
                    </div>
                  ) : (
                    <table>
                      <thead>
                        <tr><th>Sale ID</th><th>Product</th><th>Qty</th><th>Unit Price</th><th>Total</th><th>Date</th></tr>
                      </thead>
                      <tbody>
                        {custResult.purchases.map(p => (
                          <tr key={p.sale_id}>
                            <td>#{p.sale_id}</td>
                            <td style={{ fontWeight: 600 }}>{p.product_name}</td>
                            <td>{p.quantity}</td>
                            <td>{Number(p.unit_price).toLocaleString()} RWF</td>
                            <td style={{ fontWeight: 700, color: 'var(--success)' }}>{Number(p.total_price).toLocaleString()} RWF</td>
                            <td style={{ color: 'var(--text-muted)' }}>{new Date(p.sale_date).toLocaleDateString()}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  )}
                </div>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
