import React, { useState, useEffect } from 'react';
import {
  Modal,
  Input,
  Checkbox,
  Flex,
  Divider,
  Typography,
  Radio,
  Slider,
} from 'antd';
import {
  BarChartOutlined,
  LineChartOutlined,
  PieChartOutlined,
  RadarChartOutlined,
  AppstoreOutlined,
  GlobalOutlined,
  TableOutlined,
} from '@ant-design/icons';
import {
  CANVAS_MODAL_PROPS,
  CANVAS_MODAL_TITLE_STYLE,
} from './canvasModalProps';

const { Text } = Typography;

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

export interface MultiChartDataSourceResult {
  /** 用户输入的数据描述 */
  dataDescription: string;
  /** 选中的图表类型 */
  charts: string[];
  /** 各图表配置（用于 prompt） */
  chartConfigs: Record<string, Record<string, any>>;
  /** 原始 code */
  code: string;
}

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

// ─── 图表元信息 ──────────────────────────────────────────────────────────────

const ALL_CHART_OPTIONS = [
  { key: 'bar', label: '柱状图', icon: <BarChartOutlined /> },
  { key: 'line', label: '折线图', icon: <LineChartOutlined /> },
  { key: 'pie', label: '饼图', icon: <PieChartOutlined /> },
  { key: 'radar', label: '雷达图', icon: <RadarChartOutlined /> },
  { key: 'treemap', label: '矩形树图', icon: <AppstoreOutlined /> },
  { key: 'worldmap', label: '世界地图', icon: <GlobalOutlined /> },
  { key: 'table', label: '表格', icon: <TableOutlined /> },
];

// 每种图表可配置的选项
interface ConfigOptionCheckbox {
  key: string;
  label: string;
  type?: 'checkbox';
  /** 依赖条件：'key' = 该 key 为 true；'key:value' = 该 key 等于 value */
  dependsOn?: string;
}

interface ConfigOptionSelect {
  key: string;
  label: string;
  type: 'select';
  options: { value: string; label: string }[];
}

interface ConfigOptionSlider {
  key: string;
  label: string;
  type: 'slider';
  min: number;
  max: number;
}

type ConfigOption =
  | ConfigOptionCheckbox
  | ConfigOptionSelect
  | ConfigOptionSlider;

const CHART_CONFIG_OPTIONS: Record<string, ConfigOption[]> = {
  bar: [
    {
      key: 'variant',
      label: '样式',
      type: 'select',
      options: [
        { value: 'bar', label: '单系列' },
        { value: 'groupBar', label: '多系列' },
      ],
    },
    {
      key: 'direction',
      label: '方向',
      type: 'select',
      options: [
        { value: 'vertical', label: '纵向' },
        { value: 'horizontal', label: '横向' },
      ],
    },
    { key: 'stacked', label: '堆叠模式', dependsOn: 'variant:groupBar' },
    { key: 'percent', label: '百分比堆叠', dependsOn: 'stacked' },
    { key: 'showGrid', label: '显示网格线' },
    { key: 'showLabel', label: '显示数据标签' },
    { key: 'legendShow', label: '显示图例' },
  ],
  line: [
    { key: 'showGrid', label: '显示网格线' },
    { key: 'showAxis', label: '显示坐标轴' },
    { key: 'showDots', label: '显示坐标点' },
    { key: 'showLabel', label: '显示坐标点数据', dependsOn: 'showDots' },
    { key: 'smooth', label: '拟合曲线' },
    { key: 'area', label: '面积填充' },
    { key: 'stacked', label: '堆叠模式' },
    { key: 'legendShow', label: '显示图例' },
  ],
  pie: [
    {
      key: 'variant',
      label: '样式',
      type: 'select',
      options: [
        { value: 'pie', label: '饼图' },
        { value: 'ring', label: '环形图' },
      ],
    },
    { key: 'legendShow', label: '显示图例' },
  ],
  radar: [
    {
      key: 'dimensionCount',
      label: '维度数量',
      type: 'slider',
      min: 3,
      max: 8,
    },
    { key: 'legendShow', label: '显示图例' },
  ],
  treemap: [{ key: 'legendShow', label: '显示图例' }],
  worldmap: [],
  table: [{ key: 'pagination', label: '显示分页' }],
};

// ─── 从 code 解析当前 charts ─────────────────────────────────────────────────

function parseCharts(code: string): string[] {
  const match = code.match(/charts=\{(\[.*?\])\}/s);
  if (!match) return ['bar', 'line', 'pie'];
  try {
    return JSON.parse(match[1].replace(/'/g, '"'));
  } catch {
    return ['bar', 'line', 'pie'];
  }
}

// ─── Component ───────────────────────────────────────────────────────────────

const MultiChartDataSourceModal: React.FC<MultiChartDataSourceModalProps> = ({
  open,
  code,
  onConfirm,
  onCancel,
}) => {
  const [dataDescription, setDataDescription] = useState('');
  const [selectedCharts, setSelectedCharts] = useState<Set<string>>(new Set());
  const [chartConfigs, setChartConfigs] = useState<
    Record<string, Record<string, any>>
  >({});

  // 初始化
  useEffect(() => {
    if (open) {
      const charts = parseCharts(code);
      setSelectedCharts(new Set(charts));
      setDataDescription('');
      // 初始化每个图表的默认配置
      const configs: Record<string, Record<string, any>> = {};
      ALL_CHART_OPTIONS.forEach(({ key }) => {
        const options = CHART_CONFIG_OPTIONS[key] ?? [];
        configs[key] = {};
        options.forEach((opt) => {
          if (opt.type === 'select') {
            // select 类型：默认选第一个选项
            configs[key][opt.key] = opt.options[0]?.value ?? '';
          } else if (opt.type === 'slider') {
            // slider 类型：默认取中间值
            configs[key][opt.key] = Math.round((opt.min + opt.max) / 2);
          } else {
            // checkbox 类型：showGrid/showLabel/legendShow/showAxis 默认 true，其余 false
            configs[key][opt.key] =
              opt.key === 'showGrid' ||
              opt.key === 'showLabel' ||
              opt.key === 'showAxis' ||
              opt.key === 'legendShow';
          }
        });
      });
      setChartConfigs(configs);
    }
  }, [open, code]);

  const handleChartToggle = (key: string, checked: boolean) => {
    setSelectedCharts((prev) => {
      const next = new Set(prev);
      if (checked) next.add(key);
      else next.delete(key);
      return next;
    });
  };

  const handleConfigToggle = (
    chartKey: string,
    configKey: string,
    checked: boolean,
  ) => {
    setChartConfigs((prev) => {
      const updated = {
        ...prev,
        [chartKey]: { ...prev[chartKey], [configKey]: checked },
      };
      // 当关闭 stacked 时，同步关闭 percent
      if (!checked && configKey === 'stacked') {
        updated[chartKey].percent = false;
      }
      return updated;
    });
  };

  const handleConfigSelect = (
    chartKey: string,
    configKey: string,
    value: string | number,
  ) => {
    setChartConfigs((prev) => {
      const updated = {
        ...prev,
        [chartKey]: { ...prev[chartKey], [configKey]: value },
      };
      // 切到 bar 时，关闭 stacked/percent
      if (configKey === 'variant' && value === 'bar') {
        updated[chartKey].stacked = false;
        updated[chartKey].percent = false;
      }
      return updated;
    });
  };

  /** 检查依赖是否满足 */
  const isDependencyMet = (chartKey: string, dependsOn?: string): boolean => {
    if (!dependsOn) return true;
    const config = chartConfigs[chartKey] ?? {};
    if (dependsOn.includes(':')) {
      const [depKey, depVal] = dependsOn.split(':');
      return config[depKey] === depVal;
    }
    return config[dependsOn] === true;
  };

  const handleConfirm = () => {
    const charts = ALL_CHART_OPTIONS.filter(({ key }) =>
      selectedCharts.has(key),
    ).map(({ key }) => key);

    // 只传选中图表的配置
    const filteredConfigs: Record<string, Record<string, any>> = {};
    charts.forEach((key) => {
      if (chartConfigs[key]) filteredConfigs[key] = chartConfigs[key];
    });

    onConfirm({
      dataDescription: dataDescription.trim(),
      charts,
      chartConfigs: filteredConfigs,
      code,
    });
  };

  return (
    <Modal
      {...CANVAS_MODAL_PROPS}
      title={<span style={CANVAS_MODAL_TITLE_STYLE}>配置复合图表数据来源</span>}
      open={open}
      onOk={handleConfirm}
      onCancel={onCancel}
      okText="确认"
      cancelText="取消"
      okButtonProps={{ disabled: selectedCharts.size === 0 }}
      width={520}
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {/* 数据描述 */}
        <div>
          <div style={{ marginBottom: 6, fontSize: 13, color: '#595959' }}>
            数据来源描述：
          </div>
          <Input.TextArea
            value={dataDescription}
            onChange={(e) => setDataDescription(e.target.value)}
            placeholder="描述你需要的数据，如：从 t_daily_stats 表查询每日各类型设备活跃数"
            rows={3}
            style={{ resize: 'vertical' }}
          />
        </div>

        <Divider style={{ margin: '8px 0' }} />

        {/* 选择图表类型 */}
        <div>
          <div style={{ marginBottom: 8, fontSize: 13, color: '#595959' }}>
            选择展示的图表类型：
          </div>
          <Flex wrap="wrap" gap={8}>
            {ALL_CHART_OPTIONS.map(({ key, label, icon }) => (
              <Checkbox
                key={key}
                checked={selectedCharts.has(key)}
                onChange={(e) => handleChartToggle(key, e.target.checked)}
              >
                <Flex align="center" gap={4}>
                  {icon}
                  <span>{label}</span>
                </Flex>
              </Checkbox>
            ))}
          </Flex>
        </div>

        {/* 各图表配置 */}
        {ALL_CHART_OPTIONS.filter(
          ({ key }) =>
            selectedCharts.has(key) &&
            (CHART_CONFIG_OPTIONS[key]?.length ?? 0) > 0,
        ).map(({ key, label, icon }) => (
          <div key={key}>
            <Flex align="center" gap={6} style={{ marginBottom: 6 }}>
              {icon}
              <Text strong style={{ fontSize: 13 }}>
                {label}配置
              </Text>
            </Flex>
            <Flex wrap="wrap" gap={8} style={{ paddingLeft: 20 }}>
              {(CHART_CONFIG_OPTIONS[key] ?? []).map((opt) => {
                if (opt.type === 'select') {
                  return (
                    <Flex key={opt.key} align="center" gap={6}>
                      <Text style={{ fontSize: 12, color: '#8c8c8c' }}>
                        {opt.label}:
                      </Text>
                      <Radio.Group
                        size="small"
                        value={
                          chartConfigs[key]?.[opt.key] ?? opt.options[0]?.value
                        }
                        onChange={(e) =>
                          handleConfigSelect(key, opt.key, e.target.value)
                        }
                      >
                        {opt.options.map((o) => (
                          <Radio.Button key={o.value} value={o.value}>
                            {o.label}
                          </Radio.Button>
                        ))}
                      </Radio.Group>
                    </Flex>
                  );
                }
                if (opt.type === 'slider') {
                  return (
                    <Flex
                      key={opt.key}
                      align="center"
                      gap={6}
                      style={{ width: '100%' }}
                    >
                      <Text
                        style={{
                          fontSize: 12,
                          color: '#8c8c8c',
                          whiteSpace: 'nowrap',
                        }}
                      >
                        {opt.label}: {chartConfigs[key]?.[opt.key] ?? opt.min}
                      </Text>
                      <Slider
                        min={opt.min}
                        max={opt.max}
                        value={
                          chartConfigs[key]?.[opt.key] ??
                          Math.round((opt.min + opt.max) / 2)
                        }
                        onChange={(v) => handleConfigSelect(key, opt.key, v)}
                        style={{ flex: 1, minWidth: 120 }}
                      />
                    </Flex>
                  );
                }
                const disabled = !isDependencyMet(key, opt.dependsOn);
                return (
                  <Checkbox
                    key={opt.key}
                    checked={chartConfigs[key]?.[opt.key] ?? false}
                    disabled={disabled}
                    onChange={(e) =>
                      handleConfigToggle(key, opt.key, e.target.checked)
                    }
                  >
                    {opt.label}
                  </Checkbox>
                );
              })}
            </Flex>
          </div>
        ))}
      </div>
    </Modal>
  );
};

export default MultiChartDataSourceModal;
