import React, { useState, useCallback } from 'react';
import { Modal, Checkbox, Flex } from 'antd';
import {
  HolderOutlined,
  BarChartOutlined,
  LineChartOutlined,
  PieChartOutlined,
  RadarChartOutlined,
  AppstoreOutlined,
  GlobalOutlined,
  TableOutlined,
} from '@ant-design/icons';
import {
  DndContext,
  PointerSensor,
  useSensor,
  useSensors,
  type DragEndEvent,
} from '@dnd-kit/core';
import {
  SortableContext,
  arrayMove,
  useSortable,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { restrictToVerticalAxis } from '@dnd-kit/modifiers';
import type { CanvasConfigModalProps } from '../canvasConfigRegistry';
import type { MultiChartType } from '@gadmin2n/charts';
import {
  CANVAS_MODAL_PROPS,
  CANVAS_MODAL_TITLE_STYLE,
} from './canvasModalProps';

// ─── 所有可选图表的元信息 ─────────────────────────────────────────────────────

const ALL_CHARTS: {
  key: MultiChartType;
  label: string;
  icon: React.ReactNode;
}[] = [
  { 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 /> },
];

// ─── 从 code 字符串解析 charts prop ──────────────────────────────────────────

function parseCharts(code: string): MultiChartType[] {
  const match = code.match(/charts=\{(\[.*?\])\}/s);
  if (!match) return ['bar', 'line', 'pie'];
  try {
    const parsed = JSON.parse(match[1].replace(/'/g, '"'));
    if (Array.isArray(parsed)) return parsed as MultiChartType[];
  } catch {
    // 解析失败时返回默认值
  }
  return ['bar', 'line', 'pie'];
}

// ─── 将新的 charts 写回 code 字符串 ──────────────────────────────────────────

function writeCharts(code: string, charts: MultiChartType[]): string {
  const chartsStr = `charts={${JSON.stringify(charts)}}`;
  // 已有 charts prop → 替换
  if (/charts=\{.*?\}/s.test(code)) {
    return code.replace(/charts=\{.*?\}/s, chartsStr);
  }
  // 没有 charts prop → 插入到 testId 之前
  return code.replace(/(testId=)/, `${chartsStr}\n  $1`);
}

// ─── SortableChartItem ────────────────────────────────────────────────────────

interface SortableChartItemProps {
  chartKey: MultiChartType;
  label: string;
  icon: React.ReactNode;
  checked: boolean;
  disabled: boolean;
  onToggle: (key: MultiChartType, checked: boolean) => void;
}

const SortableChartItem: React.FC<SortableChartItemProps> = ({
  chartKey,
  label,
  icon,
  checked,
  disabled,
  onToggle,
}) => {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id: chartKey });

  return (
    <Flex
      ref={setNodeRef}
      align="center"
      gap={12}
      style={{
        transform: CSS.Transform.toString(transform),
        transition,
        opacity: isDragging ? 0.5 : 1,
        padding: '8px 0',
        borderBottom: '1px solid #f0f0f0',
        userSelect: 'none',
      }}
    >
      <HolderOutlined
        {...attributes}
        {...listeners}
        style={{
          color: '#ccc',
          cursor: 'grab',
          touchAction: 'none',
          fontSize: 16,
        }}
      />
      <Checkbox
        checked={checked}
        disabled={disabled}
        onChange={(e) => onToggle(chartKey, e.target.checked)}
      />
      {icon}
      <span style={{ fontSize: 14 }}>{label}</span>
    </Flex>
  );
};

// ─── MultiChartConfigModal ───────────────────────────────────────────────────

const MultiChartConfigModal: React.FC<CanvasConfigModalProps> = ({
  code,
  onConfirm,
  onCancel,
}) => {
  const initialCharts = parseCharts(code);
  // 将 ALL_CHARTS 按 initialCharts 顺序排列，未在 initialCharts 中的追加到末尾
  const initialOrder: MultiChartType[] = [
    ...initialCharts,
    ...ALL_CHARTS.map((c) => c.key).filter((k) => !initialCharts.includes(k)),
  ];

  const [order, setOrder] = useState<MultiChartType[]>(initialOrder);
  const [checked, setChecked] = useState<Set<MultiChartType>>(
    new Set(initialCharts),
  );

  const checkedCount = checked.size;

  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
  );

  const handleToggle = useCallback(
    (key: MultiChartType, isChecked: boolean) => {
      setChecked((prev) => {
        const next = new Set(prev);
        if (isChecked) next.add(key);
        else next.delete(key);
        return next;
      });
    },
    [],
  );

  const handleDragEnd = useCallback((event: DragEndEvent) => {
    const { active, over } = event;
    if (!over || active.id === over.id) return;
    setOrder((prev) => {
      const oldIndex = prev.indexOf(active.id as MultiChartType);
      const newIndex = prev.indexOf(over.id as MultiChartType);
      return arrayMove(prev, oldIndex, newIndex);
    });
  }, []);

  const handleOk = useCallback(() => {
    // 按当前 order 顺序，只取 checked 中的项
    const result = order.filter((k) => checked.has(k));
    onConfirm(writeCharts(code, result));
  }, [order, checked, code, onConfirm]);

  return (
    <Modal
      {...CANVAS_MODAL_PROPS}
      open
      title={<span style={CANVAS_MODAL_TITLE_STYLE}>配置图表</span>}
      okText="确认"
      cancelText="取消"
      onOk={handleOk}
      onCancel={onCancel}
    >
      <DndContext
        sensors={sensors}
        modifiers={[restrictToVerticalAxis]}
        onDragEnd={handleDragEnd}
      >
        <SortableContext items={order} strategy={verticalListSortingStrategy}>
          {order.map((key) => {
            const meta = ALL_CHARTS.find((c) => c.key === key)!;
            return (
              <SortableChartItem
                key={key}
                chartKey={key}
                label={meta.label}
                icon={meta.icon}
                checked={checked.has(key)}
                disabled={checked.has(key) && checkedCount === 1}
                onToggle={handleToggle}
              />
            );
          })}
        </SortableContext>
      </DndContext>
    </Modal>
  );
};

export default MultiChartConfigModal;
