/*
Copyright (C) 2025 QuantumNous

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

For commercial licensing, please contact support@quantumnous.com
*/

import React, { useState, useEffect, useMemo } from 'react';
import { Card, Avatar, Typography, Table, Tag, Spin, Banner, Tooltip } from '@douyinfe/semi-ui';
import { IconServer, IconCopy } from '@douyinfe/semi-icons';
import { API, copy, showSuccess } from '../../../../../helpers';

const { Text } = Typography;

const ChannelPricingCard = ({
  modelName,
  currency,
  tokenUnit,
  displayPrice,
  t,
}) => {
  const [loading, setLoading] = useState(false);
  const [channelPricingData, setChannelPricingData] = useState([]);

  useEffect(() => {
    const fetchChannelPricing = async () => {
      if (!modelName) return;

      setLoading(true);
      try {
        const res = await API.get(`/api/channel-pricing/model/${encodeURIComponent(modelName)}`);
        const { success, data } = res.data;
        if (success && Array.isArray(data)) {
          setChannelPricingData(data);
        } else {
          setChannelPricingData([]);
        }
      } catch (error) {
        // 静默处理错误，不显示给用户
        setChannelPricingData([]);
      } finally {
        setLoading(false);
      }
    };

    fetchChannelPricing();
  }, [modelName]);

  // 获取货币符号
  const currencySymbol = useMemo(() => {
    if (currency === 'CNY') return '¥';
    if (currency === 'CUSTOM') {
      try {
        const statusStr = localStorage.getItem('status');
        if (statusStr) {
          const s = JSON.parse(statusStr);
          return s?.custom_currency_symbol || '¤';
        }
      } catch (e) {
        // ignore
      }
      return '¤';
    }
    return '$';
  }, [currency]);

  // 格式化价格显示
  const formatPrice = (price) => {
    if (price === 0) return '-';
    const displayVal = displayPrice(price);
    const unitDivisor = tokenUnit === 'K' ? 1000 : 1;
    const numPrice = parseFloat(displayVal.replace(/[^0-9.]/g, '')) / unitDivisor;
    return `${currencySymbol}${numPrice.toFixed(4)}`;
  };

  // 空状态或加载中
  if (loading) {
    return (
      <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
        <div className='flex justify-center items-center py-8'>
          <Spin size='large' />
        </div>
      </Card>
    );
  }

  if (channelPricingData.length === 0) {
    return null; // 无渠道时不显示
  }

  // 准备表格数据
  const tableData = channelPricingData.map((item, index) => ({
    key: item.channel_id || index,
    channelId: item.channel_id,
    channelName: item.channel_public_name || ('通道' + (index + 1)),
    channelTags: item.tags || [], // 渠道定价的标签列表
    channelType: item.channel_type,
    quotaType: item.quota_type,
    modelRatio: item.model_ratio,
    completionRatio: item.completion_ratio,
    modelPrice: item.model_price,
    hasCustomPricing: item.has_custom_pricing,
    cacheRatio: item.cache_ratio,
    cacheCreationRatio: item.cache_creation_ratio,
    isDefault: item.is_default || false,
  }));

  // 判断是否存在按次计费的渠道
  const hasCallBased = tableData.some((item) => item.quotaType === 1);
  // 判断是否存在按量计费的渠道
  const hasTokenBased = tableData.some((item) => item.quotaType === 0);

  // 定义基础列
  const baseColumns = [
    {
      title: t('通道'),
      dataIndex: 'channelName',
      render: (text, record) => (
        <div className='flex items-center gap-2 flex-wrap'>
          <Tooltip content={t('点击复制通道 ID')}>
            <Tag
              color='grey'
              size='small'
              shape='circle'
              style={{ cursor: 'pointer' }}
              onClick={async () => {
                const ok = await copy(String(record.channelId));
                if (ok) showSuccess(t('已复制到剪切板'));
              }}
            >
              ID: {record.channelId} <IconCopy size='tiny' style={{ marginLeft: 2, verticalAlign: 'middle' }} />
            </Tag>
          </Tooltip>
          <Tag color='cyan' size='small' shape='circle'>
            {text}
          </Tag>
          {record.channelTags.map((tag, idx) => (
            <Tag
              key={idx}
              color={tag.color || 'default'}
              size='small'
              shape='circle'
              style={{ backgroundColor: tag.color, color: '#fff' }}
            >
              {tag.name}
            </Tag>
          ))}
          {record.isDefault && (
            <Tag color='amber' size='small' shape='circle'>
              {t('默认')}
            </Tag>
          )}
        </div>
      ),
    },
    {
      title: t('计费类型'),
      dataIndex: 'quotaType',
      render: (quotaType) => {
        const text = quotaType === 0 ? t('按量计费') : t('按次计费');
        const color = quotaType === 0 ? 'violet' : 'teal';
        return (
          <Tag color={color} size='small' shape='circle'>
            {text}
          </Tag>
        );
      },
    },
  ];

  // 只有存在按量计费的渠道时才显示输入/输出价格列
  const tokenBasedColumns = hasTokenBased
    ? [
        {
          title: t('输入价格'),
          dataIndex: 'modelRatio',
          render: (ratio, record) => {
            if (record.quotaType !== 0) return '-';
            // 输入价格 = model_ratio * 2 (渠道定价不乘分组倍率)
            const inputPrice = ratio * 2;
            return (
              <>
                <div className='font-semibold text-orange-600'>
                  {formatPrice(inputPrice)}
                </div>
                <div className='text-xs text-gray-500'>
                  / {tokenUnit === 'K' ? '1K' : '1M'} tokens
                </div>
              </>
            );
          },
        },
        {
          title: t('输出价格'),
          dataIndex: 'completionRatio',
          render: (completionRatio, record) => {
            if (record.quotaType !== 0) return '-';
            // 输出价格 = model_ratio * completion_ratio * 2
            const outputPrice = record.modelRatio * completionRatio * 2;
            return (
              <>
                <div className='font-semibold text-orange-600'>
                  {formatPrice(outputPrice)}
                </div>
                <div className='text-xs text-gray-500'>
                  / {tokenUnit === 'K' ? '1K' : '1M'} tokens
                </div>
              </>
            );
          },
        },
      ]
    : [];

  // 判断是否存在高级比例数据
  const hasAdvancedPricing = tableData.some(
    (item) => item.cacheRatio > 0 || item.cacheCreationRatio > 0
  );

  const renderCachePrice = (v, record) => {
    if (record.quotaType !== 0) return '-';
    return (
      <>
        <div className='font-semibold text-orange-600'>
          {formatPrice(record.modelRatio * v * 2)}
        </div>
        <div className='text-xs text-gray-500'>
          / {tokenUnit === 'K' ? '1K' : '1M'} tokens
        </div>
      </>
    );
  };

  const advancedColumns = hasAdvancedPricing
    ? [
        {
          title: t('缓存读取'),
          dataIndex: 'cacheRatio',
          render: renderCachePrice,
        },
        {
          title: t('缓存创建'),
          dataIndex: 'cacheCreationRatio',
          render: renderCachePrice,
        },
      ]
    : [];

  // 只有存在按次计费的渠道时才显示固定价格列
  const callBasedColumn = hasCallBased
    ? [
        {
          title: t('固定价格'),
          dataIndex: 'modelPrice',
          render: (price, record) => {
            if (record.quotaType !== 1) return '-';
            return (
              <>
                <div className='font-semibold text-orange-600'>
                  {displayPrice(price)}
                </div>
                <div className='text-xs text-gray-500'>/ {t('次')}</div>
              </>
            );
          },
        },
      ]
    : [];

  const columns = [...baseColumns, ...tokenBasedColumns, ...advancedColumns, ...callBasedColumn];

  return (
    <Card className='!rounded-2xl shadow-sm border-0 mb-6'>
      <div className='flex items-center mb-4'>
        <Avatar size='small' color='cyan' className='mr-2 shadow-md'>
          <IconServer size={16} />
        </Avatar>
        <div>
          <Text className='text-lg font-medium'>{t('通道价格')}</Text>
          <div className='text-xs text-gray-600'>
            {t('所有支持该模型的通道价格（自定义定价已标记）')}
          </div>
        </div>
      </div>
      <Banner
        type='info'
        description={t('在 API Key 后添加 ":通道ID" 可指定使用特定通道，如：sk-xxxx:1')}
        className='mb-4'
      />
      <Table
        dataSource={tableData}
        columns={columns}
        pagination={false}
        size='small'
        bordered={false}
        className='!rounded-lg'
      />
    </Card>
  );
};

export default ChannelPricingCard;
