import React, { useState, useEffect } from 'react';
import { Modal, Checkbox, Input, Button, Space } from 'antd';
import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import {
  CANVAS_MODAL_PROPS,
  CANVAS_MODAL_TITLE_STYLE,
} from './canvasModalProps';

interface NumCardDataSourceModalProps {
  open: boolean;
  code: string;
  onConfirm: (options: {
    wantChart: boolean;
    chartRange: string;
    wantComparisons: boolean;
    comparisonLabels: string[];
    dataDescription: string;
    code: string;
  }) => void;
  onCancel: () => void;
}

const NumCardDataSourceModal: React.FC<NumCardDataSourceModalProps> = ({
  open,
  code,
  onConfirm,
  onCancel,
}) => {
  const { t } = useTranslation();
  const hasChart =
    /chartData\s*=\s*\{/.test(code) || /variant\s*=\s*"withChart"/.test(code);
  const hasComparisons = /comparisons\s*=\s*\{/.test(code);

  // 解析已有的 comparison labels
  const existingLabels: string[] = [];
  if (hasComparisons) {
    const matches = code.matchAll(/label\s*:\s*"([^"]+)"/g);
    for (const m of matches) {
      existingLabels.push(m[1]);
    }
  }

  const [wantChart, setWantChart] = useState(hasChart);
  const [chartRange, setChartRange] = useState('近7天');
  const [wantComparisons, setWantComparisons] = useState(hasComparisons);
  const [labels, setLabels] = useState<string[]>(
    existingLabels.length > 0 ? existingLabels : ['比昨日'],
  );
  const [dataDescription, setDataDescription] = useState('');

  // 重置 state when modal opens
  useEffect(() => {
    if (open) {
      const curHasChart =
        /chartData\s*=\s*\{/.test(code) ||
        /variant\s*=\s*"withChart"/.test(code);
      const curHasComparisons = /comparisons\s*=\s*\{/.test(code);
      const curLabels: string[] = [];
      if (curHasComparisons) {
        const matches = code.matchAll(/label\s*:\s*"([^"]+)"/g);
        for (const m of matches) {
          curLabels.push(m[1]);
        }
      }
      setWantChart(curHasChart);
      setChartRange('近7天');
      setWantComparisons(curHasComparisons);
      setLabels(curLabels.length > 0 ? curLabels : ['比昨日']);
      setDataDescription('');
    }
  }, [open, code]);

  const handleAddLabel = () => {
    setLabels([...labels, '']);
  };

  const handleRemoveLabel = (index: number) => {
    setLabels(labels.filter((_, i) => i !== index));
  };

  const handleLabelChange = (index: number, value: string) => {
    const next = [...labels];
    next[index] = value;
    setLabels(next);
  };

  const handleConfirm = () => {
    const validLabels = labels.filter((l) => l.trim() !== '');
    onConfirm({
      wantChart,
      chartRange: wantChart ? chartRange : '',
      wantComparisons: wantComparisons && validLabels.length > 0,
      comparisonLabels: validLabels,
      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>
          <Checkbox
            checked={wantChart}
            onChange={(e) => setWantChart(e.target.checked)}
          >
            {t('canvas.dataSourceModal.includeChart')}
          </Checkbox>
          {wantChart && (
            <div
              style={{
                marginTop: 8,
                marginLeft: 24,
                display: 'flex',
                alignItems: 'center',
                gap: 8,
              }}
            >
              <span style={{ flexShrink: 0, fontSize: 13, color: '#595959' }}>
                {t('canvas.dataSourceModal.chartRange')}
              </span>
              <Input
                size="small"
                value={chartRange}
                onChange={(e) => setChartRange(e.target.value)}
                placeholder={t('canvas.dataSourceModal.chartRangePlaceholder')}
                style={{ width: 180 }}
              />
            </div>
          )}
        </div>

        <div>
          <Checkbox
            checked={wantComparisons}
            onChange={(e) => setWantComparisons(e.target.checked)}
          >
            {t('canvas.dataSourceModal.includeComparisons')}
          </Checkbox>

          {wantComparisons && (
            <div style={{ marginTop: 8, marginLeft: 24 }}>
              {labels.map((label, index) => (
                <div
                  key={index}
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: 8,
                    marginBottom: 8,
                  }}
                >
                  <span style={{ flexShrink: 0 }}>
                    {t('canvas.dataSourceModal.comparedTo')}
                  </span>
                  <Input
                    size="small"
                    placeholder={t(
                      'canvas.dataSourceModal.comparedToPlaceholder',
                    )}
                    value={label.replace(/^比/, '')}
                    onChange={(e) =>
                      handleLabelChange(index, `比${e.target.value}`)
                    }
                    style={{ width: 160 }}
                  />
                  {labels.length > 1 && (
                    <MinusCircleOutlined
                      style={{ color: '#ff4d4f', cursor: 'pointer' }}
                      onClick={() => handleRemoveLabel(index)}
                    />
                  )}
                </div>
              ))}
              <Button
                type="dashed"
                size="small"
                icon={<PlusOutlined />}
                onClick={handleAddLabel}
              >
                {t('canvas.dataSourceModal.add')}
              </Button>
            </div>
          )}
        </div>

        <div>
          <div style={{ marginBottom: 6, fontSize: 13, color: '#595959' }}>
            {t('canvas.dataSourceModal.descLabel')}
          </div>
          <Input.TextArea
            value={dataDescription}
            onChange={(e) => setDataDescription(e.target.value)}
            placeholder={t('canvas.dataSourceModal.descPlaceholder')}
            rows={3}
            style={{ resize: 'vertical' }}
          />
        </div>
      </div>
    </Modal>
  );
};

export default NumCardDataSourceModal;
