import { useQuery } from '@tanstack/react-query'
import { getDashboardKPIs } from '../../../api/analytics'
import { useDashboardTimeframe } from '../DashboardTimeframeContext'

export default function OrdersByUserWidget() {
  const { dateFrom, dateTo } = useDashboardTimeframe()
  const { data, isLoading, error } = useQuery({
    queryKey: ['analytics-kpis', dateFrom, dateTo],
    queryFn: () => getDashboardKPIs(dateFrom, dateTo),
    staleTime: 60_000,
  })

  if (isLoading) return <div className="h-52 animate-pulse rounded-lg bg-surface-muted" />
  if (error) return <p className="text-xs text-red-500">Failed to load user data</p>
  if (!data || data.orders_by_user.length === 0) {
    return <p className="text-xs text-content-muted text-center py-8">No data yet</p>
  }

  return (
    <div className="overflow-x-auto">
      <table className="w-full text-sm">
        <thead>
          <tr className="border-b border-border-light text-left">
            <th className="py-2 pr-3 text-content-secondary font-medium text-xs">Name</th>
            <th className="py-2 pr-3 text-content-secondary font-medium text-xs">Email</th>
            <th className="py-2 pr-3 text-content-secondary font-medium text-xs">Role</th>
            <th className="py-2 pr-3 text-content-secondary font-medium text-right text-xs">Orders</th>
            <th className="py-2 text-content-secondary font-medium text-right text-xs">Revenue</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-border-light">
          {data.orders_by_user.map((u) => (
            <tr key={u.email} className="hover:bg-surface-hover">
              <td className="py-1.5 pr-3 text-xs text-content">{u.full_name}</td>
              <td className="py-1.5 pr-3 text-xs text-content-muted">{u.email}</td>
              <td className="py-1.5 pr-3">
                <span className="text-xs px-2 py-0.5 rounded-full bg-surface-muted text-content-secondary">
                  {u.role === 'project_manager' ? 'PM' : u.role}
                </span>
              </td>
              <td className="py-1.5 pr-3 font-medium text-xs text-content text-right">{u.order_count}</td>
              <td className="py-1.5 font-medium text-xs text-content text-right">€ {u.revenue.toFixed(2)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}
