import React from 'react';
import {
  Box,
  Typography,
  Card,
  CardContent,
  IconButton,
  Avatar,
  Chip,
} from '@mui/material';
import { MoreVert as MoreVertIcon } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import type { IAgent } from '@/interfaces/database/agent';
import dayjs from 'dayjs';


interface AgentCardProps {
  agent: IAgent;
  onMenuClick: (event: React.MouseEvent<HTMLElement>, agent: IAgent) => void;
  onViewAgent: (agent: IAgent) => void;
}

const AgentCard: React.FC<AgentCardProps> = ({ agent, onMenuClick, onViewAgent }) => {
  const { t } = useTranslation();

  const getAvatarSrc = (src?: string) => {
    if (!src) return undefined;
    // Already a valid data URL
    if (/^data:image\/(png|jpeg|jpg|webp);base64,/.test(src)) return src;
    // HTTP(S) URL
    if (/^https?:\/\//.test(src)) return src;
    // Raw base64 without header -> assume png
    if (/^[A-Za-z0-9+/=]+$/.test(src)) return `data:image/png;base64,${src}`;
    return src;
  };

  const getPermissionInfo = (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 permissionInfo = getPermissionInfo(agent.permission || 'me');

  const nodeCount = agent.dsl?.graph?.nodes?.length ?? 0;
  const edgeCount = agent.dsl?.graph?.edges?.length ?? 0;

  return (
    <Card sx={{ borderRadius: 2, height: 260 }} onClick={() => onViewAgent(agent)}>
      <CardContent>
        <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
            <Avatar src={getAvatarSrc(agent.avatar)} sx={{ bgcolor: 'primary.main' }} />
            <Box>
              <Typography variant="h6" fontWeight={600} className='ellipsis1'>{agent.title}</Typography>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mt: 0.5 }}>
                <Chip
                  label={permissionInfo.label}
                  size="small"
                  sx={{ bgcolor: permissionInfo.color, color: permissionInfo.textColor }}
                />
              </Box>
            </Box>
          </Box>
          <Box>
            <IconButton aria-label={t('common.more')} onClick={(e) => {
              e.stopPropagation();
              onMenuClick(e, agent)
            }}>
              <MoreVertIcon />
            </IconButton>
          </Box>
        </Box>

        <Typography
          variant="body2"
          color="text.secondary"
          className='ellipsis2'
          sx={{ mt: 1 }}
        >
          {agent.description || '-'}
        </Typography>

        <Box
          sx={{
            display: 'flex',
            justifyContent: 'space-around',
            mt: 1,
            p: 1,
            backgroundColor: '#F8F9FA',
            borderRadius: 1,
          }}
        >
          <Box sx={{ textAlign: 'center' }}>
            <Typography variant="h6" sx={{ fontSize: '1.25rem', fontWeight: 600, color: 'primary.main' }}>
              {nodeCount}
            </Typography>
            <Typography variant="caption" color="text.secondary">{t('agent.nodes') || 'Nodes'}</Typography>
          </Box>
          <Box sx={{ textAlign: 'center' }}>
            <Typography variant="h6" sx={{ fontSize: '1.25rem', fontWeight: 600, color: 'primary.main' }}>
              {edgeCount}
            </Typography>
            <Typography variant="caption" color="text.secondary">{t('agent.edges') || 'Edges'}</Typography>
          </Box>
        </Box>

        <Typography variant="caption" color="text.secondary" sx={{ mt: 1, display: 'block' }}>
          {t('agent.updatedAt')}: {dayjs(agent.update_date).format('YYYY-MM-DD HH:mm:ss')}
        </Typography>

        {agent.nickname && (
          <Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>
            {t('agent.creator')}: {agent.nickname}
          </Typography>
        )}
      </CardContent>
    </Card>
  );
};

export default AgentCard;