/*
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 } from 'react';
import {
  Banner,
  Button,
  Modal,
  Radio,
  RadioGroup,
  Upload,
} from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import ModelPricingEditor from './components/ModelPricingEditor';
import ModelRatioSettings from './ModelRatioSettings';
import { API, showError, showSuccess } from '../../../helpers';

export default function ModelPricingCombined({ options, refresh }) {
  const { t } = useTranslation();
  const [editMode, setEditMode] = useState('visual');
  const [importVisible, setImportVisible] = useState(false);
  const [importing, setImporting] = useState(false);
  const [importFile, setImportFile] = useState(null);
  const [importFileList, setImportFileList] = useState([]);

  const resetImportState = () => {
    setImportFile(null);
    setImportFileList([]);
  };

  const handleImportFileChange = ({ fileList }) => {
    const selectedFileList = fileList.slice(-1);
    setImportFileList(selectedFileList);
    setImportFile(selectedFileList[0]?.fileInstance || null);
  };

  const handleImport = async () => {
    if (!importFile) {
      showError(t('请选择要导入的 Excel 文件'));
      return;
    }

    setImporting(true);
    try {
      const formData = new FormData();
      formData.append('file', importFile);
      const res = await API.post('/api/option/import_model_pricing', formData);
      const { success, message, data } = res.data || {};
      if (!success) {
        showError(message || t('模型定价导入失败'));
        return;
      }

      showSuccess(
        t(
          '模型定价导入完成：更新 {{updated}} 个，按量 {{perToken}} 个，按次 {{perRequest}} 个，失败 {{failed}} 个',
          {
            updated: data?.updated || 0,
            perToken: data?.per_token || 0,
            perRequest: data?.per_request || 0,
            failed: data?.failed || 0,
          },
        ),
      );
      await refresh();
      setImportVisible(false);
      resetImportState();
    } catch (error) {
      showError(error.response?.data?.message || t('模型定价导入失败'));
    } finally {
      setImporting(false);
    }
  };

  return (
    <div>
      <div
        className='flex flex-col md:flex-row md:items-center md:justify-between gap-2'
        style={{ marginTop: 12, marginBottom: 16 }}
      >
        <RadioGroup
          type='button'
          size='small'
          value={editMode}
          onChange={(e) => setEditMode(e.target.value)}
        >
          <Radio value='visual'>{t('可视化编辑')}</Radio>
          <Radio value='manual'>{t('手动编辑')}</Radio>
        </RadioGroup>
        <Button
          size='small'
          type='secondary'
          onClick={() => setImportVisible(true)}
        >
          {t('Excel 导入')}
        </Button>
      </div>
      {editMode === 'visual' ? (
        <ModelPricingEditor options={options} refresh={refresh} />
      ) : (
        <ModelRatioSettings options={options} refresh={refresh} />
      )}
      <Modal
        title={t('导入模型定价')}
        visible={importVisible}
        onCancel={() => {
          if (importing) return;
          setImportVisible(false);
          resetImportState();
        }}
        onOk={handleImport}
        okText={t('导入')}
        cancelText={t('取消')}
        confirmLoading={importing}
        okButtonProps={{ disabled: !importFile }}
      >
        <div className='space-y-3'>
          <Banner
            type='info'
            description={t(
              '第一行必须是表头，model_name 为必填列。按次计费填写 fixed_price；如果 fixed_price 为空，则使用 input_price 按量计费，可选 completion_price。',
            )}
          />
          <Banner
            type='warning'
            description={t(
              '导入会覆盖 Excel 中对应模型的定价方式：按量计费会清除该模型按次价格，按次计费会清除该模型倍率配置。',
            )}
          />
          <Upload
            action=''
            accept='.xlsx,.xls'
            disabled={importing}
            fileList={importFileList}
            limit={1}
            uploadTrigger='custom'
            draggable={true}
            dragMainText={t('点击上传文件或拖拽文件到这里')}
            dragSubText={t('仅支持 xls、xlsx')}
            beforeUpload={() => false}
            onChange={handleImportFileChange}
            onRemove={() => {
              setImportFile(null);
              setImportFileList([]);
            }}
          ></Upload>
          {importFile ? (
            <div className='text-sm text-[var(--semi-color-text-2)]'>
              {t('已选择文件：{{name}}', { name: importFile.name })}
            </div>
          ) : null}
        </div>
      </Modal>
    </div>
  );
}
