'use client';

import { Bookmark, Check, Trash2 } from 'lucide-react';

import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useSavedViews } from '@/hooks/use-saved-views';

interface SavedViewsDropdownProps {
  entityType: string;
  onApplyView: (
    filters: Record<string, unknown>,
    sort?: { field: string; direction: string },
  ) => void;
}

/**
 * Read-only browser for saved views. The "Save current view" affordance
 * has moved into the ColumnPicker menu (see SaveViewDialog). This
 * component renders nothing when the user has no saved views - the
 * Bookmark button on its own is just visual noise until something has
 * been saved.
 */
export function SavedViewsDropdown({ entityType, onApplyView }: SavedViewsDropdownProps) {
  const { views, activeViewId, deleteView, applyView } = useSavedViews(entityType);

  if (views.length === 0) return null;

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="outline" size="sm" className="h-8">
          <Bookmark className="mr-1.5 h-3.5 w-3.5" aria-hidden />
          Views
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-56">
        {views.map((view) => (
          <DropdownMenuItem
            key={view.id}
            className="flex items-center justify-between"
            onClick={() => {
              applyView(view.id);
              onApplyView(
                view.filters as Record<string, unknown>,
                view.sortConfig as { field: string; direction: string } | undefined,
              );
            }}
          >
            <span className="truncate">{view.name}</span>
            <div className="flex items-center gap-1">
              {activeViewId === view.id && (
                <Check className="h-3.5 w-3.5 text-primary" aria-hidden />
              )}
              <button
                className="p-0.5 rounded hover:bg-muted"
                onClick={(e) => {
                  e.stopPropagation();
                  deleteView(view.id);
                }}
              >
                <Trash2 className="h-3 w-3 text-muted-foreground" aria-hidden />
              </button>
            </div>
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
