import React from 'react';
import {
  Box,
  Typography,
  Card,
  CardContent,
  Grid,
  Chip,
  IconButton,
  Menu,
  MenuItem,
  Button,
  Avatar,
} from '@mui/material';
import {
  MoreVert as MoreVertIcon,
  Folder as FolderIcon,
  ArrowForward as ArrowForwardIcon,
  Add as AddIcon,
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import type { IKnowledge } from '@/interfaces/database/knowledge';

interface KnowledgeCardProps {
  knowledge: IKnowledge;
  onMenuClick: (event: React.MouseEvent<HTMLElement>, kb: IKnowledge) => void;
  onViewKnowledge: (kb: IKnowledge) => void;
}

const KnowledgeCard: React.FC<KnowledgeCardProps> = ({ knowledge, onMenuClick, onViewKnowledge }) => {
  const { t } = useTranslation();
  
  const getStatusInfo = (permission: string) => {
    switch (permission) {
      case 'me':
        return { label: t('common.private'), color: '#E3F2FD', textColor: '#1976D2' };
      case 'team':
        return { label: t('common.team'), color: '#E8F5E8', textColor: '#388E3C' };
      default:
        return { label: t('common.public'), color: '#FFF3E0', textColor: '#F57C00' };
    }
  };

  const statusInfo = getStatusInfo(knowledge.permission || 'me');

  // 格式化更新时间
  const formatUpdateTime = (timestamp: number) => {
    if (!timestamp) return t('common.unknown');
    const date = new Date(timestamp);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // 格式化token数量
  const formatTokenNum = (tokenNum: number) => {
    if (tokenNum < 1000) return tokenNum.toString();
    if (tokenNum < 1000000) return `${(tokenNum / 1000).toFixed(1)}K`;
    return `${(tokenNum / 1000000).toFixed(1)}M`;
  };

  return (
    <Card
      sx={{
        height: '100%',
        transition: 'all 0.2s ease-in-out',
        border: '1px solid #E5E5E5',
        '&:hover': {
          boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
          transform: 'translateY(-2px)',
        },
      }}
    >
      <CardContent onClick={() => onViewKnowledge(knowledge)}>
        <Box display="flex" justifyContent="space-between" alignItems="flex-start">
          <Box display="flex" alignItems="center" gap={1}>
            {/* 显示avatar */}
            {knowledge.avatar ? (
              <Avatar
                src={knowledge.avatar}
                sx={{ width: 32, height: 32 }}
              />
            ) : (
              <FolderIcon color="primary" />
            )}
            <Typography variant="h6" fontWeight={600} noWrap>
              {knowledge.name}
            </Typography>
          </Box>
          <Box>
            <Chip
              label={statusInfo.label}
              size="small"
              sx={{
                fontSize: '0.75rem',
                height: '24px',
                backgroundColor: statusInfo.color,
                color: statusInfo.textColor,
              }}
            />
            <IconButton
              size="small"
              onClick={(e) => {
                e.stopPropagation(); // 阻止事件冒泡
                onMenuClick(e, knowledge);
              }}
            >
              <MoreVertIcon />
            </IconButton>
          </Box>
        </Box>

        <Typography
          variant="body2"
          color="text.secondary"
          sx={{
            mt: 1,
            mb: 2,
            display: '-webkit-box',
            WebkitLineClamp: 2,
            WebkitBoxOrient: 'vertical',
            overflow: 'hidden',
          }}
        >
          {knowledge.description || t('common.noDescription')}
        </Typography>

        <Box
          sx={{
            display: 'flex',
            justifyContent: 'space-between',
            mt: 2,
            p: 1.5,
            backgroundColor: '#F8F9FA',
            borderRadius: 1,
          }}
        >
          <Box sx={{ textAlign: 'center' }}>
            <Typography
              variant="h6"
              sx={{ fontSize: '1.25rem', fontWeight: 600, color: 'primary.main' }}
            >
              {knowledge.doc_num || 0}
            </Typography>
            <Typography variant="caption" color="text.secondary">
              {t('knowledge.documentCount')}
            </Typography>
          </Box>
          <Box sx={{ textAlign: 'center' }}>
            <Typography
              variant="h6"
              sx={{ fontSize: '1.25rem', fontWeight: 600, color: 'primary.main' }}
            >
              {knowledge.chunk_num || 0}
            </Typography>
            <Typography variant="caption" color="text.secondary">
              {t('knowledge.chunkCount')}
            </Typography>
          </Box>
          <Box sx={{ textAlign: 'center' }}>
            <Typography
              variant="h6"
              sx={{ fontSize: '1.25rem', fontWeight: 600, color: 'primary.main' }}
            >
              {formatTokenNum(knowledge.token_num || 0)}
            </Typography>
            <Typography variant="caption" color="text.secondary">
              {t('knowledge.tokenCount')}
            </Typography>
          </Box>
        </Box>

        {/* 显示更新时间 */}
        <Typography variant="caption" color="text.secondary" sx={{ mt: 1, display: 'block' }}>
          {t('knowledge.lastUpdate')}: {formatUpdateTime(knowledge.update_time)}
        </Typography>

        {/* 显示创建者 */}
        {knowledge.nickname && (
          <Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>
            {t('knowledge.creator')}: {knowledge.nickname}
          </Typography>
        )}

        {/* 显示语言 */}
        {knowledge.language && (
          <Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>
            {t('common.language')}: {knowledge.language}
          </Typography>
        )}
      </CardContent>
    </Card>
  );
};

export default KnowledgeCard;