'use client';

import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import Link from 'next/link';
import {
  ArrowLeft,
  Save,
  Eye,
  Plus,
  Trash2,
  Settings,
  GripVertical,
  Layout,
  Copy,
  Download,
  Maximize2,
  Minimize2,
  ChevronRight,
  Hash,
  BarChart,
  Table,
  Type,
  Filter,
  Puzzle,
  Activity,
  Gauge,
  ArrowLeftRight,
  BarChart3,
  LineChart,
  PieChart,
  Circle,
  AreaChart,
  Radar,
  LayoutList,
  Heading,
  Calendar,
  ChevronDown,
  X,
  Check,
  Sparkles,
  FileText,
  Loader2,
  Wand2,
} from 'lucide-react';
import { InternalHeader } from '@/components/ui/internal-header';

interface WidgetDefinition {
  key: string;
  name: string;
  description: string;
  category: string;
  widgetType: string;
  icon: string;
  defaultConfig: Record<string, unknown>;
  configSchema: ConfigProperty[];
  defaultSize: { w: number; h: number };
  minSize?: { w: number; h: number };
}

interface ConfigProperty {
  key: string;
  label: string;
  type: 'string' | 'number' | 'boolean' | 'select' | 'color' | 'multiselect';
  options?: { value: string; label: string }[];
  defaultValue?: unknown;
  required?: boolean;
}

interface PlacedWidget {
  id: string;
  widgetKey: string;
  config: Record<string, unknown>;
  position: { x: number; y: number };
  size: { w: number; h: number };
  dataSource?: string;
}

const ICON_MAP: Record<string, React.ElementType> = {
  Hash,
  Activity,
  Gauge,
  ArrowLeftRight,
  BarChart3,
  LineChart,
  BarChart,
  PieChart,
  Circle,
  AreaChart,
  Radar,
  Table,
  LayoutList,
  Type,
  Heading,
  Calendar,
  ChevronDown,
  Filter,
  Puzzle,
};

const CATEGORY_ICONS: Record<string, React.ElementType> = {
  metric: Hash,
  chart: BarChart,
  table: Table,
  text: Type,
  filter: Filter,
  custom: Puzzle,
};

const CATEGORY_COLORS: Record<string, string> = {
  metric: 'bg-brand-deep/20 border-brand-deep/50 text-brand',
  chart: 'bg-brand-secondary/20 border-brand-secondary/50 text-brand-secondary-light',
  table: 'bg-green-500/20 border-green-500/50 text-green-400',
  text: 'bg-amber-500/20 border-amber-500/50 text-amber-400',
  filter: 'bg-blue-500/20 border-blue-500/50 text-blue-400',
  custom: 'bg-pink-500/20 border-pink-500/50 text-pink-400',
};

export default function ReportBuilderPage() {
  const [widgets, setWidgets] = useState<WidgetDefinition[]>([]);
  const [placedWidgets, setPlacedWidgets] = useState<PlacedWidget[]>([]);
  const [selectedWidget, setSelectedWidget] = useState<PlacedWidget | null>(null);
  const [reportName, setReportName] = useState('Untitled Report');
  const [reportDescription, setReportDescription] = useState('');
  const [expandedCategory, setExpandedCategory] = useState<string | null>('metric');
  const [isPreviewMode, setIsPreviewMode] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [showSaveModal, setShowSaveModal] = useState(false);
  const [draggedWidget, setDraggedWidget] = useState<WidgetDefinition | null>(null);
  const [gridCols] = useState(12);
  const [gridRows] = useState(8);
  const [reportModule, setReportModule] = useState('general');
  const [isPublic, setIsPublic] = useState(false);

  useEffect(() => {
    fetchWidgets();
  }, []);

  const fetchWidgets = async () => {
    try {
      const res = await fetch('/api/reports/widgets');
      const data = await res.json();
      setWidgets(data.widgets || []);
    } catch (error) {
      console.error('Error fetching widgets:', error);
    }
  };

  const handleDragStart = (widget: WidgetDefinition) => {
    setDraggedWidget(widget);
  };

  const handleDragEnd = () => {
    setDraggedWidget(null);
  };

  const handleCanvasDrop = (e: React.DragEvent) => {
    e.preventDefault();
    if (!draggedWidget) return;

    const canvas = e.currentTarget.getBoundingClientRect();
    const cellWidth = canvas.width / gridCols;
    const cellHeight = canvas.height / gridRows;

    const x = Math.floor((e.clientX - canvas.left) / cellWidth);
    const y = Math.floor((e.clientY - canvas.top) / cellHeight);

    const newWidget: PlacedWidget = {
      id: `widget-${Date.now()}`,
      widgetKey: draggedWidget.key,
      config: { ...draggedWidget.defaultConfig },
      position: { x: Math.max(0, Math.min(x, gridCols - draggedWidget.defaultSize.w)), y: Math.max(0, Math.min(y, gridRows - draggedWidget.defaultSize.h)) },
      size: { ...draggedWidget.defaultSize },
    };

    setPlacedWidgets([...placedWidgets, newWidget]);
    setSelectedWidget(newWidget);
    setDraggedWidget(null);
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
  };

  const removeWidget = (id: string) => {
    setPlacedWidgets(placedWidgets.filter((w) => w.id !== id));
    if (selectedWidget?.id === id) setSelectedWidget(null);
  };

  const duplicateWidget = (widget: PlacedWidget) => {
    const newWidget: PlacedWidget = {
      ...widget,
      id: `widget-${Date.now()}`,
      position: { x: widget.position.x + 1, y: widget.position.y + 1 },
    };
    setPlacedWidgets([...placedWidgets, newWidget]);
  };

  const updateWidgetConfig = (id: string, key: string, value: unknown) => {
    setPlacedWidgets(
      placedWidgets.map((w) =>
        w.id === id ? { ...w, config: { ...w.config, [key]: value } } : w
      )
    );
    if (selectedWidget?.id === id) {
      setSelectedWidget({ ...selectedWidget, config: { ...selectedWidget.config, [key]: value } });
    }
  };

  const updateWidgetSize = (id: string, size: { w: number; h: number }) => {
    setPlacedWidgets(
      placedWidgets.map((w) => (w.id === id ? { ...w, size } : w))
    );
  };

  const saveReport = async () => {
    setIsSaving(true);
    try {
      const res = await fetch('/api/reports/custom', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: reportName,
          description: reportDescription,
          createdById: 'system',
          module: reportModule,
          reportType: 'mixed',
          layout: { cols: gridCols, rows: gridRows },
          widgets: placedWidgets,
          isPublic,
        }),
      });

      if (res.ok) {
        setShowSaveModal(false);
        alert('Report saved successfully!');
      } else {
        throw new Error('Failed to save report');
      }
    } catch (error) {
      console.error('Error saving report:', error);
      alert('Failed to save report');
    } finally {
      setIsSaving(false);
    }
  };

  const getWidgetDefinition = (key: string) => widgets.find((w) => w.key === key);

  const widgetsByCategory = widgets.reduce((acc, widget) => {
    if (!acc[widget.category]) acc[widget.category] = [];
    acc[widget.category].push(widget);
    return acc;
  }, {} as Record<string, WidgetDefinition[]>);

  return (
    <div className="min-h-screen bg-brand-bg">
      <InternalHeader />
      
      {/* Builder Header */}
      <header className="sticky top-16 z-40 bg-slate-900/95 backdrop-blur border-b border-slate-700">
        <div className="flex items-center justify-between px-4 py-3">
          <div className="flex items-center gap-4">
            <Link
              href="/ghost-control/reports"
              className="p-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-gray-400 hover:text-white transition-colors"
            >
              <ArrowLeft className="w-5 h-5" />
            </Link>
            <div>
              <input
                type="text"
                value={reportName}
                onChange={(e) => setReportName(e.target.value)}
                className="bg-transparent text-xl font-bold text-white border-none focus:outline-none focus:ring-2 focus:ring-brand-deep/50 rounded px-2 py-1 -ml-2"
              />
              <p className="text-sm text-gray-500 px-2">Custom Report Builder</p>
            </div>
          </div>

          <div className="flex items-center gap-2">
            <button
              onClick={() => setIsPreviewMode(!isPreviewMode)}
              className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${
                isPreviewMode
                  ? 'bg-brand-deep text-white'
                  : 'bg-slate-800 text-gray-300 hover:bg-slate-700'
              }`}
            >
              {isPreviewMode ? <Minimize2 className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
              {isPreviewMode ? 'Edit' : 'Preview'}
            </button>
            <button
              onClick={() => setShowSaveModal(true)}
              className="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-brand-deep to-brand-secondary text-white rounded-lg hover:opacity-90 transition-opacity"
            >
              <Save className="w-4 h-4" />
              Save Report
            </button>
          </div>
        </div>
      </header>

      <div className="flex" style={{ height: 'calc(100vh - 130px)' }}>
        {/* Widget Palette - Left Sidebar */}
        {!isPreviewMode && (
          <aside className="w-72 bg-slate-900/50 border-r border-slate-700 overflow-y-auto">
            <div className="p-4">
              <h3 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-4">
                Widget Library
              </h3>

              {Object.entries(widgetsByCategory).map(([category, categoryWidgets]) => {
                const CategoryIcon = CATEGORY_ICONS[category] || Puzzle;
                const isExpanded = expandedCategory === category;

                return (
                  <div key={category} className="mb-2">
                    <button
                      onClick={() => setExpandedCategory(isExpanded ? null : category)}
                      className="w-full flex items-center justify-between p-3 bg-slate-800/50 rounded-lg hover:bg-slate-800 transition-colors"
                    >
                      <div className="flex items-center gap-2">
                        <CategoryIcon className="w-4 h-4 text-gray-400" />
                        <span className="text-sm font-medium text-white capitalize">{category}s</span>
                        <span className="text-xs text-gray-500">({categoryWidgets.length})</span>
                      </div>
                      <ChevronRight
                        className={`w-4 h-4 text-gray-400 transition-transform ${isExpanded ? 'rotate-90' : ''}`}
                      />
                    </button>

                    <AnimatePresence>
                      {isExpanded && (
                        <motion.div
                          initial={{ height: 0, opacity: 0 }}
                          animate={{ height: 'auto', opacity: 1 }}
                          exit={{ height: 0, opacity: 0 }}
                          className="overflow-hidden"
                        >
                          <div className="p-2 space-y-2">
                            {categoryWidgets.map((widget) => {
                              const Icon = ICON_MAP[widget.icon] || Hash;
                              return (
                                <div
                                  key={widget.key}
                                  draggable
                                  onDragStart={() => handleDragStart(widget)}
                                  onDragEnd={handleDragEnd}
                                  className={`p-3 rounded-lg border cursor-grab active:cursor-grabbing transition-all hover:scale-[1.02] ${CATEGORY_COLORS[category]}`}
                                >
                                  <div className="flex items-center gap-2">
                                    <Icon className="w-4 h-4" />
                                    <span className="text-sm font-medium">{widget.name}</span>
                                  </div>
                                  <p className="text-xs text-gray-400 mt-1 line-clamp-1">
                                    {widget.description}
                                  </p>
                                </div>
                              );
                            })}
                          </div>
                        </motion.div>
                      )}
                    </AnimatePresence>
                  </div>
                );
              })}
            </div>
          </aside>
        )}

        {/* Canvas Area */}
        <main className={`flex-1 p-6 overflow-auto ${isPreviewMode ? '' : 'bg-slate-950/50'}`}>
          <div
            onDrop={handleCanvasDrop}
            onDragOver={handleDragOver}
            className={`relative w-full h-full min-h-[600px] rounded-xl border-2 border-dashed transition-colors ${
              draggedWidget
                ? 'border-brand-deep bg-brand-deep/5'
                : 'border-slate-700 bg-slate-900/30'
            }`}
            style={{
              display: 'grid',
              gridTemplateColumns: `repeat(${gridCols}, 1fr)`,
              gridTemplateRows: `repeat(${gridRows}, 1fr)`,
              gap: '8px',
              padding: '8px',
            }}
          >
            {/* Grid overlay */}
            {!isPreviewMode &&
              Array.from({ length: gridCols * gridRows }).map((_, i) => (
                <div
                  key={i}
                  className="border border-slate-800/50 rounded bg-slate-800/10"
                />
              ))}

            {/* Placed Widgets */}
            {placedWidgets.map((widget) => {
              const definition = getWidgetDefinition(widget.widgetKey);
              const Icon = definition ? ICON_MAP[definition.icon] || Hash : Hash;

              return (
                <motion.div
                  key={widget.id}
                  layoutId={widget.id}
                  initial={{ opacity: 0, scale: 0.8 }}
                  animate={{ opacity: 1, scale: 1 }}
                  onClick={() => setSelectedWidget(widget)}
                  className={`absolute rounded-lg border transition-all cursor-pointer ${
                    selectedWidget?.id === widget.id
                      ? 'border-brand-deep ring-2 ring-brand-deep/30'
                      : 'border-slate-600 hover:border-slate-500'
                  } ${definition ? CATEGORY_COLORS[definition.category]?.replace('border-', 'bg-').replace('/50', '/30') : 'bg-slate-800'}`}
                  style={{
                    gridColumn: `${widget.position.x + 1} / span ${widget.size.w}`,
                    gridRow: `${widget.position.y + 1} / span ${widget.size.h}`,
                    position: 'relative',
                  }}
                >
                  <div className="p-3 h-full flex flex-col">
                    {!isPreviewMode && (
                      <div className="flex items-center justify-between mb-2">
                        <div className="flex items-center gap-2">
                          <GripVertical className="w-4 h-4 text-gray-500 cursor-move" />
                          <Icon className="w-4 h-4 text-gray-400" />
                          <span className="text-xs text-gray-400">{definition?.name}</span>
                        </div>
                        <div className="flex items-center gap-1">
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              duplicateWidget(widget);
                            }}
                            className="p-1 hover:bg-slate-700 rounded"
                          >
                            <Copy className="w-3 h-3 text-gray-500" />
                          </button>
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              removeWidget(widget.id);
                            }}
                            className="p-1 hover:bg-red-500/20 rounded"
                          >
                            <Trash2 className="w-3 h-3 text-red-400" />
                          </button>
                        </div>
                      </div>
                    )}
                    <div className="flex-1 flex items-center justify-center">
                      <WidgetPreview widget={widget} definition={definition} />
                    </div>
                  </div>
                </motion.div>
              );
            })}

            {/* Empty state */}
            {placedWidgets.length === 0 && !draggedWidget && (
              <div className="absolute inset-0 flex items-center justify-center">
                <div className="text-center">
                  <Layout className="w-16 h-16 text-slate-600 mx-auto mb-4" />
                  <h3 className="text-lg font-semibold text-gray-400 mb-2">Start Building</h3>
                  <p className="text-sm text-gray-500 max-w-xs">
                    Drag widgets from the left panel and drop them here to build your custom report
                  </p>
                </div>
              </div>
            )}
          </div>
        </main>

        {/* Config Panel - Right Sidebar */}
        {!isPreviewMode && selectedWidget && (
          <aside className="w-80 bg-slate-900/50 border-l border-slate-700 overflow-y-auto">
            <div className="p-4">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-sm font-semibold text-gray-400 uppercase tracking-wider">
                  Widget Settings
                </h3>
                <button
                  onClick={() => setSelectedWidget(null)}
                  className="p-1 hover:bg-slate-700 rounded"
                >
                  <X className="w-4 h-4 text-gray-400" />
                </button>
              </div>

              <WidgetConfigPanel
                widget={selectedWidget}
                definition={getWidgetDefinition(selectedWidget.widgetKey)}
                onConfigChange={(key, value) => updateWidgetConfig(selectedWidget.id, key, value)}
                onSizeChange={(size) => updateWidgetSize(selectedWidget.id, size)}
              />
            </div>
          </aside>
        )}
      </div>

      {/* Save Modal */}
      <AnimatePresence>
        {showSaveModal && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4"
            onClick={() => setShowSaveModal(false)}
          >
            <motion.div
              initial={{ scale: 0.95, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.95, opacity: 0 }}
              onClick={(e) => e.stopPropagation()}
              className="bg-slate-900 rounded-xl border border-slate-700 p-6 w-full max-w-md"
            >
              <h3 className="text-xl font-bold text-white mb-4">Save Report</h3>

              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-400 mb-1">Report Name</label>
                  <input
                    type="text"
                    value={reportName}
                    onChange={(e) => setReportName(e.target.value)}
                    className="w-full px-4 py-2 bg-slate-800 border border-slate-600 rounded-lg text-white focus:border-brand-deep focus:ring-1 focus:ring-brand-deep"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-400 mb-1">Description</label>
                  <textarea
                    value={reportDescription}
                    onChange={(e) => setReportDescription(e.target.value)}
                    rows={3}
                    className="w-full px-4 py-2 bg-slate-800 border border-slate-600 rounded-lg text-white focus:border-brand-deep focus:ring-1 focus:ring-brand-deep"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-400 mb-1">Module</label>
                  <select
                    value={reportModule}
                    onChange={(e) => setReportModule(e.target.value)}
                    className="w-full px-4 py-2 bg-slate-800 border border-slate-600 rounded-lg text-white focus:border-brand-deep focus:ring-1 focus:ring-brand-deep"
                  >
                    <option value="general">General</option>
                    <option value="finance">Finance</option>
                    <option value="hr">HR</option>
                    <option value="sales">Sales</option>
                    <option value="operations">Operations</option>
                    <option value="compliance">Compliance</option>
                    <option value="inventory">Inventory</option>
                    <option value="marketing">Marketing</option>
                  </select>
                </div>

                <div className="flex items-center gap-3">
                  <input
                    type="checkbox"
                    id="isPublic"
                    checked={isPublic}
                    onChange={(e) => setIsPublic(e.target.checked)}
                    className="rounded border-slate-600 bg-slate-800 text-brand-deep focus:ring-brand-deep"
                  />
                  <label htmlFor="isPublic" className="text-sm text-gray-300">
                    Make this report public (visible to all users)
                  </label>
                </div>
              </div>

              <div className="flex justify-end gap-3 mt-6">
                <button
                  onClick={() => setShowSaveModal(false)}
                  className="px-4 py-2 bg-slate-800 text-gray-300 rounded-lg hover:bg-slate-700 transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={saveReport}
                  disabled={isSaving || !reportName.trim()}
                  className="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-brand-deep to-brand-secondary text-white rounded-lg hover:opacity-90 transition-opacity disabled:opacity-50"
                >
                  {isSaving ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <Save className="w-4 h-4" />
                  )}
                  Save
                </button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

// Widget Preview Component
function WidgetPreview({
  widget,
  definition,
}: {
  widget: PlacedWidget;
  definition?: WidgetDefinition;
}) {
  const config = widget.config;

  switch (widget.widgetKey) {
    case 'kpi_card':
      return (
        <div className="text-center">
          <p className="text-xs text-gray-500">{String(config.title || 'Metric')}</p>
          <p className="text-2xl font-bold text-white mt-1">
            {String(config.prefix || '')}12,345{String(config.suffix || '')}
          </p>
          {Boolean(config.showTrend) && (
            <p className="text-xs text-green-400 mt-1">↑ 12.5%</p>
          )}
        </div>
      );

    case 'sparkline':
      return (
        <div className="w-full">
          <p className="text-xs text-gray-500 mb-2">{String(config.title || 'Trend')}</p>
          <svg className="w-full h-8" viewBox="0 0 100 30">
            <path
              d="M 0 20 L 10 18 L 20 22 L 30 15 L 40 17 L 50 12 L 60 14 L 70 8 L 80 10 L 90 5 L 100 7"
              fill="none"
              stroke="#0EA5E9"
              strokeWidth="2"
            />
          </svg>
        </div>
      );

    case 'gauge':
      return (
        <div className="text-center">
          <svg className="w-16 h-16" viewBox="0 0 36 36">
            <path
              d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
              fill="none"
              stroke="#1e293b"
              strokeWidth="3"
            />
            <path
              d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
              fill="none"
              stroke="#0EA5E9"
              strokeWidth="3"
              strokeDasharray="75, 100"
            />
          </svg>
          <p className="text-sm font-bold text-white mt-2">75%</p>
        </div>
      );

    case 'line_chart':
    case 'area_chart':
      return (
        <div className="w-full h-full flex items-end justify-center gap-1 p-2">
          {[40, 60, 45, 70, 55, 80, 65].map((h, i) => (
            <div
              key={i}
              className="w-full bg-gradient-to-t from-brand-deep to-brand-secondary rounded-t"
              style={{ height: `${h}%` }}
            />
          ))}
        </div>
      );

    case 'bar_chart':
      return (
        <div className="w-full h-full flex items-end justify-center gap-2 p-2">
          {[60, 80, 45, 90, 70].map((h, i) => (
            <div
              key={i}
              className="w-6 bg-brand-deep rounded-t"
              style={{ height: `${h}%` }}
            />
          ))}
        </div>
      );

    case 'pie_chart':
    case 'donut_chart':
      return (
        <svg className="w-16 h-16" viewBox="0 0 36 36">
          <circle cx="18" cy="18" r="15.9155" fill="#0EA5E9" />
          <path
            d="M18 2.0845 a 15.9155 15.9155 0 0 1 11.2672 27.0831 L18 18 Z"
            fill="#FDBA74"
          />
          <path
            d="M18 2.0845 a 15.9155 15.9155 0 0 0 -11.2672 27.0831 L18 18 Z"
            fill="#10b981"
          />
          {widget.widgetKey === 'donut_chart' && (
            <circle cx="18" cy="18" r="8" fill="#0C1222" />
          )}
        </svg>
      );

    case 'data_table':
    case 'summary_table':
      return (
        <div className="w-full text-xs">
          <div className="grid grid-cols-3 gap-1 text-gray-500 border-b border-slate-700 pb-1 mb-1">
            <span>Col 1</span>
            <span>Col 2</span>
            <span>Col 3</span>
          </div>
          <div className="grid grid-cols-3 gap-1 text-gray-300">
            <span>Data</span>
            <span>Data</span>
            <span>Data</span>
          </div>
        </div>
      );

    case 'text_block':
      return <p className="text-sm text-gray-300">{String(config.content || 'Text content')}</p>;

    case 'header':
      return (
        <div>
          <h4 className="font-bold text-white">{String(config.title || 'Section Title')}</h4>
          {Boolean(config.subtitle) && <p className="text-xs text-gray-500">{String(config.subtitle)}</p>}
        </div>
      );

    default:
      return (
        <div className="text-center text-gray-500">
          <Puzzle className="w-8 h-8 mx-auto" />
          <p className="text-xs mt-1">{definition?.name || 'Widget'}</p>
        </div>
      );
  }
}

// Widget Configuration Panel
function WidgetConfigPanel({
  widget,
  definition,
  onConfigChange,
  onSizeChange,
}: {
  widget: PlacedWidget;
  definition?: WidgetDefinition;
  onConfigChange: (key: string, value: unknown) => void;
  onSizeChange: (size: { w: number; h: number }) => void;
}) {
  if (!definition) return null;

  return (
    <div className="space-y-4">
      {/* Size Controls */}
      <div className="bg-slate-800/50 rounded-lg p-4">
        <h4 className="text-sm font-medium text-white mb-3">Size</h4>
        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className="text-xs text-gray-500 block mb-1">Width (cols)</label>
            <input
              type="number"
              value={widget.size.w}
              onChange={(e) => onSizeChange({ ...widget.size, w: parseInt(e.target.value) || 1 })}
              min={definition.minSize?.w || 1}
              max={12}
              className="w-full px-3 py-2 bg-slate-900 border border-slate-600 rounded text-white text-sm"
            />
          </div>
          <div>
            <label className="text-xs text-gray-500 block mb-1">Height (rows)</label>
            <input
              type="number"
              value={widget.size.h}
              onChange={(e) => onSizeChange({ ...widget.size, h: parseInt(e.target.value) || 1 })}
              min={definition.minSize?.h || 1}
              max={8}
              className="w-full px-3 py-2 bg-slate-900 border border-slate-600 rounded text-white text-sm"
            />
          </div>
        </div>
      </div>

      {/* Config Properties */}
      <div className="bg-slate-800/50 rounded-lg p-4">
        <h4 className="text-sm font-medium text-white mb-3">Configuration</h4>
        <div className="space-y-3">
          {definition.configSchema.map((prop) => (
            <div key={prop.key}>
              <label className="text-xs text-gray-500 block mb-1">{prop.label}</label>
              {prop.type === 'string' && (
                <input
                  type="text"
                  value={String(widget.config[prop.key] || '')}
                  onChange={(e) => onConfigChange(prop.key, e.target.value)}
                  className="w-full px-3 py-2 bg-slate-900 border border-slate-600 rounded text-white text-sm"
                />
              )}
              {prop.type === 'number' && (
                <input
                  type="number"
                  value={Number(widget.config[prop.key] || 0)}
                  onChange={(e) => onConfigChange(prop.key, parseFloat(e.target.value))}
                  className="w-full px-3 py-2 bg-slate-900 border border-slate-600 rounded text-white text-sm"
                />
              )}
              {prop.type === 'boolean' && (
                <div className="flex items-center">
                  <input
                    type="checkbox"
                    checked={Boolean(widget.config[prop.key])}
                    onChange={(e) => onConfigChange(prop.key, e.target.checked)}
                    className="rounded border-slate-600 bg-slate-900 text-brand-deep focus:ring-brand-deep"
                  />
                </div>
              )}
              {prop.type === 'select' && prop.options && (
                <select
                  value={String(widget.config[prop.key] || '')}
                  onChange={(e) => onConfigChange(prop.key, e.target.value)}
                  className="w-full px-3 py-2 bg-slate-900 border border-slate-600 rounded text-white text-sm"
                >
                  {prop.options.map((opt) => (
                    <option key={opt.value} value={opt.value}>
                      {opt.label}
                    </option>
                  ))}
                </select>
              )}
              {prop.type === 'color' && (
                <input
                  type="color"
                  value={String(widget.config[prop.key] || '#0EA5E9')}
                  onChange={(e) => onConfigChange(prop.key, e.target.value)}
                  className="w-full h-10 rounded border border-slate-600 bg-slate-900"
                />
              )}
            </div>
          ))}
        </div>
      </div>

      {/* Data Source */}
      <div className="bg-slate-800/50 rounded-lg p-4">
        <h4 className="text-sm font-medium text-white mb-3">Data Source</h4>
        <select
          value={widget.dataSource || ''}
          onChange={(e) => onConfigChange('dataSource', e.target.value)}
          className="w-full px-3 py-2 bg-slate-900 border border-slate-600 rounded text-white text-sm"
        >
          <option value="">Select data source...</option>
          <option value="ar_aging">AR Aging Report</option>
          <option value="ap_aging">AP Aging Report</option>
          <option value="cash_flow">Cash Flow Statement</option>
          <option value="revenue">Revenue by Customer</option>
          <option value="sales_pipeline">Sales Pipeline</option>
          <option value="employee_directory">Employee Directory</option>
          <option value="agent_performance">Agent Performance</option>
          <option value="system_health">System Health</option>
        </select>
        <p className="text-xs text-gray-500 mt-2">
          Connect this widget to a data source for live data
        </p>
      </div>
    </div>
  );
}
