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

// ─── Types ────────────────────────────────────────────────────────────────────

export interface TableDataSourceResult {
  columns: string[];
  wantPagination: boolean;
  pageSize: number;
  dataDescription: string;
  code: string;
}

interface TableDataSourceModalProps {
  open: boolean;
  code: string;
  onConfirm: (result: TableDataSourceResult) => void;
  onCancel: () => void;
}

// ─── 从 code 解析已有列名 ─────────────────────────────────────────────────────

function parseColumnTitles(code: string): string[] {
  const titles: string[] = [];
  const regex = /title\s*:\s*"([^"]*)"/g;
  let match: RegExpExecArray | null;
  while ((match = regex.exec(code)) !== null) {
    titles.push(match[1]);
  }
  return titles.length > 0 ? titles : [''];
}

// ─── 从 code 检测 pagination 状态 ─────────────────────────────────────────────

function parsePagination(code: string): { has: boolean; pageSize: number } {
  const has = /pagination\s*=\s*\{\{/.test(code);
  const pageSizeMatch = code.match(/pageSize\s*:\s*(\d+)/);
  return { has, pageSize: pageSizeMatch ? Number(pageSizeMatch[1]) : 10 };
}

// ─── 组件 ─────────────────────────────────────────────────────────────────────

const TableDataSourceModal: React.FC<TableDataSourceModalProps> = ({
  open,
  code,
  onConfirm,
  onCancel,
}) => {
  const { t } = useTranslation();
  const [columns, setColumns] = useState<string[]>(['']);
  const [wantPagination, setWantPagination] = useState(false);
  const [pageSize, setPageSize] = useState(10);
  const [dataDescription, setDataDescription] = useState('');

  useEffect(() => {
    if (open) {
      setColumns(parseColumnTitles(code));
      const pagination = parsePagination(code);
      setWantPagination(pagination.has);
      setPageSize(pagination.pageSize);
      setDataDescription('');
    }
  }, [open, code]);

  const handleConfirm = () => {
    const validColumns = columns.filter((c) => c.trim() !== '');
    onConfirm({
      columns: validColumns.length > 0 ? validColumns : ['名称'],
      wantPagination,
      pageSize,
      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: 8, fontSize: 13, color: '#595959' }}>
            列配置：
          </div>
          {columns.map((col, index) => (
            <div
              key={index}
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: 8,
                marginBottom: 8,
              }}
            >
              <Input
                size="small"
                placeholder={t('canvas.dataSourceModal.columnPlaceholder')}
                value={col}
                onChange={(e) => {
                  const next = [...columns];
                  next[index] = e.target.value;
                  setColumns(next);
                }}
                style={{ width: 200 }}
              />
              {columns.length > 1 && (
                <MinusCircleOutlined
                  style={{ color: '#ff4d4f', cursor: 'pointer' }}
                  onClick={() =>
                    setColumns(columns.filter((_, i) => i !== index))
                  }
                />
              )}
            </div>
          ))}
          <Button
            type="dashed"
            size="small"
            icon={<PlusOutlined />}
            onClick={() => setColumns([...columns, ''])}
          >
            新增列
          </Button>
        </div>

        {/* 分页选项 */}
        <div>
          <Checkbox
            checked={wantPagination}
            onChange={(e) => setWantPagination(e.target.checked)}
          >
            包含分页
          </Checkbox>
          {wantPagination && (
            <div
              style={{
                marginTop: 8,
                marginLeft: 24,
                display: 'flex',
                alignItems: 'center',
                gap: 8,
              }}
            >
              <span style={{ flexShrink: 0, fontSize: 13, color: '#595959' }}>
                每页条数：
              </span>
              <Select
                size="small"
                value={pageSize}
                onChange={(v) => setPageSize(v)}
                style={{ width: 100 }}
                options={[
                  {
                    label: `10 ${t('canvas.dataSourceModal.pageSizeUnit')}`,
                    value: 10,
                  },
                  {
                    label: `20 ${t('canvas.dataSourceModal.pageSizeUnit')}`,
                    value: 20,
                  },
                  {
                    label: `50 ${t('canvas.dataSourceModal.pageSizeUnit')}`,
                    value: 50,
                  },
                  {
                    label: `100 ${t('canvas.dataSourceModal.pageSizeUnit')}`,
                    value: 100,
                  },
                ]}
              />
            </div>
          )}
        </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.tablePlaceholder')}
            rows={3}
            style={{ resize: 'vertical' }}
          />
        </div>
      </div>
    </Modal>
  );
};

export default TableDataSourceModal;
