import { useQuery } from '@tanstack/react-query'
import {
  ResponsiveContainer, PieChart, Pie, Cell, Legend, Tooltip,
} from 'recharts'
import { getDashboardKPIs } from '../../../api/analytics'
import { useDashboardTimeframe } from '../DashboardTimeframeContext'

const TOOLTIP_STYLE = {
  backgroundColor: 'var(--color-bg-surface)',
  border: '1px solid var(--color-border)',
  borderRadius: '8px',
  color: 'var(--color-text)',
}

export default function ItemStatusWidget() {
  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="space-y-3"><div className="h-40 animate-pulse rounded-lg bg-surface-muted" /><div className="h-40 animate-pulse rounded-lg bg-surface-muted" /></div>
  if (error) return <p className="text-xs text-red-500">Failed to load item status</p>
  if (!data) return null

  const itemPie = [
    { name: 'Pending', value: data.item_status.pending, color: '#f59e0b' },
    { name: 'Approved', value: data.item_status.approved, color: '#22c55e' },
    { name: 'Rejected', value: data.item_status.rejected, color: '#ef4444' },
  ]

  const renderPie = [
    { name: 'Pending', value: data.render_status.pending, color: '#f59e0b' },
    { name: 'Processing', value: data.render_status.processing, color: '#3b82f6' },
    { name: 'Completed', value: data.render_status.completed, color: '#22c55e' },
    { name: 'Failed', value: data.render_status.failed, color: '#ef4444' },
  ]

  const noItemData = itemPie.every((d) => d.value === 0)
  const noRenderData = renderPie.every((d) => d.value === 0)

  return (
    <div className="space-y-4">
      <div>
        <p className="text-xs font-medium text-content-secondary mb-1">Item Status</p>
        {noItemData ? (
          <p className="text-xs text-content-muted text-center py-4">No data yet</p>
        ) : (
          <ResponsiveContainer width="100%" height={160}>
            <PieChart>
              <Pie data={itemPie} dataKey="value" nameKey="name" cx="50%" cy="45%" outerRadius={55}
                label={({ name, value }) => `${name}: ${value}`} labelLine={false}>
                {itemPie.map((e) => <Cell key={e.name} fill={e.color} />)}
              </Pie>
              <Legend wrapperStyle={{ fontSize: 11 }} />
              <Tooltip contentStyle={TOOLTIP_STYLE} />
            </PieChart>
          </ResponsiveContainer>
        )}
      </div>

      <div>
        <p className="text-xs font-medium text-content-secondary mb-1">Render Status</p>
        {noRenderData ? (
          <p className="text-xs text-content-muted text-center py-4">No data yet</p>
        ) : (
          <ResponsiveContainer width="100%" height={160}>
            <PieChart>
              <Pie data={renderPie} dataKey="value" nameKey="name" cx="50%" cy="45%" outerRadius={55}
                label={({ name, value }) => `${name}: ${value}`} labelLine={false}>
                {renderPie.map((e) => <Cell key={e.name} fill={e.color} />)}
              </Pie>
              <Legend wrapperStyle={{ fontSize: 11 }} />
              <Tooltip contentStyle={TOOLTIP_STYLE} />
            </PieChart>
          </ResponsiveContainer>
        )}
      </div>
    </div>
  )
}
