"use client";

import { LayoutGrid, Plus } from "lucide-react";
import type { WidgetItem } from "@/types/dashboard";
import { ModalShell } from "@/components/ui/ModalShell";
import { Button } from "@/components/ui/button";

export interface AddWidgetModalProps {
  available: WidgetItem[];
  onSelect: (widget: WidgetItem) => void;
  onClose: () => void;
}

/**
 * Widget picker for the dashboard grid.
 *
 * Rebuilt on `ModalShell`. Besides the dialog accessibility, this collapses two
 * near-duplicate branches — the previous version rendered a completely separate
 * overlay when nothing was available — into one dialog with a proper empty
 * state, so the two paths can no longer drift apart.
 */
export function AddWidgetModal({ available, onSelect, onClose }: AddWidgetModalProps) {
  const isEmpty = available.length === 0;

  return (
    <ModalShell
      isOpen
      onClose={onClose}
      size="sm"
      icon={<LayoutGrid />}
      eyebrow="Dashboard"
      title="Add widget"
      description={
        isEmpty
          ? undefined
          : "Choose a widget to add to your dashboard. You can reorder it afterwards."
      }
      footer={
        <Button variant="outline" onClick={onClose} className="w-full sm:w-auto">
          {isEmpty ? "Close" : "Cancel"}
        </Button>
      }
    >
      {isEmpty ? (
        <div className="flex flex-col items-center gap-1.5 py-6 text-center">
          <span className="mb-1 flex size-11 items-center justify-center rounded-full bg-muted text-muted-foreground">
            <LayoutGrid className="size-5" aria-hidden />
          </span>
          <p className="text-sm font-semibold text-foreground">Nothing left to add</p>
          <p className="max-w-xs text-xs leading-relaxed text-muted-foreground">
            Every available asset allocation widget is already on your dashboard.
          </p>
        </div>
      ) : (
        <ul className="space-y-2">
          {available.map((widget) => (
            <li key={widget.widget_id}>
              <button
                type="button"
                onClick={() => onSelect(widget)}
                className="group flex w-full items-center justify-between gap-3 rounded-md border border-border bg-card px-4 py-3 text-left text-sm font-medium text-foreground transition-colors hover:border-primary/40 hover:bg-accent"
              >
                <span className="min-w-0 truncate">
                  {widget.name || "Asset Allocation"}
                </span>
                <Plus
                  className="size-4 shrink-0 text-muted-foreground transition-colors group-hover:text-primary"
                  aria-hidden
                />
              </button>
            </li>
          ))}
        </ul>
      )}
    </ModalShell>
  );
}
