import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { t as translate } from 'i18next';
import {
  Box,
  Typography,
  Paper,
  Chip,
  IconButton,
  TextField,
  InputAdornment,
  Menu,
  MenuItem,
  Tooltip,
  Button,
  Stack,
  FormControl,
  InputLabel,
  Select,
  OutlinedInput,
  type SelectChangeEvent,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  LinearProgress,
  CircularProgress,
} from '@mui/material';
import {
  Search as SearchIcon,
  FileUpload as FileUploadIcon,
  Delete as DeleteIcon,
  PlayArrow as PlayIcon,
  Stop as StopIcon,
  Edit as EditIcon,
  Visibility as ViewIcon,
  CheckCircle as EnableIcon,
  Cancel as DisableIcon,
  Clear as ClearIcon,
  MoreVert as MoreVertIcon,
  PictureAsPdf as PdfIcon,
  Description as DocIcon,
  Image as ImageIcon,
  VideoFile as VideoIcon,
  AudioFile as AudioIcon,
  Refresh as RefreshIcon,
  InsertDriveFile as FileIcon,
  Upload as UploadIcon,
  BugReportOutlined as ProcessIcon,
} from '@mui/icons-material';
import { DataGrid, type GridColDef, type GridRowSelectionModel } from '@mui/x-data-grid';
import { zhCN, enUS } from '@mui/x-data-grid/locales';
import type { IKnowledgeFile } from '@/interfaces/database/knowledge';
import type { IDocumentInfoFilter } from '@/interfaces/database/document';
import { RunningStatus } from '@/constants/knowledge';
import dayjs from 'dayjs';
import logger from '@/utils/logger';
import { LanguageAbbreviation } from '@/constants/common';


interface DocumentListComponentProps {
  files: IKnowledgeFile[];
  loading: boolean;
  searchKeyword: string;
  onSearchChange: (keyword: string) => void;
  onReparse: (fileIds: string[]) => void;
  onDelete: (fileIds: string[]) => void;
  onUpload: () => void;
  onRefresh: () => void;
  rowSelectionModel: GridRowSelectionModel;
  onRowSelectionModelChange: (model: GridRowSelectionModel) => void;
  // 分页相关props
  total: number;
  page: number;
  pageSize: number;
  onPageChange: (page: number) => void;
  onPageSizeChange: (pageSize: number) => void;
  // 筛选器相关props
  documentFilter?: IDocumentInfoFilter;
  // filter 变化时触发
  onSelectedFilterChange?: (filter: {
    run_status: Array<string>,
    suffix: Array<string>,
  }) => void;
  // 新增操作功能props
  onRename: (fileId: string, newName: string) => void;
  onChangeStatus: (fileIds: string[], status: string) => void;
  onCancelRun: (fileIds: string[]) => void;
  onViewDetails?: (file: IKnowledgeFile) => void;
  onViewProcessDetails?: (file: IKnowledgeFile) => void;
}

const getRunStatusLabel = (status: string) => {
  const statusLabels = {
    [RunningStatus.UNSTART]: translate('knowledge.runStatus.unstart'),
    [RunningStatus.RUNNING]: translate('knowledge.runStatus.running'),
    [RunningStatus.CANCEL]: translate('knowledge.runStatus.cancel'),
    [RunningStatus.DONE]: translate('knowledge.runStatus.done'),
    [RunningStatus.FAIL]: translate('knowledge.runStatus.fail'),
  };
  return statusLabels[status as keyof typeof statusLabels] || translate('knowledge.runStatus.unknown');
};

const getFileIcon = (type: string, suffix?: string) => {
  const fileTypeArr = ['pdf', 'doc', 'docx', 'jpg', 'jpeg', 'png', 'gif', 'mp4', 'avi', 'mov', 'mp3', 'wav'];
  const index = fileTypeArr.indexOf(type.toLowerCase());
  if (index === -1) {
    // type 找不到就用 suffix
    const suffixIndex = fileTypeArr.indexOf(suffix?.toLowerCase() || '');
    if (suffixIndex !== -1) {
      return getFileIcon(fileTypeArr[suffixIndex]);
    }
    return <FileIcon />;
  }

  switch (type.toLowerCase()) {
    case 'pdf': return <PdfIcon color="error" />;
    case 'doc':
    case 'docx': return <DocIcon color="primary" />;
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif': return <ImageIcon color="success" />;
    case 'mp4':
    case 'avi':
    case 'mov': return <VideoIcon color="secondary" />;
    case 'mp3':
    case 'wav': return <AudioIcon color="warning" />;
    default: return <FileIcon />;
  }
};

const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

const getStatusChip = (status: string) => {
  return <Chip label={status === '1' ? translate('common.enabled') : translate('common.disabled')}
    color={status === '1' ? 'success' : 'error'}
    size="small" />;
};

const getRunStatusChip = (run: RunningStatus, progress: number) => {
  const statusConfig = {  
    [RunningStatus.UNSTART]: { label: translate('knowledge.runStatus.unstart'), color: 'default' as const },
    [RunningStatus.RUNNING]: { label: translate('knowledge.runStatus.parsing'), color: 'info' as const },
    [RunningStatus.CANCEL]: { label: translate('knowledge.runStatus.cancel'), color: 'warning' as const },
    [RunningStatus.DONE]: { label: translate('knowledge.runStatus.done'), color: 'success' as const },
    [RunningStatus.FAIL]: { label: translate('knowledge.runStatus.fail'), color: 'error' as const },
  };

  const config = statusConfig[run] || { label: translate('knowledge.runStatus.unknown'), color: 'default' as const };

  if (run === RunningStatus.RUNNING) {
    return (
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <CircularProgress size={16} />
        <Box sx={{ minWidth: 80 }}>
          <Typography variant="caption" color="text.secondary">
            {(progress*100).toFixed(2)}%
          </Typography>
          <LinearProgress variant="determinate" value={progress} sx={{ height: 4, borderRadius: 2 }} />
        </Box>
      </Box>
    );
  }

  return <Chip label={config.label} color={config.color} size="small" />;
};

const DocumentListComponent: React.FC<DocumentListComponentProps> = ({
  files,
  loading,
  searchKeyword,
  onSearchChange,
  onReparse,
  onDelete,
  onUpload,
  onRefresh,
  rowSelectionModel,
  onRowSelectionModelChange,
  total,
  page,
  pageSize,
  onPageChange,
  onPageSizeChange,
  documentFilter,
  onSelectedFilterChange,
  onRename,
  onChangeStatus,
  onCancelRun,
  onViewDetails,
  onViewProcessDetails
}) => {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);

  // 菜单出现的时候选中的 file; selectedFileId 会清空， ref用于上一次的保存状态
  const selectedFileIdRef = useRef<string>('');
  const selectedFileRef = useRef<IKnowledgeFile | undefined>(undefined);

  const [selectedFileId, setSelectedFileId] = useState<string>('');
  const [selectedFile, setSelectedFile] = useState<IKnowledgeFile | undefined>(undefined);

  const [selectedRunStatus, setSelectedRunStatus] = useState<string[]>([]);
  const [selectedSuffix, setSelectedSuffix] = useState<string[]>([]);
  const [renameDialogOpen, setRenameDialogOpen] = useState(false);
  const [newFileName, setNewFileName] = useState('');

  const { i18n, t } = useTranslation();

  // 根据当前语言获取DataGrid的localeText
  const getDataGridLocale = () => {
    const currentLanguage = i18n.language;
    return currentLanguage === LanguageAbbreviation.Zh ? zhCN : enUS;
  };

  const handleFilterSubmit = useCallback(() => {
    const filter = {
      run_status: selectedRunStatus,
      suffix: selectedSuffix,
    };

    if (onSelectedFilterChange) {
      onSelectedFilterChange(filter);
    }
  }, [selectedRunStatus, selectedSuffix])

  const handleMenuClick = (event: React.MouseEvent<HTMLElement>, file: IKnowledgeFile) => {
    event.stopPropagation();
    setAnchorEl(event.currentTarget);
    setSelectedFileId(file.id);
    setSelectedFile(file);
    selectedFileIdRef.current = file.id;
    selectedFileRef.current = file;
  };

  const handleMenuClose = () => {
    setAnchorEl(null);
    setSelectedFileId('');
    setSelectedFile(undefined);
  };

  const handleReparse = () => {
    if (selectedFileId) {
      onReparse([selectedFileId]);
    }
    handleMenuClose();
  };

  const handleDelete = () => {
    if (selectedFileId) {
      onDelete([selectedFileId]);
    }
    handleMenuClose();
  };

  const handleRename = () => {
    if (selectedFileRef.current) {
      setNewFileName(selectedFileRef.current.name);
      setRenameDialogOpen(true);
    }
    handleMenuClose();
  };

  const handleRenameConfirm = () => {
    console.log('selectedFileId', selectedFileIdRef.current);
    console.log('newFileName', newFileName);

    if (selectedFileIdRef.current && newFileName.trim()) {
      onRename(selectedFileIdRef.current, newFileName.trim());
      setRenameDialogOpen(false);
      setNewFileName('');
    }
  };

  const handleChangeStatus = (status: string) => {
    if (selectedFileId) {
      onChangeStatus([selectedFileId], status);
    }
    handleMenuClose();
  };

  const handleCancelRun = () => {
    if (selectedFileId) {
      onCancelRun([selectedFileId]);
    }
    handleMenuClose();
  };

  const handleViewProcessDetails = (file?: IKnowledgeFile) => {
    if (file && onViewProcessDetails) {
      onViewProcessDetails?.(file);
    }
    handleMenuClose();
  };

  const handleViewDetails = (file?: IKnowledgeFile) => {
    if (file && onViewDetails) {
      onViewDetails?.(file);
    }
    handleMenuClose();
  };

  const handleRunStatusChange = (event: SelectChangeEvent<string[]>) => {
    const value = event.target.value;
    setSelectedRunStatus(typeof value === 'string' ? value.split(',') : value);
  };

  const handleSuffixChange = (event: SelectChangeEvent<string[]>) => {
    const value = event.target.value;
    setSelectedSuffix(typeof value === 'string' ? value.split(',') : value);
  };

  // 处理分页变化
  const handlePaginationModelChange = (model: { page: number; pageSize: number }) => {
    if (model.page !== page - 1) { // DataGrid的page是0-based，我们的是1-based
      onPageChange(model.page + 1);
    }
    if (model.pageSize !== pageSize) {
      onPageSizeChange(model.pageSize);
    }
  };

  // DataGrid 列定义
  const columns: GridColDef[] = [
    {
      field: 'name',
      headerName: t('knowledge.fileName'),
      flex: 2,
      minWidth: 200,
      cellClassName: 'grid-center-cell',
      renderCell: (params) => (
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            gap: 1,
            cursor: 'pointer',
            ":hover": { color: 'primary.main', fontWeight: 'bold' }
          }}
          onClick={(e) => {
            e.stopPropagation();
            console.log('查看详情:', params.row);
            if (onViewDetails) {
              onViewDetails(params.row);
            }
          }}
        >
          <Tooltip title={t('knowledge.viewFileDetails', { fileName: params.value })}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              {getFileIcon(params.row.type, params.row.suffix)}
              <Typography variant="body2" noWrap>{params.value}</Typography>
            </Box>
          </Tooltip>
        </Box>
      ),
    },
    {
      field: 'type',
      headerName: t('knowledge.type'),
      flex: 0.5,
      minWidth: 80,
      renderCell: (params) => (
        <Chip label={params.value.toUpperCase()} size="small" variant="outlined" />
      ),
    },
    {
      field: 'size',
      headerName: t('knowledge.size'),
      flex: 0.5,
      minWidth: 80,
      renderCell: (params) => formatFileSize(params.value),
    },
    {
      field: 'chunk_num',
      headerName: t('knowledge.chunkCount'),
      flex: 0.5,
      minWidth: 80,
      type: 'number',
    },
    {
      field: 'status',
      headerName: t('knowledge.status'),
      flex: 0.8,
      minWidth: 100,
      renderCell: (params) => getStatusChip(params.value),
    },
    {
      field: 'run',
      headerName: t('knowledge.parseStatus'),
      flex: 0.8,
      minWidth: 100,
      renderCell: (params) => getRunStatusChip(params.value, params.row.progress),
    },
    {
      field: 'create_time',
      headerName: t('knowledge.uploadTime'),
      flex: 1,
      minWidth: 140,
      valueFormatter: (value) => dayjs(value).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      field: 'actions',
      headerName: t('knowledge.actions'),
      flex: 1.2,
      minWidth: 200,
      sortable: false,
      cellClassName: 'grid-center-cell',
      renderCell: (params) => (
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Box
            sx={{
              display: 'flex',
              alignItems: 'center',
              gap: 0.5,
              cursor: 'pointer',
              padding: '4px 8px',
              borderRadius: 1,
              '&:hover': {
                backgroundColor: 'action.hover',
                color: 'primary.main'
              }
            }}
            onClick={(e) => {
              e.stopPropagation();
              console.log('查看详情:', params.row);
              handleViewDetails(params.row);
            }}
          >
            <ViewIcon fontSize="small" />
          </Box>
          <Box
            sx={{
              display: 'flex',
              alignItems: 'center',
              gap: 0.5,
              cursor: 'pointer',
              padding: '4px 8px',
              borderRadius: 1,
              '&:hover': {
                backgroundColor: 'action.hover',
                color: 'primary.main'
              }
            }}
            onClick={(e) => {
              e.stopPropagation();
              console.log('查看解析详情:', params.row);
              handleViewProcessDetails(params.row);
            }}
          >
            <ProcessIcon fontSize="small" />
          </Box>
          <Tooltip title={t('common.moreActions')}>
            <IconButton
              size="small"
              onClick={(e) => handleMenuClick(e, params.row)}
            >
              <MoreVertIcon fontSize="small" />
            </IconButton>
          </Tooltip>
        </Box>
      ),
    },
  ];

  return (
    <Box>
      {/* 筛选器 */}
      {documentFilter && (
        <Paper sx={{ p: 2, mb: 2 }}>
          <Typography variant="h6" sx={{ mb: 2 }}>{t('knowledge.filter')}</Typography>
          <Stack direction="row" spacing={2} alignItems="center">
            {/* 运行状态筛选 */}
            <FormControl sx={{ minWidth: 200 }}>
              <InputLabel>{t('knowledge.runStatusFilter')}</InputLabel>
              <Select
                multiple
                value={selectedRunStatus}
                onChange={handleRunStatusChange}
                input={<OutlinedInput label={t('knowledge.runStatusFilter')} />}
                renderValue={(selected) => (
                  <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                    {selected.map((value) => (
                      <Chip key={value} label={getRunStatusLabel(value)} size="small" />
                    ))}
                  </Box>
                )}
              >
                {Object.entries(documentFilter.run_status).map(([status, count]) => (
                  <MenuItem key={status} value={status}>
                    {getRunStatusLabel(status)} ({count})
                  </MenuItem>
                ))}
              </Select>
            </FormControl>

            {/* 文件类型筛选 */}
            <FormControl sx={{ minWidth: 200 }}>
              <InputLabel>{t('knowledge.fileTypeFilter')}</InputLabel>
              <Select
                multiple
                value={selectedSuffix}
                onChange={handleSuffixChange}
                input={<OutlinedInput label={t('knowledge.fileTypeFilter')} />}
                renderValue={(selected) => (
                  <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                    {selected.map((value) => (
                      <Chip key={value} label={value.toUpperCase()} size="small" />
                    ))}
                  </Box>
                )}
              >
                {Object.entries(documentFilter.suffix).map(([suffix, count]) => (
                  <MenuItem key={suffix} value={suffix}>
                    {suffix.toUpperCase()} ({count})
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            {/* clear filter */}
            <Button variant="outlined" onClick={async () => {
              await new Promise(resolve => {
                setSelectedRunStatus([]);
                setSelectedSuffix([]);
                setTimeout(resolve, 200);
              });
              handleFilterSubmit();
            }}>
              {t('common.clearFilter')}
            </Button>
            {/* submit filter */}
            <Button variant="contained" onClick={async () => {
              await new Promise(resolve => {
                setTimeout(resolve, 200);
              });
              handleFilterSubmit();
            }}>
              {t('common.confirmFilter')}
            </Button>
          </Stack>
        </Paper>
      )}

      {/* 文件操作栏 */}
      <Paper sx={{ p: 2, mb: 2 }}>
        <Stack direction="row" spacing={2} alignItems="center" justifyContent="space-between">
          <TextField
            placeholder={t('knowledge.searchFiles')}
            value={searchKeyword}
            onChange={(e) => onSearchChange(e.target.value)}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <SearchIcon />
                </InputAdornment>
              ),
            }}
            sx={{ minWidth: 300 }}
            size="small"
          />

          <Stack direction="row" spacing={1}>
            <Button
              variant="contained"
              startIcon={<UploadIcon />}
              onClick={onUpload}
            >
              {t('knowledge.uploadFile')}
            </Button>

            {rowSelectionModel.ids.size > 0 && (
              <>
                <Button
                  variant="outlined"
                  startIcon={<RefreshIcon />}
                  onClick={() => onReparse(Array.from(rowSelectionModel.ids).map((id) => id.toString()))}
                >
                  {t('knowledge.reparse')} ({rowSelectionModel.ids.size})
                </Button>

                <Button
                  variant="outlined"
                  color="error"
                  startIcon={<DeleteIcon />}
                  onClick={() => onDelete(Array.from(rowSelectionModel.ids).map((id) => id.toString()))}
                >
                  {t('common.delete')} ({rowSelectionModel.ids.size})
                </Button>
              </>
            )}

            <IconButton onClick={onRefresh}>
              <RefreshIcon />
            </IconButton>
          </Stack>
        </Stack>
      </Paper>

      {/* 文件列表 */}
      <Paper sx={{ height: 600, width: '100%' }}>
        <DataGrid
          rows={files}
          columns={columns}
          loading={loading}
          checkboxSelection
          disableRowSelectionOnClick
          rowSelectionModel={rowSelectionModel}
          onRowSelectionModelChange={onRowSelectionModelChange}
          pageSizeOptions={[10, 25, 50, 100]}
          paginationMode="server"
          rowCount={total}
          paginationModel={{
            page: page - 1,
            pageSize: pageSize,
          }}
          onPaginationModelChange={handlePaginationModelChange}
          localeText={getDataGridLocale().components.MuiDataGrid.defaultProps.localeText}
          sx={{
            '& .MuiDataGrid-cell:focus': {
              outline: 'none',
            },
            '& .MuiDataGrid-row:hover': {
              backgroundColor: 'action.hover',
            },
          }}
        />
      </Paper>

      {/* 右键菜单 */}
      <Menu
        anchorEl={anchorEl}
        open={Boolean(anchorEl)}
        onClose={handleMenuClose}
      >
        <MenuItem onClick={() => handleViewDetails(selectedFile)}>
          <ViewIcon sx={{ mr: 1 }} />
          <Typography>{t('knowledge.viewDetails')}</Typography>
        </MenuItem>
        <MenuItem onClick={handleRename}>
          <EditIcon sx={{ mr: 1 }} />
          <Typography>{t('common.rename')}</Typography>
        </MenuItem>
        <MenuItem onClick={handleReparse}>
          <PlayIcon sx={{ mr: 1 }} />
          <Typography>{t('knowledge.reparse')}</Typography>
        </MenuItem>
        {selectedFile?.run === RunningStatus.RUNNING && (
          <MenuItem onClick={handleCancelRun}>
            <StopIcon sx={{ mr: 1 }} />
            <Typography>{t('knowledge.cancelRun')}</Typography>
          </MenuItem>
        )}
        {selectedFile?.status === '1' ? (
          <MenuItem onClick={() => handleChangeStatus('0')}>
            <DisableIcon sx={{ mr: 1 }} />
            <Typography>{t('common.disable')}</Typography>
          </MenuItem>
        ) : (
          <MenuItem onClick={() => handleChangeStatus('1')}>
            <EnableIcon sx={{ mr: 1 }} />
            <Typography>{t('common.enable')}</Typography>
          </MenuItem>
        )}
        <MenuItem onClick={handleDelete}>
          <DeleteIcon sx={{ mr: 1 }} color="error" />
          <Typography color="error">{t('common.delete')}</Typography>
        </MenuItem>
      </Menu>

      {/* 重命名对话框 */}
      <Dialog open={renameDialogOpen} onClose={() => setRenameDialogOpen(false)}>
        <DialogTitle>{t('knowledge.renameFile')}</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            margin="dense"
            label={t('knowledge.fileName')}
            fullWidth
            variant="outlined"
            value={newFileName}
            onChange={(e) => setNewFileName(e.target.value)}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setRenameDialogOpen(false)}>{t('common.cancel')}</Button>
          <Button onClick={handleRenameConfirm} variant="contained">{t('common.confirm')}</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default DocumentListComponent;