import React, { useState, useEffect } from 'react';
import { Modal, Slider, Input } from 'antd';
import { useTranslation } from 'react-i18next';
import {
  CANVAS_MODAL_PROPS,
  CANVAS_MODAL_TITLE_STYLE,
} from './canvasModalProps';

interface RadarChartDataSourceModalProps {
  open: boolean;
  code: string;
  onConfirm: (result: {
    dimensionCount: number;
    dataDescription: string;
    code: string;
  }) => void;
  onCancel: () => void;
}

const RadarChartDataSourceModal: React.FC<RadarChartDataSourceModalProps> = ({
  open,
  code,
  onConfirm,
  onCancel,
}) => {
  const { t } = useTranslation();
  const [dimensionCount, setDimensionCount] = useState(5);
  const [dataDescription, setDataDescription] = useState('');

  // 打开时从 code 解析当前 indicators 数量作为默认值
  useEffect(() => {
    if (open) {
      const matches = code.match(/\{\s*name:/g);
      const count = matches ? matches.length : 5;
      setDimensionCount(Math.min(8, Math.max(3, count)));
      setDataDescription('');
    }
  }, [open, code]);

  const handleConfirm = () => {
    onConfirm({
      dimensionCount,
      dataDescription: dataDescription.trim(),
      code,
    });
  };

  return (
    <Modal
      {...CANVAS_MODAL_PROPS}
      title={
        <span style={CANVAS_MODAL_TITLE_STYLE}>
          {t('canvas.dataSourceModal.title')}
        </span>
      }
      open={open}
      onOk={handleConfirm}
      onCancel={onCancel}
      okText={t('canvas.dataSourceModal.ok')}
      cancelText={t('canvas.dataSourceModal.cancel')}
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div>
          <div style={{ marginBottom: 6, fontSize: 13, color: '#595959' }}>
            维度数量：{dimensionCount}
          </div>
          <Slider
            min={3}
            max={8}
            value={dimensionCount}
            onChange={setDimensionCount}
            marks={{ 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8' }}
          />
        </div>

        <div>
          <div style={{ marginBottom: 6, fontSize: 13, color: '#595959' }}>
            数据来源描述：
          </div>
          <Input.TextArea
            value={dataDescription}
            onChange={(e) => setDataDescription(e.target.value)}
            placeholder={t('canvas.dataSourceModal.radarPlaceholder')}
            rows={3}
            style={{ resize: 'vertical' }}
          />
        </div>
      </div>
    </Modal>
  );
};

export default RadarChartDataSourceModal;
