'use client';

import { useCallback, useRef, useState } from 'react';
import {
  DropdownMenu,
  DropdownMenuItem,
} from '@/internal/components/DropdownMenu';
import { cn } from '@/styles/theme';
import type { TokenSelectDropdownProps } from '../types';
import { TokenRow } from './TokenRow';
import { TokenSelectButton } from './TokenSelectButton';

export function TokenSelectDropdown({
  options,
  setToken,
  token,
}: TokenSelectDropdownProps) {
  const [isOpen, setIsOpen] = useState(false);
  const buttonRef = useRef<HTMLButtonElement | null>(null);

  const closeDropdown = useCallback(() => {
    setIsOpen(false);
  }, []);

  const toggleDropdown = useCallback(() => {
    setIsOpen((prev) => !prev);
  }, []);

  return (
    <div className="relative max-w-fit shrink-0">
      <DropdownMenu
        trigger={
          <TokenSelectButton
            ref={buttonRef}
            onClick={toggleDropdown}
            isOpen={isOpen}
            token={token}
          />
        }
        isOpen={isOpen}
        onClose={closeDropdown}
        align="end"
        aria-label="Select token"
        className="rounded-ock-default text-ock-foreground flex max-h-80 w-[200px] flex-col overflow-y-hidden ock-scrollbar overflow-y-auto"
      >
        {options.map((token) => (
          <TokenRow
            as={DropdownMenuItem}
            key={token.name + token.address}
            className={cn('bg-ock-background-inverse', 'px-4 py-2')}
            token={token}
            onClick={() => {
              setToken(token);
              setIsOpen(false);
            }}
          />
        ))}
      </DropdownMenu>
    </div>
  );
}
