'use client';

import Link from 'next/link';
import { ChevronDown } from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger
} from '@/components/ui/dropdown-menu';
import { cn } from '@/lib/utils';

type FamilyGroupOption = {
  id: string;
  name: string;
};

export function FamilyGroupSelector({
  groups,
  selectedGroupId,
  onSelect,
  href,
  className,
  nameClassName
}: {
  groups: FamilyGroupOption[];
  selectedGroupId: string | null;
  onSelect: (groupId: string) => void;
  href?: string;
  className?: string;
  nameClassName?: string;
}) {
  const selected = groups.find((group) => group.id === selectedGroupId) ?? groups[0];

  if (!selected) return null;

  const nameElement = href ? (
    <Link href={href} className={cn('truncate hover:underline', nameClassName)} onClick={(event) => event.stopPropagation()}>
      {selected.name}
    </Link>
  ) : (
    <span className={cn('truncate', nameClassName)}>{selected.name}</span>
  );

  if (groups.length <= 1) {
    return <div className={cn('min-w-0', className)}>{nameElement}</div>;
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <button
          type="button"
          className={cn(
            'flex min-w-0 max-w-full items-center gap-0.5 rounded-lg text-left transition hover:bg-[#f4f5f8]',
            className
          )}
        >
          {nameElement}
          <ChevronDown className="h-3 w-3 shrink-0 text-[#667085]" aria-hidden />
        </button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="start" className="max-w-[220px] rounded-xl">
        {groups.map((group) => (
          <DropdownMenuItem
            key={group.id}
            className={cn('truncate rounded-lg', group.id === selected.id && 'font-medium text-[#3390ec]')}
            onClick={() => onSelect(group.id)}
          >
            {group.name}
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
