"use client";

/**
 * Wraps each widget section. In normal mode, renders children with
 * the appropriate column span. In edit mode, adds a drag handle,
 * visibility toggle, and size selector.
 */

import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { GripVertical, Eye, EyeOff, Columns2, Columns3 } from "lucide-react";
import type { WidgetSize } from "@/lib/layouts/widget-registry";

interface Props {
  id: string;
  name: string;
  visible: boolean;
  size: WidgetSize;
  editing: boolean;
  onToggleVisible: () => void;
  onChangeSize: (size: WidgetSize) => void;
  children: React.ReactNode;
}

const SIZE_CLASSES: Record<WidgetSize, string> = {
  full: "col-span-full",
  half: "col-span-1",
  third: "col-span-1",
};

export default function WidgetWrapper({ id, name, visible, size, editing, onToggleVisible, onChangeSize, children }: Props) {
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id, disabled: !editing });
  const style: React.CSSProperties = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  };

  if (!visible && !editing) return null;

  return (
    <div ref={setNodeRef} style={style} className={`${SIZE_CLASSES[size]} ${!visible ? "opacity-40" : ""}`}>
      {editing && (
        <div className="flex items-center gap-2 mb-1.5 px-1">
          <button {...attributes} {...listeners} className="touch-none cursor-grab active:cursor-grabbing text-slate-300 hover:text-slate-500">
            <GripVertical className="w-3.5 h-3.5" />
          </button>
          <span className="text-[10px] font-bold uppercase tracking-widest text-slate-400 flex-1 truncate">{name}</span>
          <button onClick={onToggleVisible} className={`w-6 h-6 rounded-md flex items-center justify-center ${visible ? "text-brand-600 bg-brand-50" : "text-slate-400 bg-slate-100"}`}>
            {visible ? <Eye className="w-3 h-3" /> : <EyeOff className="w-3 h-3" />}
          </button>
          <div className="flex bg-slate-100 rounded-md p-0.5 gap-0.5">
            {(["full", "half", "third"] as const).map((s) => (
              <button key={s} onClick={() => onChangeSize(s)} className={`px-1.5 py-0.5 rounded text-[9px] font-bold uppercase ${size === s ? "bg-white text-slate-900 shadow-sm" : "text-slate-400"}`}>
                {s === "full" ? "Full" : s === "half" ? "½" : "⅓"}
              </button>
            ))}
          </div>
        </div>
      )}
      <div className={editing ? "border-2 border-dashed rounded-xl overflow-hidden " + (visible ? "border-brand-200" : "border-slate-200") : ""}>
        {visible ? children : (
          <div className="bg-slate-50 rounded-xl px-4 py-8 text-center">
            <EyeOff className="w-5 h-5 text-slate-300 mx-auto mb-1" />
            <p className="text-[11px] font-semibold text-slate-400">Hidden</p>
          </div>
        )}
      </div>
    </div>
  );
}
