import { CopyOutlined, EyeInvisibleOutlined, EyeOutlined } from '@ant-design/icons';
import { Button } from '@lobehub/ui';
import { App, Flex } from 'antd';
import { type FC } from 'react';
import { 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 />}
          size="small"
          title={isVisible ? t('apikey.display.hide') : t('apikey.display.show')}
          type="text"
          onClick={toggleVisibility}
        />
        <Button
          icon={<CopyOutlined />}
          size="small"
          title={t('apikey.display.copy')}
          type="text"
          onClick={handleCopy}
        />
      </Flex>
    </Flex>
  );
};

export default ApiKeyDisplay;
