/**
 * DashboardGrid — grid layout with drag-and-drop widget positioning (Task 5.25).
 * Uses native HTML5 drag-and-drop with CSS Grid — no heavy DnD library.
 */

import React, { useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { DashboardWidgetLoader } from './DashboardWidgetLoader';
import type { DashboardWidgetDef } from '@/api/dashboard';

interface DashboardGridProps {
  widgets: DashboardWidgetDef[];
}

export function DashboardGrid({ widgets: initialWidgets }: DashboardGridProps) {
  const { t } = useTranslation();
  const [widgets, setWidgets] = useState(initialWidgets);
  const [dragIndex, setDragIndex] = useState<number | null>(null);
  const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);

  const handleDragStart = useCallback((index: number) => {
    setDragIndex(index);
  }, []);

  const handleDragOver = useCallback((e: React.DragEvent, index: number) => {
    e.preventDefault();
    setDragOverIndex(index);
  }, []);

  const handleDrop = useCallback((index: number) => {
    if (dragIndex === null || dragIndex === index) {
      setDragIndex(null);
      setDragOverIndex(null);
      return;
    }
    setWidgets((prev) => {
      const next = [...prev];
      const [moved] = next.splice(dragIndex, 1);
      next.splice(index, 0, moved);
      return next;
    });
    setDragIndex(null);
    setDragOverIndex(null);
  }, [dragIndex]);

  const handleDragEnd = useCallback(() => {
    setDragIndex(null);
    setDragOverIndex(null);
  }, []);

  if (widgets.length === 0) {
    return (
      <p className="text-sm text-secondary-500" data-testid="dashboard-grid-empty">
        {t('dashboard.noWidgets')}
      </p>
    );
  }

  return (
    <div
      className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4"
      data-testid="dashboard-grid"
    >
      {widgets.map((widget, index) => {
        const colSpan = Math.min(widget.col_span || 1, 4);
        const colSpanClass = {
          1: 'lg:col-span-1',
          2: 'lg:col-span-2',
          3: 'lg:col-span-3',
          4: 'lg:col-span-4',
        }[colSpan] || 'lg:col-span-1';

        return (
          <div
            key={`${widget.plugin_name}-${widget.id}`}
            className={`${colSpanClass} ${
              dragIndex === index ? 'opacity-50' : ''
            } ${
              dragOverIndex === index ? 'ring-2 ring-primary-400 rounded-lg' : ''
            }`}
            draggable
            onDragStart={() => handleDragStart(index)}
            onDragOver={(e) => handleDragOver(e, index)}
            onDrop={() => handleDrop(index)}
            onDragEnd={handleDragEnd}
            data-testid={`dashboard-grid-item-${widget.id}`}
          >
            <div className="bg-white rounded-lg shadow-sm border border-secondary-200 p-4 h-full">
              <div className="flex items-center justify-between mb-3">
                <h3 className="text-sm font-medium text-secondary-700">
                  {widget.label || t(widget.label_key)}
                </h3>
                <span className="text-xs text-secondary-400 cursor-move" title={t('dashboard.dragToReorder')}>⋮⋮</span>
              </div>
              <DashboardWidgetLoader widget={widget} />
            </div>
          </div>
        );
      })}
    </div>
  );
}
