import { useEffect, useMemo, useState } from 'react'
import { toast } from 'react-hot-toast'
import { getDailyReport } from '../services/reportsService'
import { getAllTransactions } from '../services/transactionsService'


function StatCard({ title, value, hint, tone }) {
  const toneMap = {
    purple: 'from-purple-500/20 to-fuchsia-500/10 border-purple-400/30',
    indigo: 'from-indigo-500/20 to-cyan-500/10 border-indigo-400/30',
    emerald: 'from-emerald-500/20 to-teal-500/10 border-emerald-400/30',
    amber: 'from-amber-500/20 to-orange-500/10 border-amber-400/30',
  }

  return (
    <div className={`rounded-2xl border bg-gradient-to-br ${toneMap[tone] || toneMap.purple} p-4`}>
      <div className="text-sm text-slate-300">{title}</div>
      <div className="mt-2 text-2xl font-semibold">{value}</div>
      {hint ? <div className="mt-1 text-xs text-slate-400">{hint}</div> : null}
    </div>
  )
}

export default function DashboardPage() {
  const [daily, setDaily] = useState(null)
  const [recent, setRecent] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const run = async () => {
      try {
        setLoading(true)
        const [d, t] = await Promise.all([getDailyReport(), getAllTransactions()])
        setDaily(d)
        setRecent(Array.isArray(t) ? t.slice(0, 6) : [])
      } catch (err) {
        toast.error(err?.message || 'Failed to load dashboard')
      } finally {
        setLoading(false)
      }
    }
    run()
  }, [])

  const totalStockIn = useMemo(() => {
    const list = daily?.transactions?.stockIn || []
    return Array.isArray(list) ? list.reduce((sum, x) => sum + (x.quantityMoved || 0), 0) : 0
  }, [daily])

  const totalStockOut = useMemo(() => {
    const list = daily?.transactions?.stockOut || []
    return Array.isArray(list) ? list.reduce((sum, x) => sum + (x.quantityMoved || 0), 0) : 0
  }, [daily])

  return (
    <div>
      <div className="flex items-start justify-between gap-4 mb-4">
        <div>
          <h2 className="text-2xl font-semibold">Dashboard</h2>
          <p className="text-sm text-slate-400 mt-1">Inventory overview and recent activity.</p>
        </div>
        <div className="hidden lg:block text-right">
          <div className="text-xs text-slate-400">Today</div>
          <div className="text-sm font-semibold text-white">{daily?.date || '—'}</div>
        </div>
      </div>

      {loading ? (
        <div className="rounded-2xl border border-white/10 bg-white/5 p-6">Loading dashboard...</div>
      ) : (
        <>
          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4 mb-6">
            <StatCard title="Total Products" value={daily?.totalProducts ?? 0} tone="purple" />
            <StatCard title="Total Warehouses" value={daily?.totalWarehouses ?? 0} tone="indigo" />
            <StatCard title="Total Transactions" value={daily?.totalTransactions ?? 0} tone="emerald" />
            <StatCard title="Current Stock" value={daily?.availableStock ?? 0} hint={`Stock In: ${totalStockIn} • Stock Out: ${totalStockOut}`} tone="amber" />
          </div>

          <div className="rounded-2xl border border-white/10 bg-white/5">
            <div className="p-4 border-b border-white/10 flex items-center justify-between">
              <div>
                <div className="text-sm text-slate-300">Recent Transactions</div>
                <div className="text-xs text-slate-400 mt-1">Latest stock movements</div>
              </div>
              <div className="text-xs text-slate-400">Showing {recent.length} items</div>
            </div>

            <div className="p-4 overflow-x-auto">
              <table className="min-w-full text-sm">
                <thead className="text-xs text-slate-400">
                  <tr>
                    <th className="text-left font-medium py-2 px-2">Product</th>
                    <th className="text-left font-medium py-2 px-2">Warehouse</th>
                    <th className="text-left font-medium py-2 px-2">Date</th>
                    <th className="text-left font-medium py-2 px-2">Type</th>
                    <th className="text-right font-medium py-2 px-2">Qty</th>
                  </tr>
                </thead>
                <tbody>
                  {recent.length === 0 ? (
                    <tr>
                      <td colSpan={5} className="text-center py-10 text-slate-500">No transactions yet.</td>
                    </tr>
                  ) : (
                    recent.map((tx) => (
                      <tr key={tx._id} className="border-t border-white/10">
                        <td className="py-3 px-2">
                          <div className="font-medium">{tx.product?.productName || tx.product?.productCode || '—'}</div>
                          <div className="text-xs text-slate-400">{tx.product?.productCode || ''}</div>
                        </td>
                        <td className="py-3 px-2">
                          <div className="font-medium">{tx.warehouse?.warehouseName || '—'}</div>
                          <div className="text-xs text-slate-400">{tx.warehouse?.warehouseCode || ''}</div>
                        </td>
                        <td className="py-3 px-2 text-slate-200">{tx.transactionDate ? new Date(tx.transactionDate).toISOString().split('T')[0] : '—'}</td>
                        <td className="py-3 px-2">
                          <span
                            className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold ${
                              tx.transactionType === 'Stock In' ? 'bg-emerald-500/15 text-emerald-200 border border-emerald-400/20' : 'bg-red-500/15 text-red-200 border border-red-400/20'
                            }`}
                          >
                            {tx.transactionType}
                          </span>
                        </td>
                        <td className="py-3 px-2 text-right">
                          <div className="font-semibold">{tx.quantityMoved}</div>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </>
      )}
    </div>
  )
}

