import React, { useState, useCallback } from 'react';
import {
  Box,
  Paper,
  Typography,
  Grid,
  Card,
  CardContent,
  Chip,
  Stack,
  Pagination,
  CircularProgress,
  Alert,
  Divider,
  Avatar,
  IconButton,
  Tooltip,
  Checkbox,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  DialogContentText,
  Toolbar,
  FormControlLabel,
  TextField,
  Switch,
  Backdrop,
  Popover,
} from '@mui/material';
import {
  Image as ImageIcon,
  TextSnippet as TextIcon,
  Visibility as VisibilityIcon,
  VisibilityOff as VisibilityOffIcon,
  Delete as DeleteIcon,
  ToggleOn as EnableIcon,
  ToggleOff as DisableIcon,
  SelectAll as SelectAllIcon,
  Clear as ClearIcon,
  Edit as EditIcon,
  Close as CloseIcon,
  Save as SaveIcon,
  ZoomIn as ZoomInIcon,
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import type { IChunk, IChunkDetail } from '@/interfaces/database/knowledge';
import knowledgeService from '@/services/knowledge_service';

interface ChunkListResultProps {
  doc_id: string;
  chunks: IChunk[];
  total: number;
  loading: boolean;
  error: string | null;
  page: number;
  pageSize: number;
  onPageChange: (page: number) => void;
  onRefresh?: () => void;
  docName?: string;
  onLocate?: (chunk: IChunk) => void;
}

function ChunkListResult(props: ChunkListResultProps) {
  const { doc_id, chunks, total, loading, page, pageSize, onPageChange, onRefresh, onLocate } = props;
  const { t } = useTranslation();
  
  // 选择状态
  const [selectedChunks, setSelectedChunks] = useState<string[]>([]);
  const [selectAll, setSelectAll] = useState(false);
  
  // 操作状态
  const [operationLoading, setOperationLoading] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  
  // 图片预览状态
  const [imagePreviewOpen, setImagePreviewOpen] = useState(false);
  const [previewImageUrl, setPreviewImageUrl] = useState('');
  const [imageHoverAnchor, setImageHoverAnchor] = useState<HTMLElement | null>(null);
  const [hoveredImageUrl, setHoveredImageUrl] = useState('');
  
  // 编辑状态
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [editingChunk, setEditingChunk] = useState<IChunkDetail | null>(null);
  const [editContent, setEditContent] = useState('');
  const [editAvailable, setEditAvailable] = useState(true);
  const [editLoading, setEditLoading] = useState(false);

  // 处理单个选择
  const handleSelectChunk = useCallback((chunkId: string, checked: boolean) => {
    setSelectedChunks(prev => {
      if (checked) {
        return [...prev, chunkId];
      } else {
        return prev.filter(id => id !== chunkId);
      }
    });
  }, []);
  
  // 处理全选
  const handleSelectAll = useCallback((checked: boolean) => {
    setSelectAll(checked);
    if (checked) {
      setSelectedChunks(chunks.map(chunk => chunk.chunk_id));
    } else {
      setSelectedChunks([]);
    }
  }, [chunks]);
  
  // 清空选择
  const handleClearSelection = useCallback(() => {
    setSelectedChunks([]);
    setSelectAll(false);
  }, []);
  
  // 启用/禁用chunks
  const handleToggleChunks = useCallback(async (enable: boolean) => {
    if (selectedChunks.length === 0) return;
    
    try {
      setOperationLoading(true);
      await knowledgeService.switchChunk({
        chunk_ids: selectedChunks,
        available_int: enable ? 1 : 0,
        doc_id: doc_id || ''
      });
      
      // delay 800 ms
      await new Promise(resolve => setTimeout(resolve, 800));
      // 清空选择并刷新
      handleClearSelection();
      onRefresh?.();
    } catch (err) {
      console.error('Failed to toggle chunks:', err);
    } finally {
      setOperationLoading(false);
    }
  }, [selectedChunks, handleClearSelection, onRefresh]);

  // 图片hover处理
  const handleImageHover = useCallback((event: React.MouseEvent<HTMLElement>, imageUrl: string) => {
    setImageHoverAnchor(event.currentTarget);
    setHoveredImageUrl(imageUrl);
  }, []);

  const handleImageHoverClose = useCallback(() => {
    setImageHoverAnchor(null);
    setHoveredImageUrl('');
  }, []);

  // 图片点击放大
  const handleImageClick = useCallback((imageUrl: string, chunk?: IChunk) => {
    setPreviewImageUrl(imageUrl);
    setImagePreviewOpen(true);
    if (chunk) {
      onLocate?.(chunk);
    }
  }, []);

  // 编辑chunk
  const handleEditChunk = useCallback(async (chunk: IChunk) => {
    try {
      setEditLoading(true);
      // 获取chunk详情
      const chunk_id = chunk.chunk_id || '';
      const response = await knowledgeService.getChunk({ chunk_id });
      const chunkDetail: IChunkDetail = response.data.data;
      
      setEditingChunk(chunkDetail);
      setEditContent(chunkDetail.content_with_weight || '');

      const available_int = chunk.available_int
      const available_int_D = chunkDetail.available_int;
      if (available_int_D === undefined) {
        setEditAvailable(available_int === 1);
      } else {
        setEditAvailable(available_int_D === 1);
      }

      setEditDialogOpen(true);
    } catch (err) {
      console.error('Failed to get chunk detail:', err);
    } finally {
      setEditLoading(false);
    }
  }, []);

  // 保存编辑
  const handleSaveEdit = useCallback(async () => {
    if (!editingChunk) return;
    
    try {
      setEditLoading(true);
      await knowledgeService.updateChunk({
        ...editingChunk,
        chunk_id: editingChunk.id || '',
        content_with_weight: editContent,
        available_int: editAvailable ? 1 : 0,
      });
      
      setEditDialogOpen(false);
      setEditingChunk(null);
      // delay 800 ms
      await new Promise(resolve => setTimeout(resolve, 800));
      onRefresh?.();
    } catch (err) {
      console.error('Failed to update chunk:', err);
    } finally {
      setEditLoading(false);
    }
  }, [editingChunk, editContent, editAvailable, onRefresh]);

  // 取消编辑
  const handleCancelEdit = useCallback(() => {
    setEditDialogOpen(false);
    setEditingChunk(null);
    setEditContent('');
    setEditAvailable(true);
  }, []);
  
  // 删除chunks
  const handleDeleteChunks = useCallback(async () => {
    if (selectedChunks.length === 0) return;
    
    try {
      setOperationLoading(true);
      await knowledgeService.removeChunk({
        chunk_ids: selectedChunks
      });
      
      // 关闭对话框，清空选择并刷新
      setDeleteDialogOpen(false);
      handleClearSelection();
      onRefresh?.();
    } catch (err) {
      console.error('Failed to delete chunks:', err);
    } finally {
      setOperationLoading(false);
    }
  }, [selectedChunks, handleClearSelection, onRefresh]);

  if (loading) {
    return (
      <Paper sx={{ p: 3, textAlign: 'center' }}>
        <CircularProgress />
        <Typography variant="body2" color="text.secondary" sx={{ mt: 2 }}>
          {t('chunkPage.loadingChunkData')}
        </Typography>
      </Paper>
    );
  }

  if (!chunks || chunks.length === 0) {
    return (
      <Paper sx={{ p: 3, textAlign: 'center' }}>
        <Typography variant="h6" color="text.secondary">
          {t('chunkPage.noChunkData')}
        </Typography>
        <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
          {t('chunkPage.noChunkDataDescription')}
        </Typography>
      </Paper>
    );
  }

  const totalPages = Math.ceil(total / pageSize);
  const enabledCount = chunks.filter(chunk => chunk.available_int === 1).length;
  const selectedEnabledCount = selectedChunks.filter(id => 
    chunks.find(chunk => chunk.chunk_id === id)?.available_int === 1
  ).length;

  const selectedDisabledCount = selectedChunks.length - selectedEnabledCount;

  return (
    <Box>
      {/* 批量操作工具栏 */}
      <Paper sx={{ mb: 3 }}>
        <Toolbar sx={{ px: 2, py: 1 }}>
          <FormControlLabel
            control={
              <Checkbox
                checked={selectAll}
                indeterminate={selectedChunks.length > 0 && selectedChunks.length < chunks.length}
                onChange={(e) => handleSelectAll(e.target.checked)}
              />
            }
            label={`${t('chunkPage.selectAll')} (${t('chunkPage.selected')} ${selectedChunks.length} ${t('chunkPage.items')})`}
          />
          
          <Box sx={{ flexGrow: 1 }} />
          
          {selectedChunks.length > 0 && (
            <Stack direction="row" spacing={1}>
              {selectedDisabledCount > 0 && (
                <Button
                  startIcon={<EnableIcon />}
                  onClick={() => handleToggleChunks(true)}
                  disabled={operationLoading}
                  color="success"
                  variant="outlined"
                  size="small"
                >
                  {t('chunkPage.enable')} ({selectedDisabledCount})
                </Button>
              )}
              
              {selectedEnabledCount > 0 && (
                <Button
                  startIcon={<DisableIcon />}
                  onClick={() => handleToggleChunks(false)}
                  disabled={operationLoading}
                  color="warning"
                  variant="outlined"
                  size="small"
                >
                  {t('chunkPage.disable')} ({selectedEnabledCount})
                </Button>
              )}
              
              <Button
                startIcon={<DeleteIcon />}
                onClick={() => setDeleteDialogOpen(true)}
                disabled={operationLoading}
                color="error"
                variant="outlined"
                size="small"
              >
                {t('common.delete')} ({selectedChunks.length})
              </Button>
              
              <Button
                startIcon={<ClearIcon />}
                onClick={handleClearSelection}
                variant="outlined"
                size="small"
              >
                {t('chunkPage.clearSelection')}
              </Button>
            </Stack>
          )}
        </Toolbar>
      </Paper>

      {/* Chunk列表 */}
      <Paper sx={{ p: 3, mb: 3 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
          <Typography variant="h6">
            {t('chunkPage.chunkList')} ({t('chunkPage.page')} {page} {t('chunkPage.pageOf')} {totalPages} {t('chunkPage.pages')})
          </Typography>
          <Typography variant="body2" color="text.secondary">
            {t('chunkPage.total')} {total} {t('chunkPage.chunks')}
          </Typography>
        </Box>

        <Grid container spacing={2}>
          {chunks.map((chunk, index) => (
            <Grid size={12} key={chunk.chunk_id}>
              <Card
                variant="outlined"
                sx={{
                  transition: 'all 0.2s ease-in-out',
                  '&:hover': {
                    boxShadow: 2,
                  },
                  border: selectedChunks.includes(chunk.chunk_id) ? '2px solid' : '1px solid',
                  borderColor: selectedChunks.includes(chunk.chunk_id) 
                    ? 'primary.main' 
                    : chunk.available_int === 1 
                    ? 'success.light' 
                    : 'grey.300',
                  backgroundColor: selectedChunks.includes(chunk.chunk_id) ? 'action.selected' : 'background.paper',
                }}
              >
                <CardContent sx={{ p: 2 }}>
                  {/* 头部操作区域 */}
                  <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 2 }}>
                    <Checkbox
                      checked={selectedChunks.includes(chunk.chunk_id)}
                      onChange={(e) => handleSelectChunk(chunk.chunk_id, e.target.checked)}
                    />
                    
                    <Chip
                      icon={chunk.available_int === 1 ? <VisibilityIcon /> : <VisibilityOffIcon />}
                      label={chunk.available_int === 1 ? t('chunkPage.enabled') : t('chunkPage.disabled')}
                      size="small"
                      color={chunk.available_int === 1 ? 'success' : 'default'}
                      variant={chunk.available_int === 1 ? 'filled' : 'outlined'}
                    />
                    {/* 定位到文档位置 */}
                    <Tooltip title={'定位'}>
                      <IconButton size="small" onClick={() => onLocate?.(chunk)}>
                        <ZoomInIcon />
                      </IconButton>
                    </Tooltip>
                  </Box>

                  {/* 主要内容区域 - 左右布局 */}
                  <Box sx={{ display: 'flex', gap: 2, minHeight: '120px' }}>
                    {/* 左侧图片区域 */}
                    <Box sx={{ 
                      width: chunk.image_id ? '120px' : '0px',
                      flexShrink: 0,
                      display: chunk.image_id ? 'block' : 'none'
                    }}>
                      {chunk.image_id && (
                        <Box
                          sx={{
                            width: '100%',
                            height: '120px',
                            border: '1px solid',
                            borderColor: 'grey.300',
                            borderRadius: 1,
                            overflow: 'hidden',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            backgroundColor: 'grey.50',
                            position: 'relative',
                            cursor: 'pointer',
                            '&:hover': {
                              borderColor: 'primary.main',
                              '& .image-overlay': {
                                opacity: 1,
                              }
                            }
                          }}
                          onClick={() => handleImageClick(`${import.meta.env.VITE_API_BASE_URL}/v1/document/image/${chunk.image_id}`, chunk)}
                          onMouseEnter={(e) => handleImageHover(e, `${import.meta.env.VITE_API_BASE_URL}/v1/document/image/${chunk.image_id}`)}
                          onMouseLeave={handleImageHoverClose}
                        >
                          <Box
                            component="img"
                            src={`${import.meta.env.VITE_API_BASE_URL}/v1/document/image/${chunk.image_id}`}
                            alt={t('chunkPage.chunkRelatedImage')}
                            sx={{
                              maxWidth: '100%',
                              maxHeight: '100%',
                              objectFit: 'contain',
                            }}
                            onError={(e) => {
                              const target = e.target as HTMLImageElement;
                              target.style.display = 'none';
                            }}
                          />
                          {/* 悬浮覆盖层 */}
                          <Box
                            className="image-overlay"
                            sx={{
                              position: 'absolute',
                              top: 0,
                              left: 0,
                              right: 0,
                              bottom: 0,
                              backgroundColor: 'rgba(0, 0, 0, 0.5)',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              opacity: 0,
                              transition: 'opacity 0.2s ease-in-out',
                            }}
                          >
                            <ZoomInIcon sx={{ color: 'white', fontSize: 32 }} />
                          </Box>
                        </Box>
                      )}
                    </Box>

                    {/* 右侧内容区域 */}
                    <Box sx={{ flex: 1, minWidth: 0, position: 'relative' }}>
                      <Paper
                        variant="outlined"
                        sx={{
                          p: 1.5,
                          height: '120px',
                          overflow: 'auto',
                          backgroundColor: 'grey.50',
                          borderRadius: 1,
                          fontSize: '0.875rem',
                          lineHeight: 1.5,
                          cursor: 'pointer',
                          '&:hover': {
                            backgroundColor: 'grey.100',
                            '& .edit-button': {
                              opacity: 1,
                            }
                          }
                        }}
                        onClick={() => handleEditChunk(chunk)}
                      >
                        <Typography
                          variant="body2"
                          sx={{
                            whiteSpace: 'pre-wrap',
                            color: 'text.primary',
                          }}
                        >
                          {chunk.content_with_weight || t('chunkPage.noContent')}
                        </Typography>
                        
                        {/* 编辑按钮 */}
                        <IconButton
                          className="edit-button"
                          size="small"
                          sx={{
                            position: 'absolute',
                            top: 8,
                            right: 8,
                            opacity: 0,
                            transition: 'opacity 0.2s ease-in-out',
                            backgroundColor: 'background.paper',
                            '&:hover': {
                              backgroundColor: 'primary.light',
                              color: 'primary.contrastText',
                            }
                          }}
                          onClick={(e) => {
                            e.stopPropagation();
                            handleEditChunk(chunk);
                          }}
                        >
                          <EditIcon fontSize="small" />
                        </IconButton>
                      </Paper>
                    </Box>
                  </Box>

                  {/* 关键词区域 */}
                  {((chunk.important_kwd ?? []).length > 0 || (chunk.question_kwd ?? []).length > 0 || (chunk.tag_kwd ?? []).length > 0) && (
                    <Box>
                      <Typography variant="caption" color="text.secondary" sx={{ mb: 1, display: 'block' }}>
                        {t('chunkPage.keywordInfo')}
                      </Typography>

                      <Stack spacing={1}>
                        {chunk.important_kwd && chunk.important_kwd.length > 0 && (
                          <Box>
                            <Typography variant="caption" color="text.secondary" sx={{ mr: 1 }}>
                              {t('chunkPage.important')}:
                            </Typography>
                            {chunk.important_kwd.map((keyword, kwdIndex) => (
                              <Chip
                                key={kwdIndex}
                                label={keyword}
                                size="small"
                                variant="filled"
                                color="primary"
                                sx={{ mr: 0.5, mb: 0.5, fontSize: '0.75rem' }}
                              />
                            ))}
                          </Box>
                        )}

                        {chunk.question_kwd && chunk.question_kwd.length > 0 && (
                          <Box>
                            <Typography variant="caption" color="text.secondary" sx={{ mr: 1 }}>
                              {t('chunkPage.question')}:
                            </Typography>
                            {chunk.question_kwd.map((keyword, kwdIndex) => (
                              <Chip
                                key={kwdIndex}
                                label={keyword}
                                size="small"
                                variant="filled"
                                color="secondary"
                                sx={{ mr: 0.5, mb: 0.5, fontSize: '0.75rem' }}
                              />
                            ))}
                          </Box>
                        )}

                        {chunk.tag_kwd && chunk.tag_kwd.length > 0 && (
                          <Box>
                            <Typography variant="caption" color="text.secondary" sx={{ mr: 1 }}>
                              {t('chunkPage.tag')}:
                            </Typography>
                            {chunk.tag_kwd.map((keyword, kwdIndex) => (
                              <Chip
                                key={kwdIndex}
                                label={keyword}
                                size="small"
                                variant="filled"
                                color="info"
                                sx={{ mr: 0.5, mb: 0.5, fontSize: '0.75rem' }}
                              />
                            ))}
                          </Box>
                        )}
                      </Stack>
                    </Box>
                  )}
                </CardContent>
              </Card>
            </Grid>
          ))}
        </Grid>

        {/* 分页控件 */}
        {totalPages > 1 && (
          <Box sx={{ display: 'flex', justifyContent: 'center', mt: 3 }}>
            <Pagination
              count={totalPages}
              page={page}
              onChange={(_, newPage) => onPageChange(newPage)}
              color="primary"
              showFirstButton
              showLastButton
            />
          </Box>
        )}
      </Paper>

      {/* 图片hover预览 */}
      <Popover
        open={Boolean(imageHoverAnchor)}
        anchorEl={imageHoverAnchor}
        onClose={handleImageHoverClose}
        anchorOrigin={{
          vertical: 'top',
          horizontal: 'right',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'left',
        }}
        sx={{
          pointerEvents: 'none',
        }}
      >
        <Box sx={{ p: 1, maxWidth: 300, maxHeight: 300 }}>
          <Box
            component="img"
            src={hoveredImageUrl}
            alt="Preview"
            sx={{
              maxWidth: '100%',
              maxHeight: '100%',
              objectFit: 'contain',
              display: 'block',
            }}
          />
        </Box>
      </Popover>

      {/* 图片放大预览 */}
      <Dialog
        open={imagePreviewOpen}
        onClose={() => setImagePreviewOpen(false)}
        maxWidth='md'
        fullWidth
        sx={{
          '& .MuiDialog-paper': {
            backgroundColor: 'rgba(0, 0, 0, 0.2)',
          }
        }}
      >
        <DialogContent sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
          <Box
            component="img"
            src={previewImageUrl}
            alt="Full size preview"
            sx={{
              maxWidth: '100%',
              maxHeight: '80vh',
              objectFit: 'contain',
            }}
          />
        </DialogContent>
        <DialogActions>
          <IconButton
            onClick={() => setImagePreviewOpen(false)}
            sx={{ color: 'white' }}
          >
            <CloseIcon />
          </IconButton>
        </DialogActions>
      </Dialog>

      {/* 编辑chunk对话框 */}
      <Dialog
        open={editDialogOpen}
        onClose={handleCancelEdit}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>
          {t('chunkPage.editChunk')}
        </DialogTitle>
        <DialogContent>
          <Box sx={{ mt: 2 }}>
            <TextField
              label={t('chunkPage.content')}
              multiline
              rows={8}
              fullWidth
              value={editContent}
              onChange={(e) => setEditContent(e.target.value)}
              variant="outlined"
              sx={{ mb: 2 }}
            />
            <FormControlLabel
              control={
                <Switch
                  checked={editAvailable}
                  onChange={(e) => setEditAvailable(e.target.checked)}
                />
              }
              label={t('chunkPage.enabled')}
            />
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCancelEdit}>
            {t('common.cancel')}
          </Button>
          <Button 
            onClick={handleSaveEdit} 
            variant="contained"
            disabled={editLoading}
            startIcon={editLoading ? <CircularProgress size={16} /> : <SaveIcon />}
          >
            {editLoading ? t('chunkPage.saving') : t('common.save')}
          </Button>
        </DialogActions>
      </Dialog>

      {/* 删除确认对话框 */}
      <Dialog
        open={deleteDialogOpen}
        onClose={() => setDeleteDialogOpen(false)}
      >
        <DialogTitle>{t('dialog.confirmDelete')}</DialogTitle>
        <DialogContent>
          <DialogContentText>
            {t('chunkPage.confirmDeleteChunks', { count: selectedChunks.length })}
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>
            {t('common.cancel')}
          </Button>
          <Button 
            onClick={handleDeleteChunks} 
            color="error" 
            disabled={operationLoading}
          >
            {operationLoading ? t('chunkPage.deleting') : t('dialog.confirmDelete')}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}

export default ChunkListResult;