import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import {
  Settings2, BarChart2, Activity, ImageIcon, DollarSign, Cpu,
  TrendingUp, LineChart, PieChart, Clock, LayoutGrid, Table2, Users, Server,
} from 'lucide-react'
import { getDashboardConfig } from '../../api/dashboard'
import type { WidgetType } from '../../api/dashboard'
import { DashboardTimeframeProvider, useDashboardTimeframe } from './DashboardTimeframeContext'
import type { Preset } from './DashboardTimeframeContext'
import WidgetContainer from './WidgetContainer'
import DashboardCustomizeModal from './DashboardCustomizeModal'
import ProductionStatsWidget from './widgets/ProductionStatsWidget'
import QueueStatusWidget from './widgets/QueueStatusWidget'
import RecentRendersWidget from './widgets/RecentRendersWidget'
import CostOverviewWidget from './widgets/CostOverviewWidget'
import WorkerStatusWidget from './widgets/WorkerStatusWidget'
import KPISummaryWidget from './widgets/KPISummaryWidget'
import OrderThroughputWidget from './widgets/OrderThroughputWidget'
import RevenueChartWidget from './widgets/RevenueChartWidget'
import ItemStatusWidget from './widgets/ItemStatusWidget'
import ProcessingTimesWidget from './widgets/ProcessingTimesWidget'
import RenderTimeByOutputTypeWidget from './widgets/RenderTimeByOutputTypeWidget'
import OutputTypeUsageWidget from './widgets/OutputTypeUsageWidget'
import TopProductsWidget from './widgets/TopProductsWidget'
import OrdersByUserWidget from './widgets/OrdersByUserWidget'
import RenderBackendStatsWidget from './widgets/RenderBackendStatsWidget'

const WIDGET_META: Record<WidgetType, { title: string; icon: React.ReactNode }> = {
  ProductionStats:          { title: 'Production Stats',           icon: <BarChart2 size={15} /> },
  QueueStatus:              { title: 'Queue Status',               icon: <Activity size={15} /> },
  RecentRenders:            { title: 'Recent Renders',             icon: <ImageIcon size={15} /> },
  CostOverview:             { title: 'Cost Overview',              icon: <DollarSign size={15} /> },
  WorkerStatus:             { title: 'Worker Status',              icon: <Cpu size={15} /> },
  KPISummary:               { title: 'KPI Summary',                icon: <TrendingUp size={15} /> },
  OrderThroughput:          { title: 'Order Throughput',           icon: <LineChart size={15} /> },
  RevenueChart:             { title: 'Revenue',                    icon: <DollarSign size={15} /> },
  ItemStatus:               { title: 'Item & Render Status',       icon: <PieChart size={15} /> },
  ProcessingTimes:          { title: 'Processing Times',           icon: <Clock size={15} /> },
  RenderTimeByOutputType:   { title: 'Render Time by Output Type', icon: <BarChart2 size={15} /> },
  OutputTypeUsage:          { title: 'Output Type Usage',          icon: <LayoutGrid size={15} /> },
  TopProducts:              { title: 'Top 10 Products',            icon: <Table2 size={15} /> },
  OrdersByUser:             { title: 'Orders by User',             icon: <Users size={15} /> },
  RenderBackendStats:       { title: 'Render Backend Stats',       icon: <Server size={15} /> },
}

// Analytics widget types that need a timeframe
const ANALYTICS_WIDGET_TYPES = new Set<WidgetType>([
  'ProductionStats', 'KPISummary', 'OrderThroughput', 'RevenueChart',
  'ItemStatus', 'ProcessingTimes', 'RenderTimeByOutputType',
  'OutputTypeUsage', 'TopProducts', 'OrdersByUser', 'RenderBackendStats',
])

const PRESETS: { key: Preset; label: string }[] = [
  { key: '4w', label: '4 W' },
  { key: '3m', label: '3 M' },
  { key: '6m', label: '6 M' },
  { key: '1y', label: '1 Y' },
  { key: 'all', label: 'All' },
  { key: 'custom', label: 'Custom' },
]

function WidgetBody({ type }: { type: WidgetType }) {
  switch (type) {
    case 'ProductionStats':        return <ProductionStatsWidget />
    case 'QueueStatus':            return <QueueStatusWidget />
    case 'RecentRenders':          return <RecentRendersWidget />
    case 'CostOverview':           return <CostOverviewWidget />
    case 'WorkerStatus':           return <WorkerStatusWidget />
    case 'KPISummary':             return <KPISummaryWidget />
    case 'OrderThroughput':        return <OrderThroughputWidget />
    case 'RevenueChart':           return <RevenueChartWidget />
    case 'ItemStatus':             return <ItemStatusWidget />
    case 'ProcessingTimes':        return <ProcessingTimesWidget />
    case 'RenderTimeByOutputType': return <RenderTimeByOutputTypeWidget />
    case 'OutputTypeUsage':        return <OutputTypeUsageWidget />
    case 'TopProducts':            return <TopProductsWidget />
    case 'OrdersByUser':           return <OrdersByUserWidget />
    case 'RenderBackendStats':     return <RenderBackendStatsWidget />
    default:                       return <p className="text-xs text-content-muted">Unknown widget</p>
  }
}

function TimeframeSelector({ widgets }: { widgets: WidgetType[] }) {
  const { preset, customFrom, customTo, setPreset, setCustomFrom, setCustomTo } = useDashboardTimeframe()
  const hasAnalytics = widgets.some((t) => ANALYTICS_WIDGET_TYPES.has(t))
  if (!hasAnalytics) return null

  return (
    <div className="flex flex-wrap items-center gap-2">
      {PRESETS.map(({ key, label }) => (
        <button
          key={key}
          onClick={() => setPreset(key)}
          className={`px-3 py-1 rounded-full text-xs font-semibold transition-colors ${
            preset === key
              ? 'text-white'
              : 'bg-surface-muted text-content-secondary hover:bg-surface-hover'
          }`}
          style={preset === key ? { backgroundColor: 'var(--color-accent)' } : undefined}
        >
          {label}
        </button>
      ))}
      {preset === 'custom' && (
        <div className="flex items-center gap-2 ml-1">
          <input
            type="date"
            value={customFrom}
            onChange={(e) => setCustomFrom(e.target.value)}
            className="border border-border-default rounded px-2 py-0.5 text-xs"
          />
          <span className="text-content-muted text-xs">–</span>
          <input
            type="date"
            value={customTo}
            onChange={(e) => setCustomTo(e.target.value)}
            className="border border-border-default rounded px-2 py-0.5 text-xs"
          />
        </div>
      )}
    </div>
  )
}

function DashboardGridInner() {
  const [showCustomize, setShowCustomize] = useState(false)

  const { data: widgets, isLoading } = useQuery({
    queryKey: ['dashboard-config'],
    queryFn: getDashboardConfig,
    staleTime: 300_000,
  })

  const widgetTypes = (widgets ?? []).map((w) => w.widget_type as WidgetType)

  return (
    <div className="space-y-4">
      {/* Toolbar */}
      <div className="flex flex-wrap items-center gap-3 justify-between">
        <TimeframeSelector widgets={widgetTypes} />
        <button
          onClick={() => setShowCustomize(true)}
          className="btn-secondary text-sm flex items-center gap-1.5 ml-auto"
        >
          <Settings2 size={14} />
          Anpassen
        </button>
      </div>

      {/* Grid */}
      {isLoading ? (
        <div className="grid grid-cols-3 gap-4">
          {[0, 1, 2].map((i) => (
            <div key={i} className="h-40 rounded-xl animate-pulse bg-surface-muted" />
          ))}
        </div>
      ) : (widgets ?? []).length === 0 ? (
        <div className="rounded-xl border border-border-default p-8 text-center text-content-muted text-sm">
          No widgets configured. Click <strong>Anpassen</strong> to add widgets.
        </div>
      ) : (
        <div
          className="grid gap-4"
          style={{ gridTemplateColumns: 'repeat(3, minmax(0, 1fr))' }}
        >
          {(widgets ?? []).map((w, i) => {
            const pos = w.position
            const meta = WIDGET_META[w.widget_type as WidgetType] ?? {
              title: w.widget_type,
              icon: null,
            }
            return (
              <div
                key={`${w.widget_type}-${i}`}
                style={{
                  gridColumnStart: pos.col + 1,
                  gridColumnEnd: `span ${pos.w}`,
                  gridRowStart: pos.row + 1,
                  gridRowEnd: `span ${pos.h}`,
                }}
              >
                <WidgetContainer title={meta.title} icon={meta.icon}>
                  <WidgetBody type={w.widget_type as WidgetType} />
                </WidgetContainer>
              </div>
            )
          })}
        </div>
      )}

      {/* Customize modal */}
      {showCustomize && (
        <DashboardCustomizeModal
          currentWidgets={widgets ?? []}
          onClose={() => setShowCustomize(false)}
        />
      )}
    </div>
  )
}

export default function DashboardGrid() {
  return (
    <DashboardTimeframeProvider>
      <DashboardGridInner />
    </DashboardTimeframeProvider>
  )
}
