import React, { type JSX } from 'react';

import type { CodeBlockItems } from '@redocly/theme/components/CodeBlock/CodeBlock';

import { Dropdown } from '@redocly/theme/components/Dropdown/Dropdown';
import { DropdownMenu } from '@redocly/theme/components/Dropdown/DropdownMenu';
import { DropdownMenuItem } from '@redocly/theme/components/Dropdown/DropdownMenuItem';
import { Button } from '@redocly/theme/components/Button/Button';
import { NoneIcon } from '@redocly/theme/icons/NoneIcon/NoneIcon';
import { getFileIconByLanguage } from '@redocly/theme/core/utils';

export function CodeBlockDropdown({ items, onChange, value }: CodeBlockItems): JSX.Element {
  const activeItem = items.find((item) => item.id === value) || items[0];
  const icon = activeItem?.lang ? getFileIconByLanguage(activeItem?.lang) : null;
  return (
    <Dropdown
      withArrow
      alignment="end"
      trigger={
        <Button iconPosition="right" variant="ghost" size="small">
          {icon}
          {activeItem.name}
        </Button>
      }
    >
      <DropdownMenu>
        {items.map((item) => {
          const icon = getFileIconByLanguage(item.lang || '');
          const isActive = item.id === value;
          return (
            <DropdownMenuItem
              key={item.id}
              onAction={() => onChange(item.id)}
              active={isActive}
              prefix={item.lang ? icon : <NoneIcon size="var(--icon-size)" />}
            >
              {item.name}
            </DropdownMenuItem>
          );
        })}
      </DropdownMenu>
    </Dropdown>
  );
}
