import { useState, useEffect } from 'react';
import api from '../services/api';
import { formatCurrency, formatNumber, startOfMonth, today } from '../utils/formatters';
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid } from 'recharts';

export default function SalesReport() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [filters, setFilters] = useState({ startDate: startOfMonth(), endDate: today(), groupBy: 'day' });

  async function fetchReport() {
    setLoading(true);
    try {
      const res = await api.get('/reports/sales', { params: filters });
      setData(res.data.data);
    } finally { setLoading(false); }
  }

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

  const setF = (k, v) => setFilters(p => ({ ...p, [k]: v }));

  const chartData = (data?.data || []).map(r => ({
    period: r.period,
    Penjualan: parseFloat(r.total_revenue),
    Transaksi: parseInt(r.total_transactions),
  }));

  const totals = data?.totals || {};

  return (
    <div className="space-y-6">
      <div className="card p-4 flex flex-wrap gap-3 items-end">
        <div>
          <label className="label">Dari</label>
          <input type="date" className="input" value={filters.startDate} onChange={e => setF('startDate', e.target.value)} />
        </div>
        <div>
          <label className="label">Sampai</label>
          <input type="date" className="input" value={filters.endDate} onChange={e => setF('endDate', e.target.value)} />
        </div>
        <div>
          <label className="label">Kelompokkan</label>
          <select className="input" value={filters.groupBy} onChange={e => setF('groupBy', e.target.value)}>
            <option value="day">Harian</option>
            <option value="month">Bulanan</option>
            <option value="year">Tahunan</option>
          </select>
        </div>
        <button onClick={fetchReport} disabled={loading} className="btn-primary">
          {loading ? 'Memuat...' : 'Tampilkan'}
        </button>
      </div>

      {data && (
        <>
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            {[
              { label: 'Total Transaksi', value: formatNumber(totals.total_transactions), color: 'text-blue-600' },
              { label: 'Total Omzet', value: formatCurrency(totals.total_revenue), color: 'text-orange-600' },
              { label: 'Total HPP', value: formatCurrency(totals.total_hpp), color: 'text-emerald-600' },
            ].map(s => (
              <div key={s.label} className="card p-5">
                <p className="text-sm text-gray-500">{s.label}</p>
                <p className={`text-2xl font-bold mt-1 ${s.color}`}>{s.value}</p>
              </div>
            ))}
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            {[
              { key: 'tunai',    label: 'Tunai',    icon: '💵', color: 'border-green-400',  textColor: 'text-green-600'  },
              { key: 'transfer', label: 'Transfer', icon: '🏦', color: 'border-blue-400',   textColor: 'text-blue-600'   },
              { key: 'qris',     label: 'QRIS',     icon: '📱', color: 'border-purple-400', textColor: 'text-purple-600' },
            ].map(({ key, label, icon, color, textColor }) => {
              const pm = data.payment_summary?.[key];
              return (
                <div key={key} className={`card p-5 border-l-4 ${color}`}>
                  <div className="flex items-center justify-between mb-2">
                    <p className="text-sm font-semibold text-gray-600">{icon} {label}</p>
                    <span className="text-xs text-gray-400">{formatNumber(pm?.total_transactions ?? 0)} transaksi</span>
                  </div>
                  <p className={`text-xl font-bold ${textColor}`}>{formatCurrency(pm?.total_revenue ?? 0)}</p>
                </div>
              );
            })}
          </div>

          {chartData.length > 0 && (
            <div className="card p-5">
              <h3 className="font-semibold text-gray-800 mb-4">Grafik Penjualan</h3>
              <ResponsiveContainer width="100%" height={280}>
                <BarChart data={chartData} margin={{ top: 0, right: 0, left: 0, bottom: 0 }}>
                  <CartesianGrid strokeDasharray="3 3" vertical={false} />
                  <XAxis dataKey="period" tick={{ fontSize: 11 }} />
                  <YAxis tick={{ fontSize: 11 }} tickFormatter={v => formatCurrency(v).replace('Rp ', 'Rp')} width={80} />
                  <Tooltip formatter={(v) => formatCurrency(v)} labelStyle={{ fontWeight: 600 }} />
                  <Bar dataKey="Penjualan" fill="#f97316" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            </div>
          )}

          <div className="card overflow-hidden">
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-gray-50 border-b">
                  <tr>
                    {['Periode','Transaksi','Total Omzet'].map(h => (
                      <th key={h} className="table-th">{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {data.data.length === 0 ? (
                    <tr><td colSpan={3} className="table-td text-center py-8 text-gray-400">Tidak ada data</td></tr>
                  ) : data.data.map((row, i) => (
                    <tr key={i} className="hover:bg-gray-50">
                      <td className="table-td font-medium">{row.period}</td>
                      <td className="table-td">{formatNumber(row.total_transactions)}</td>
                      <td className="table-td font-bold text-orange-600">{formatCurrency(row.total_revenue)}</td>
                    </tr>
                  ))}
                  {data.data.length > 0 && (
                    <tr className="bg-gray-50 font-semibold">
                      <td className="table-td">TOTAL</td>
                      <td className="table-td">{formatNumber(totals.total_transactions)}</td>
                      <td className="table-td text-orange-600">{formatCurrency(totals.total_revenue)}</td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </>
      )}
    </div>
  );
}
