/*
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, { useEffect, useState, useRef } from 'react';
import { Button, Col, Form, Row, Spin, Typography, TagInput } from '@douyinfe/semi-ui';
import {
  compareObjects,
  API,
  showError,
  showSuccess,
  showWarning,
  toBoolean,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';

// 将字符串转换为数组（用于 TagInput 显示）
function stringToArray(str) {
  if (!str || typeof str !== 'string') return [];
  const trimmed = str.trim();
  // 尝试 JSON 解析（后端存的是 JSON 数组格式）
  if (trimmed.startsWith('[')) {
    try {
      const arr = JSON.parse(trimmed);
      if (Array.isArray(arr)) {
        return arr.map((s) => s.trim()).filter((s) => s.length > 0);
      }
    } catch (e) {
      // JSON 解析失败，fallback 到换行分隔
    }
  }
  // 换行分隔格式兼容
  return str
    .split('\n')
    .map((s) => s.trim())
    .filter((s) => s.length > 0);
}

// 将数组转换为 JSON 字符串（用于保存）
function arrayToString(arr) {
  if (!arr || !Array.isArray(arr)) return '[]';
  const filtered = arr
    .map((s) => s.trim())
    .filter((s) => s.length > 0);
  return JSON.stringify(filtered);
}

// 字段类型定义，用于从 props.options 加载时正确转换类型
const FIELD_TYPES = {
  'region_sync.enabled': 'boolean',
  'region_sync.region_id': 'string',
  'region_sync.is_master': 'boolean',
  'region_sync.master_endpoint': 'string',
  'region_sync.slave_endpoints': 'string',
  'region_sync.sync_api_key': 'string',
  'region_sync.min_balance_threshold': 'number',
  'region_sync.sync_interval_seconds': 'number',
  'region_sync.max_retry_count': 'number',
  'region_sync.sync_batch_size': 'number',
  'region_sync.quota_sync_interval_seconds': 'number',
  'region_sync.disable_cached_consume': 'boolean',
};

// 默认值常量，确保所有字段始终存在（即使 API 不返回某些敏感字段）
const DEFAULT_INPUTS = {
  'region_sync.enabled': false,
  'region_sync.region_id': '',
  'region_sync.is_master': false,
  'region_sync.master_endpoint': '',
  'region_sync.slave_endpoints': '',
  'region_sync.sync_api_key': '',
  'region_sync.min_balance_threshold': 100000,
  'region_sync.sync_interval_seconds': 60,
  'region_sync.max_retry_count': 3,
  'region_sync.sync_batch_size': 100,
  'region_sync.quota_sync_interval_seconds': 300,
  'region_sync.disable_cached_consume': false,
};

export default function SettingsRegionSync(props) {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  // 原始数据（字符串格式，用于保存）
  const [inputs, setInputs] = useState({ ...DEFAULT_INPUTS });
  // TagInput 显示用的数组格式
  const [slaveEndpoints, setSlaveEndpoints] = useState([]);

  const refForm = useRef();
  const [inputsRow, setInputsRow] = useState({ ...DEFAULT_INPUTS });

  function handleFieldChange(fieldName) {
    return (value) => {
      setInputs((inputs) => ({ ...inputs, [fieldName]: value }));
    };
  }

  // 处理 TagInput 变化
  function handleTagInputChange(fieldName, setter) {
    return (value) => {
      setter(value);
      const strValue = arrayToString(value);
      setInputs((inputs) => ({ ...inputs, [fieldName]: strValue }));
    };
  }

  function onSubmit() {
    const updateArray = compareObjects(inputs, inputsRow);
    if (!updateArray.length) return showWarning(t('你似乎并没有修改什么'));
    const requestQueue = updateArray
      .filter((item) => {
        // 跳过敏感字段的空值提交，避免覆盖已保存的密钥
        if (
          item.key === 'region_sync.sync_api_key' &&
          (!inputs[item.key] || inputs[item.key] === '')
        ) {
          return false;
        }
        return true;
      })
      .map((item) => {
        let value = '';
        if (typeof inputs[item.key] === 'boolean') {
          value = String(inputs[item.key]);
        } else {
          value = String(inputs[item.key]);
        }
        return API.put('/api/option/', {
          key: item.key,
          value,
        });
      });
    if (!requestQueue.length) return showWarning(t('你似乎并没有修改什么'));
    setLoading(true);
    Promise.all(requestQueue)
      .then((res) => {
        if (requestQueue.length === 1) {
          if (res.includes(undefined)) return;
        } else if (requestQueue.length > 1) {
          if (res.includes(undefined))
            return showError(t('部分保存失败，请重试'));
        }
        showSuccess(t('保存成功'));
        props.refresh();
      })
      .catch(() => {
        showError(t('保存失败，请重试'));
      })
      .finally(() => {
        setLoading(false);
      });
  }

  useEffect(() => {
    // 始终从默认值开始，确保所有字段（包括 API 不返回的敏感字段）都有值
    const currentInputs = { ...DEFAULT_INPUTS };
    for (let key in props.options) {
      if (FIELD_TYPES[key]) {
        let value = props.options[key];
        const fieldType = FIELD_TYPES[key];
        // 确保类型正确：API 返回的都是字符串
        if (fieldType === 'number' && typeof value === 'string') {
          value = parseInt(value, 10);
          if (isNaN(value)) value = 0;
        } else if (fieldType === 'boolean' && typeof value === 'string') {
          value = toBoolean(value);
        }
        currentInputs[key] = value;
      }
    }
    setInputs(currentInputs);
    setInputsRow(structuredClone(currentInputs));

    // 转换为数组用于 TagInput
    setSlaveEndpoints(stringToArray(currentInputs['region_sync.slave_endpoints']));
  }, [props.options]);

  // 当条件渲染的组件挂载后，重新设置表单值
  // 原因：setValues 在 enabled/isMaster 变为 true 之前调用，
  // 此时 InputNumber 等组件尚未挂载，无法接收值
  useEffect(() => {
    if (refForm.current) {
      refForm.current.setValues(inputs);
    }
  }, [inputs['region_sync.enabled'], inputs['region_sync.is_master']]);

  const enabled = inputs['region_sync.enabled'];
  const isMaster = inputs['region_sync.is_master'];

  return (
    <>
      <Spin spinning={loading}>
        <Form
          values={inputs}
          getFormApi={(formAPI) => (refForm.current = formAPI)}
          style={{ marginBottom: 15 }}
        >
          <Form.Section text={t('跨区域同步设置')}>
            <Typography.Text
              type='tertiary'
              style={{ marginBottom: 16, display: 'block' }}
            >
              {t('配置国内与海外节点之间的用户数据同步，实现跨区域余额管理')}
            </Typography.Text>

            {/* 启用开关 - 始终显示 */}
            <Row gutter={16}>
              <Col xs={24} sm={12} md={8} lg={8} xl={8}>
                <Form.Switch
                  field={'region_sync.enabled'}
                  label={t('启用跨区域同步')}
                  size='default'
                  checkedText='｜'
                  uncheckedText='〇'
                  onChange={handleFieldChange('region_sync.enabled')}
                />
              </Col>
            </Row>

            {/* 保存按钮 - 未启用时也显示 */}
            {!enabled && (
              <Row style={{ marginTop: 16 }}>
                <Button size='default' onClick={onSubmit}>
                  {t('保存跨区域同步设置')}
                </Button>
              </Row>
            )}

            {/* 启用后才显示以下内容 */}
            {enabled && (
              <>
                {/* 区域 ID */}
                <Row gutter={16} style={{ marginTop: 16 }}>
                  <Col xs={24} sm={12} md={8} lg={8} xl={8}>
                    <Form.Input
                      field={'region_sync.region_id'}
                      label={t('区域 ID')}
                      placeholder={t('例如: cn-east, us-west')}
                      onChange={handleFieldChange('region_sync.region_id')}
                    />
                  </Col>
                </Row>

                {/* 角色选择 */}
                <Row gutter={16} style={{ marginTop: 16 }}>
                  <Col xs={24} sm={12} md={8} lg={8} xl={8}>
                    <Form.Switch
                      field={'region_sync.is_master'}
                      label={t('当前节点为主节点')}
                      size='default'
                      checkedText='｜'
                      uncheckedText='〇'
                      onChange={handleFieldChange('region_sync.is_master')}
                    />
                  </Col>
                </Row>

                {/* 共用设置：API 密钥 */}
                <Row gutter={16} style={{ marginTop: 16 }}>
                  <Col xs={24} sm={24} md={12} lg={12} xl={12}>
                    <Form.Input
                      field={'region_sync.sync_api_key'}
                      label={t('同步 API 密钥')}
                      placeholder={t('用于节点间认证的密钥（已设置的密钥不会显示）')}
                      onChange={handleFieldChange('region_sync.sync_api_key')}
                      type='password'
                      mode='password'
                    />
                  </Col>
                </Row>

                {/* 主节点专属设置 */}
                {isMaster && (
                  <>
                    <Row gutter={16} style={{ marginTop: 16 }}>
                      <Col xs={24}>
                        <div className='semi-form-field'>
                          <label className='semi-form-field-label'>
                            {t('从节点地址列表')}
                          </label>
                          <TagInput
                            value={slaveEndpoints}
                            onChange={handleTagInputChange(
                              'region_sync.slave_endpoints',
                              setSlaveEndpoints
                            )}
                            placeholder={t('输入地址后按回车添加')}
                            separator=','
                            addOnBlur
                            style={{ marginTop: 4 }}
                          />
                          <Typography.Text
                            type='tertiary'
                            size='small'
                            style={{ marginTop: 4, display: 'block' }}
                          >
                            {t('例如: https://slave1.example.com')}
                          </Typography.Text>
                        </div>
                      </Col>
                    </Row>
                    <Row gutter={16} style={{ marginTop: 16 }}>
                      <Col xs={24} sm={12} md={6} lg={6} xl={6}>
                        <Form.InputNumber
                          field={'region_sync.min_balance_threshold'}
                          label={t('最小余额阈值')}
                          placeholder={t('同步触发阈值')}
                          onChange={handleFieldChange(
                            'region_sync.min_balance_threshold'
                          )}
                          min={0}
                          extraText={t('额度单位换算：500,000 额度 = $1 USD。例如设置为 100,000 即 $0.2')}
                        />
                      </Col>
                      <Col xs={24} sm={12} md={6} lg={6} xl={6}>
                        <Form.InputNumber
                          field={'region_sync.sync_interval_seconds'}
                          label={t('同步间隔 (秒)')}
                          placeholder={t('批量同步间隔')}
                          onChange={handleFieldChange(
                            'region_sync.sync_interval_seconds'
                          )}
                          min={10}
                        />
                      </Col>
                      <Col xs={24} sm={12} md={6} lg={6} xl={6}>
                        <Form.InputNumber
                          field={'region_sync.max_retry_count'}
                          label={t('最大重试次数')}
                          placeholder={t('失败重试次数')}
                          onChange={handleFieldChange('region_sync.max_retry_count')}
                          min={0}
                          max={10}
                        />
                      </Col>
                      <Col xs={24} sm={12} md={6} lg={6} xl={6}>
                        <Form.InputNumber
                          field={'region_sync.sync_batch_size'}
                          label={t('同步批次大小')}
                          placeholder={t('每批处理记录数')}
                          onChange={handleFieldChange('region_sync.sync_batch_size')}
                          min={1}
                          max={1000}
                        />
                      </Col>
                    </Row>
                    <Row gutter={16} style={{ marginTop: 16 }}>
                      <Col xs={24} sm={12} md={8} lg={8} xl={8}>
                        <Form.Switch
                          field={'region_sync.disable_cached_consume'}
                          label={t('禁用缓存消费')}
                          size='default'
                          checkedText='｜'
                          uncheckedText='〇'
                          onChange={handleFieldChange(
                            'region_sync.disable_cached_consume'
                          )}
                        />
                      </Col>
                    </Row>
                  </>
                )}

                {/* 从节点专属设置 */}
                {!isMaster && (
                  <>
                    <Row gutter={16} style={{ marginTop: 16 }}>
                      <Col xs={24} sm={24} md={12} lg={12} xl={12}>
                        <Form.Input
                          field={'region_sync.master_endpoint'}
                          label={t('主节点地址')}
                          placeholder={t('例如: https://master.example.com')}
                          onChange={handleFieldChange('region_sync.master_endpoint')}
                        />
                      </Col>
                    </Row>
                    <Row gutter={16} style={{ marginTop: 16 }}>
                      <Col xs={24} sm={12} md={8} lg={8} xl={8}>
                        <Form.InputNumber
                          field={'region_sync.quota_sync_interval_seconds'}
                          label={t('余额同步间隔 (秒)')}
                          placeholder={t('从主节点拉取余额的间隔')}
                          onChange={handleFieldChange(
                            'region_sync.quota_sync_interval_seconds'
                          )}
                          min={30}
                        />
                      </Col>
                    </Row>
                  </>
                )}

                {/* 保存按钮 */}
                <Row style={{ marginTop: 16 }}>
                  <Button size='default' onClick={onSubmit}>
                    {t('保存跨区域同步设置')}
                  </Button>
                </Row>
              </>
            )}
          </Form.Section>
        </Form>
      </Spin>
    </>
  );
}
