import { useEffect, useMemo, useState, useCallback } from 'react';
import { Dialog, DialogTitle, DialogContent, Box, List, ListItemButton, ListItemText, Divider, Typography } from '@mui/material';
import { ReactFlow, Background, MiniMap, Controls, SmoothStepEdge } from '@xyflow/react';
import '@xyflow/react/dist/style.css';
import agentService from '@/services/agent_service';
import type { IAgentVersionItem, IAgent, IGraph } from '@/interfaces/database/agent';
import ReadonlyNode from '@/pages/agent/canvas/node/ReadonlyNode';
import NoteNode from '@/pages/agent/canvas/node/NoteNode';

function sanitizeGraph(g?: IGraph | null): IGraph | null {
  if (!g) return null;
  const nodes = (g.nodes || []).map((n: any) => ({ ...n, draggable: false, selectable: false }));
  const edges = (g.edges || []).map((e: any) => {
    const { sourceHandle, targetHandle, ...rest } = e || {};
    return { ...rest };
  });
  return { nodes, edges };
}

const nodeTypes = {
  beginNode: ReadonlyNode,
  agentNode: ReadonlyNode,
  messageNode: ReadonlyNode,
  toolNode: ReadonlyNode,
  noteNode: NoteNode,
  retrievalNode: ReadonlyNode,
  ragNode: ReadonlyNode,
  switchNode: ReadonlyNode,
  categorizeNode: ReadonlyNode,
  iterationNode: ReadonlyNode,
  iterationStartNode: ReadonlyNode,
  keywordNode: ReadonlyNode,
  relevantNode: ReadonlyNode,
  logicNode: ReadonlyNode,
  emailNode: ReadonlyNode,
  tokenizerNode: ReadonlyNode,
  templateNode: ReadonlyNode,
  rewriteNode: ReadonlyNode,
  invokeNode: ReadonlyNode,
  parserNode: ReadonlyNode,
  fileNode: ReadonlyNode,
  extractorNode: ReadonlyNode,
  splitterNode: ReadonlyNode,
  placeholderNode: ReadonlyNode,
  contextNode: ReadonlyNode,
  group: ReadonlyNode,
  generateNode: ReadonlyNode,
} as const;

const edgeTypes = { buttonEdge: SmoothStepEdge, ButtonEdge: SmoothStepEdge } as const;

export interface VersionListDialogProps {
  open: boolean;
  canvasId?: string;
  onClose: () => void;
}

export default function VersionListDialog({ open, canvasId, onClose }: VersionListDialogProps) {
  const [versions, setVersions] = useState<IAgentVersionItem[]>([]);
  const [selected, setSelected] = useState<IAgentVersionItem | null>(null);
  const [detail, setDetail] = useState<IAgent | null>(null);

  const graph = useMemo(() => sanitizeGraph(detail?.dsl?.graph), [detail]);

  const fetchList = useCallback(async () => {
    if (!canvasId) return;
    const res = await agentService.getAgentVersionList(canvasId);
    const list = res?.data?.data || res?.data || [];
    setVersions(list);
    const first = list?.[0] || null;
    setSelected(first);
  }, [canvasId]);

  const fetchDetail = useCallback(async (versionId?: string) => {
    if (!versionId) return;
    const res = await agentService.getVersion(versionId);
    const data = res?.data?.data || res?.data;
    setDetail(data);
  }, []);

  useEffect(() => {
    if (open) fetchList();
  }, [open, fetchList]);

  useEffect(() => {
    if (selected?.id) fetchDetail(selected.id);
  }, [selected, fetchDetail]);

  return (
    <Dialog open={open} onClose={onClose} fullWidth maxWidth="lg">
      <DialogTitle>历史版本</DialogTitle>
      <DialogContent>
        <Box sx={{ display: 'flex', gap: 2, height: 520 }}>
          <Box sx={{ width: 280, borderRight: '1px solid', borderColor: 'divider', overflow: 'auto' }}>
            <List dense>
              {versions.map((v) => (
                <ListItemButton
                  key={v.id}
                  selected={selected?.id === v.id}
                  onClick={() => setSelected(v)}
                >
                  <ListItemText
                    primary={v.title}
                    secondary={`Created: ${v.create_date} ${new Date((String(v.create_time).length >= 13 ? v.create_time : v.create_time * 1000)).toLocaleTimeString()}`}
                  />
                </ListItemButton>
              ))}
            </List>
          </Box>

          <Box sx={{ flex: 1, position: 'relative' }}>
            <Typography variant="subtitle1" gutterBottom>
              {detail?.title || selected?.title || '未选择版本'}
            </Typography>
            <Divider sx={{ mb: 2 }} />
            {graph && (
              <Box sx={{ height: 440 }}>
                <ReactFlow
                  nodes={graph.nodes || []}
                  edges={graph.edges || []}
                  fitView
                  nodesDraggable={false}
                  nodesConnectable={false}
                  elementsSelectable={false}
                  nodeTypes={nodeTypes as any}
                  edgeTypes={edgeTypes as any}
                  defaultEdgeOptions={{ animated: true, type: 'smoothstep' }}
                  proOptions={{ hideAttribution: true }}
                  minZoom={0.25}
                  maxZoom={2}
                  style={{ width: '100%', height: '100%' }}
                >
                  <Background />
                  <MiniMap pannable zoomable />
                  <Controls showInteractive={false} />
                </ReactFlow>
              </Box>
            )}
          </Box>
        </Box>
      </DialogContent>
    </Dialog>
  );
}