import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { X, Save } from 'lucide-react'
import { toast } from 'sonner'
import { updateDashboardConfig, updateTenantDefaultDashboard } from '../../api/dashboard'
import type { WidgetConfig, WidgetType } from '../../api/dashboard'

const WIDGET_LABELS: Record<WidgetType, string> = {
  ProductionStats:          'Production Stats',
  QueueStatus:              'Queue Status',
  RecentRenders:            'Recent Renders',
  CostOverview:             'Cost Overview',
  WorkerStatus:             'Worker Status',
  KPISummary:               'KPI Summary',
  OrderThroughput:          'Order Throughput',
  RevenueChart:             'Revenue',
  ItemStatus:               'Item & Render Status',
  ProcessingTimes:          'Processing Times',
  RenderTimeByOutputType:   'Render Time by Output Type',
  OutputTypeUsage:          'Output Type Usage',
  TopProducts:              'Top 10 Products',
  OrdersByUser:             'Orders by User',
  RenderBackendStats:       'Render Backend Stats',
}

const OPERATIONAL_TYPES: WidgetType[] = [
  'ProductionStats',
  'QueueStatus',
  'RecentRenders',
  'CostOverview',
  'WorkerStatus',
]

const ANALYTICS_TYPES: WidgetType[] = [
  'KPISummary',
  'OrderThroughput',
  'RevenueChart',
  'ItemStatus',
  'ProcessingTimes',
  'RenderTimeByOutputType',
  'OutputTypeUsage',
  'TopProducts',
  'OrdersByUser',
  'RenderBackendStats',
]

const ALL_WIDGET_TYPES: WidgetType[] = [...OPERATIONAL_TYPES, ...ANALYTICS_TYPES]

function recalculatePositions(widgets: WidgetConfig[]): WidgetConfig[] {
  return widgets.map((w, i) => ({
    ...w,
    position: {
      col: i % 3,
      row: Math.floor(i / 3),
      w: 1,
      h: 1,
    },
  }))
}

interface Props {
  currentWidgets: WidgetConfig[]
  onClose: () => void
  /** When true, saves to tenant-default instead of user config */
  tenantMode?: boolean
}

export default function DashboardCustomizeModal({
  currentWidgets,
  onClose,
  tenantMode = false,
}: Props) {
  const qc = useQueryClient()

  const [enabled, setEnabled] = useState<Set<WidgetType>>(
    new Set(currentWidgets.map((w) => w.widget_type as WidgetType))
  )

  const saveMut = useMutation({
    mutationFn: async () => {
      const selected = ALL_WIDGET_TYPES.filter((t) => enabled.has(t))
      const configMap = new Map(
        currentWidgets.map((w) => [w.widget_type, w.config])
      )
      const newWidgets: WidgetConfig[] = selected.map((t) => ({
        widget_type: t,
        position: { col: 0, row: 0, w: 1, h: 1 },
        config: configMap.get(t),
      }))
      const layouted = recalculatePositions(newWidgets)
      if (tenantMode) {
        return updateTenantDefaultDashboard(layouted)
      }
      return updateDashboardConfig(layouted)
    },
    onSuccess: () => {
      toast.success('Dashboard layout saved')
      qc.invalidateQueries({ queryKey: ['dashboard-config'] })
      onClose()
    },
    onError: (e: unknown) => {
      const msg = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(msg ?? 'Failed to save')
    },
  })

  function toggle(type: WidgetType) {
    setEnabled((prev) => {
      const next = new Set(prev)
      if (next.has(type)) {
        next.delete(type)
      } else {
        next.add(type)
      }
      return next
    })
  }

  function renderGroup(title: string, types: WidgetType[]) {
    return (
      <div>
        <p className="text-xs font-semibold text-content-muted uppercase tracking-wide mb-2 px-1">{title}</p>
        <div className="space-y-1.5">
          {types.map((type) => (
            <label
              key={type}
              className="flex items-center gap-3 cursor-pointer rounded-lg border border-border-default px-4 py-2.5 hover:border-accent transition-colors"
            >
              <input
                type="checkbox"
                checked={enabled.has(type)}
                onChange={() => toggle(type)}
                className="w-4 h-4 rounded accent-accent"
              />
              <span className="text-sm font-medium text-content">
                {WIDGET_LABELS[type]}
              </span>
            </label>
          ))}
        </div>
      </div>
    )
  }

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center"
      style={{ backgroundColor: 'rgba(0,0,0,0.5)' }}
    >
      <div
        className="rounded-xl shadow-xl w-full max-w-md mx-4 max-h-[90vh] flex flex-col"
        style={{ backgroundColor: 'var(--color-bg-surface)' }}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-5 py-4 border-b border-border-default flex-shrink-0">
          <h2 className="font-semibold text-content">
            {tenantMode ? 'Edit Tenant Default Dashboard' : 'Customize Dashboard'}
          </h2>
          <button
            onClick={onClose}
            className="text-content-muted hover:text-content transition-colors"
          >
            <X size={18} />
          </button>
        </div>

        {/* Widget list */}
        <div className="px-5 py-4 space-y-4 overflow-y-auto">
          <p className="text-xs text-content-muted">
            Select which widgets are visible on the dashboard.
          </p>
          {renderGroup('Operational', OPERATIONAL_TYPES)}
          {renderGroup('Analytics', ANALYTICS_TYPES)}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-3 px-5 py-4 border-t border-border-default flex-shrink-0">
          <button onClick={onClose} className="btn-secondary text-sm">
            Cancel
          </button>
          <button
            onClick={() => saveMut.mutate()}
            disabled={saveMut.isPending}
            className="btn-primary text-sm flex items-center gap-2"
          >
            <Save size={14} />
            {saveMut.isPending ? 'Saving…' : 'Save'}
          </button>
        </div>
      </div>
    </div>
  )
}
