/**
 * ColumnVisibilityMenu
 * 
 * Dropdown menu to show/hide table columns.
 * Integrates with TanStack Table column visibility state.
 * 
 * Features:
 * - Checkbox list of all columns
 * - Hide/show individual columns
 * - "Reset to default" button
 * - Persisted via localStorage
 */

'use client';

import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Columns3 } from 'lucide-react';
import type { Table } from '@tanstack/react-table';
import type { PolicySettingRow } from '@/lib/types/policy-table';

interface ColumnVisibilityMenuProps {
  table: Table<PolicySettingRow>;
}

export function ColumnVisibilityMenu({ table }: ColumnVisibilityMenuProps) {
  const columns = table
    .getAllColumns()
    .filter((column) => column.getCanHide());

  const hiddenCount = columns.filter((column) => !column.getIsVisible()).length;

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="outline" size="sm" className="ml-auto h-8 lg:flex">
          <Columns3 className="mr-2 h-4 w-4" />
          Columns
          {hiddenCount > 0 && (
            <span className="ml-1 rounded-full bg-primary px-2 py-0.5 text-xs text-primary-foreground">
              {hiddenCount}
            </span>
          )}
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-[180px]">
        <DropdownMenuLabel>Toggle columns</DropdownMenuLabel>
        <DropdownMenuSeparator />
        {columns.map((column) => {
          return (
            <DropdownMenuCheckboxItem
              key={column.id}
              className="capitalize"
              checked={column.getIsVisible()}
              onCheckedChange={(value) => column.toggleVisibility(!!value)}
            >
              {/* Format column ID to human-readable label */}
              {column.id.replace(/([A-Z])/g, ' $1').trim()}
            </DropdownMenuCheckboxItem>
          );
        })}
        <DropdownMenuSeparator />
        <Button
          variant="ghost"
          size="sm"
          className="w-full justify-start"
          onClick={() => table.resetColumnVisibility()}
        >
          Reset to default
        </Button>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
