import { CopyOutlined, EyeInvisibleOutlined, EyeOutlined } from '@ant-design/icons';
import { Button } from '@lobehub/ui';
import { App, Flex } from 'antd';
import { FC, useState } from 'react';
import { useTranslation } from 'react-i18next';

interface ApiKeyDisplayProps {
  apiKey?: string;
}

const ApiKeyDisplay: FC<ApiKeyDisplayProps> = ({ apiKey }) => {
  const { t } = useTranslation('auth');
  const [isVisible, setIsVisible] = useState(false);
  const { message } = App.useApp();

  const toggleVisibility = () => {
    setIsVisible(!isVisible);
  };

  const handleCopy = async () => {
    if (!apiKey) return;

    try {
      await navigator.clipboard.writeText(apiKey);
      message.success(t('apikey.display.copySuccess'));
    } catch {
      message.error(t('apikey.display.copyError'));
    }
  };

  const displayValue = apiKey && (isVisible ? apiKey : `lb-${'*'.repeat(apiKey.length - 2)}`);

  if (!apiKey) {
    return t('apikey.display.autoGenerated');
  }

  return (
    <Flex align="center" gap={8}>
      <span style={{ fontSize: '14px' }}>{displayValue}</span>
      <Flex>
        <Button
          icon={isVisible ? <EyeInvisibleOutlined /> : <EyeOutlined />}
          onClick={toggleVisibility}
          size="small"
          title={isVisible ? t('apikey.display.hide') : t('apikey.display.show')}
          type="text"
        />
        <Button
          icon={<CopyOutlined />}
          onClick={handleCopy}
          size="small"
          title={t('apikey.display.copy')}
          type="text"
        />
      </Flex>
    </Flex>
  );
};

export default ApiKeyDisplay;
