import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Box,
  Typography,
  List,
  ListItemButton,
  ListItemText,
  Grid,
  Card,
  CardContent,
  CardActions,
  Avatar,
} from '@mui/material';
import { Add as AddIcon } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import agentService from '@/services/agent_service';
import type { IAgentTemplate } from '@/interfaces/database/agent';
import { useSnackbar } from '@/hooks/useSnackbar';
import { AgentCategory } from '@/constants/agent';
import { IAgentCreateRequestBody } from '@/interfaces/request/agent';
import { useAgentOperations } from '@/hooks/agent-hooks';
import { Position } from '@xyflow/react';

interface CreateAgentDialogProps {
  open: boolean;
  onClose: () => void;
  onCreated?: (newId?: string) => void;
}

const CreateAgentDialog: React.FC<CreateAgentDialogProps> = ({ open, onClose, onCreated }) => {
  const { t, i18n } = useTranslation();
  const { showMessage } = useSnackbar();
  const ops = useAgentOperations();
  const [loading, setLoading] = useState(false);
  const [templates, setTemplates] = useState<IAgentTemplate[]>([]);
  const [activeCategory, setActiveCategory] = useState<string>('Recommended');
  const categoryRefs = useRef<Record<string, HTMLDivElement | null>>({});
  const lang = i18n.language?.startsWith('zh') ? 'zh' : 'en';

  useEffect(() => {
    if (!open) return;
    let mounted = true;
    setLoading(true);
    agentService
      .listTemplates()
      .then((res: any) => {
        const data = res?.data?.data || [];
        if (mounted) {
          setTemplates(data);
        }
      })
      .catch((err: any) => {
        console.error('listTemplates error', err);
        showMessage.error(t('common.fetchFailed'));
      })
      .finally(() => {
        if (mounted) setLoading(false);
      });
    return () => {
      mounted = false;
    };
  }, [open]);

  const categories = useMemo(() => {
    const set = new Set<string>();
    templates.forEach((tpl) => {
      if (tpl.canvas_type) set.add(tpl.canvas_type);
    });
    const arr = Array.from(set);
    // 将 Recommended 放在第一位
    arr.sort((a, b) => {
      if (a === 'Recommended') return -1;
      if (b === 'Recommended') return 1;
      return a.localeCompare(b);
    });
    return arr;
  }, [templates]);

  // 当分类列表变化时，默认选中 Recommended 或第一个分类
  useEffect(() => {
    if (categories.length > 0) {
      if (!categories.includes(activeCategory)) {
        setActiveCategory(categories.includes('Recommended') ? 'Recommended' : categories[0]);
      }
    }
  }, [categories]);

  // 保证选中项在可视区域
  useEffect(() => {
    const el = categoryRefs.current[activeCategory];
    if (el) {
      el.scrollIntoView({ block: 'nearest', inline: 'nearest' });
    }
  }, [activeCategory]);

  const filteredTemplates = useMemo(() => {
    return templates.filter((tpl) => tpl.canvas_type === activeCategory);
  }, [templates, activeCategory]);

  const handleUseTemplate = async (tpl: IAgentTemplate) => {
    try {
      setLoading(true);
      const body: IAgentCreateRequestBody = {
        title: (tpl.title as any)?.[lang] || 'Untitled',
        avatar: tpl.avatar,
        description: (tpl.description as any)?.[lang] || '',
        dsl: tpl.dsl,
        canvas_category: (tpl as any).canvas_category || AgentCategory.AgentCanvas,
      };
      const result = await ops.createAgent(body);
      if (result.success) {
        if (onCreated) onCreated(result.id);
      }
      onClose();
    } catch (err: any) {
      console.error('create agent by template error', err);
    } finally {
      setLoading(false);
    }
  };

  const handleCreateBlankAgent = async () => {
    try {
      setLoading(true);
      const body: IAgentCreateRequestBody = {
        title: lang === 'zh' ? '空白智能体' : 'Blank Agent',
        dsl: {
          graph: {
            nodes: [
              {
                id: 'begin',
                type: 'beginNode',
                position: { x: 50, y: 200 },
                data: { label: 'Begin', name: 'begin' },
                sourcePosition: Position.Left,
                targetPosition: Position.Right,
              },
            ],
            edges: [],
          },
          components: {
            begin: {
              obj: { component_name: 'Begin', params: {} },
              downstream: [],
              upstream: [],
            },
          },
          retrieval: [],
          history: [],
          path: [],
          messages: [],
          globals: {
            'sys.query': '',
            'sys.user_id': '',
            'sys.conversation_turns': 0,
            'sys.files': [],
          },
        },
        canvas_category: AgentCategory.AgentCanvas,
      };
      const result = await ops.createAgent(body);
      if (result.success) {
        if (onCreated) onCreated(result.id);
      }
      onClose();
    } catch (err: any) {
      console.error('create blank agent error', err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      fullWidth
      maxWidth="lg"
      PaperProps={{ sx: { height: '85%' } }}
    >
      <DialogTitle>{t('agent.createAgent')}</DialogTitle>
      <DialogContent dividers sx={{ overflowY: 'auto', p: 2 }}>
        <Box display="flex" gap={2} sx={{ height: 560 }}>
          {/* 左侧分类 */}
          <Box sx={{ width: 220, borderRight: '1px solid', borderColor: 'divider', overflowY: 'auto' }}>
            <List>
              {categories.map((cat) => (
                <ListItemButton
                  key={cat}
                  selected={activeCategory === cat}
                  onClick={() => setActiveCategory(cat)}
                  ref={(el) => { categoryRefs.current[cat] = el; }}
                >
                  <ListItemText
                    primary={cat}
                    primaryTypographyProps={{
                      color: activeCategory === cat ? 'primary' : 'text.primary',
                      fontWeight: activeCategory === cat ? 700 : 400,
                    }}
                  />
                </ListItemButton>
              ))}
            </List>
          </Box>

          {/* 右侧模板网格 */}
          <Box flex={1} px={2} sx={{ overflowY: 'auto' }}>
            <Grid container spacing={2}>
              {activeCategory === 'Recommended' && (
                <Grid size={{ xs: 12, sm: 6, md: 4 }}>
                  <Card
                    variant="outlined"
                    sx={{
                      height: 220,
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      cursor: 'pointer',
                      p: 4,
                    }}
                    onClick={handleCreateBlankAgent}
                  >
                    <Box display="flex" flexDirection="column" alignItems="center" gap={1}>
                      <AddIcon fontSize="large" />
                      <Typography variant="subtitle1">
                        {lang === 'zh' ? '新建空白智能体' : 'New Blank Agent'}
                      </Typography>
                    </Box>
                  </Card>
                </Grid>
              )}
              {filteredTemplates.map((tpl) => (
                <Grid key={tpl.id} size={{ xs: 12, sm: 6, md: 4 }}>
                  <Card variant="outlined" sx={{ height: 220, display: 'flex', flexDirection: 'column' }}>
                    <CardContent sx={{ flexGrow: 1, pb: 0 }}>
                      <Box display="flex" alignItems="center" gap={2}>
                        <Avatar src={tpl.avatar} />
                        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1}}>
                          <Typography variant="h6" className='ellipsis2'>
                            {(tpl.title as any)?.[lang] || (tpl.title as any)}
                          </Typography>
                          <Typography
                            variant="body2"
                            color="text.secondary"
                            className='ellipsis3'
                          >
                            {(tpl.description as any)?.[lang] || ''}
                          </Typography>
                        </Box>
                      </Box>
                    </CardContent>
                    <CardActions sx={{ justifyContent: 'flex-end', mt: 'auto', p: 2, pt: 1 }}>
                      <Button
                        variant="contained"
                        onClick={() => handleUseTemplate(tpl)}
                        disabled={loading}
                      >
                        {t('agent.useTemplate')}
                      </Button>
                    </CardActions>
                  </Card>
                </Grid>
              ))}
            </Grid>
            {(!loading && filteredTemplates.length === 0) && (
              <Box sx={{ textAlign: 'center', py: 6 }}>
                <Typography color="text.secondary">{t('agent.noTemplates')}</Typography>
              </Box>
            )}
          </Box>
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>{t('common.close')}</Button>
      </DialogActions>
    </Dialog >
  );
};

export default CreateAgentDialog;