import React from 'react';
import {
  Card,
  CardContent,
  Typography,
  Avatar,
  Box,
  IconButton,
  Menu,
  MenuItem,
  Chip,
  Divider
} from '@mui/material';
import {
  MoreVert as MoreVertIcon,
  Visibility as VisibilityIcon,
  Star as StarIcon,
  CalendarToday as CalendarIcon,
  Person as PersonIcon
} from '@mui/icons-material';
import { useRouter } from 'next/navigation';

interface EnhancedCardProps {
  id: string;
  title: string;
  content: string;
  author: string;
  avatar?: string;
  date?: string;
  rating?: number;
  category?: string;
  type: 'testimonial' | 'success-story';
  onView?: (id: string) => void;
  onEdit?: (id: string) => void;
  onDelete?: (id: string) => void;
}

const EnhancedCard: React.FC<EnhancedCardProps> = ({
  id,
  title,
  content,
  author,
  avatar,
  date,
  rating,
  category,
  type,
  onView,
  onEdit,
  onDelete
}) => {
  const router = useRouter();
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
  const open = Boolean(anchorEl);

  const handleMenuClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleMenuClose = () => {
    setAnchorEl(null);
  };

  const handleView = () => {
    handleMenuClose();
    if (onView) {
      onView(id);
    } else {
      if (type === 'testimonial') {
        router.push(`/dashboard/testimonialDetail?testimonialId=${id}`);
      } else {
        router.push(`/dashboard/successStoryDetail?storyId=${id}`);
      }
    }
  };

  const handleEdit = () => {
    handleMenuClose();
    if (onEdit) {
      onEdit(id);
    }
  };

  const handleDelete = () => {
    handleMenuClose();
    if (onDelete) {
      onDelete(id);
    }
  };

  // Truncate content to 150 characters
  const truncatedContent = content.length > 150 
    ? `${content.substring(0, 150)}...` 
    : content;

  // Get initials from author name
  const getInitials = (name: string) => {
    return name
      .split(' ')
      .map(word => word.charAt(0))
      .join('')
      .toUpperCase()
      .slice(0, 2);
  };

  return (
    <Card
      sx={{
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        transition: 'all 0.3s ease-in-out',
        border: '1px solid',
        borderColor: 'divider',
        '&:hover': {
          transform: 'translateY(-4px)',
          boxShadow: '0 8px 25px rgba(0,0,0,0.15)',
          borderColor: 'primary.main',
        },
        position: 'relative',
        overflow: 'hidden',
        '&::before': {
          content: '""',
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          height: '4px',
          background: type === 'testimonial' 
            ? 'linear-gradient(90deg, #1976d2, #42a5f5)' 
            : 'linear-gradient(90deg, #2e7d32, #4caf50)',
        },
        cursor: 'pointer',
      }}
      onClick={handleView}
    >
      <CardContent sx={{ p: 3, flexGrow: 1, display: 'flex', flexDirection: 'column' }}>
        {/* Header */}
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 2, pr: 2 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, flex: 1, minWidth: 0 }}>
            <Avatar
              src={avatar}
              sx={{
                width: 56,
                height: 56,
                bgcolor: type === 'testimonial' ? 'primary.main' : 'success.main',
                fontSize: '1.2rem',
                fontWeight: 'bold'
              }}
            >
              {getInitials(author)}
            </Avatar>
            <Box sx={{ flex: 1, minWidth: 0 }}>
              <Typography
                variant="h6"
                sx={{
                  fontWeight: 600,
                  color: 'text.primary',
                  mb: 0.5,
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  maxWidth: '140px',
                  display: 'block'
                }}
              >
                {title}
              </Typography>
              <Typography
                variant="body2"
                sx={{
                  color: 'text.secondary',
                  fontWeight: 500,
                  display: 'flex',
                  alignItems: 'center',
                  gap: 0.5
                }}
              >
                <PersonIcon sx={{ fontSize: 16 }} />
                {author}
              </Typography>
            </Box>
          </Box>
          <IconButton
            size="small"
            onClick={e => { e.stopPropagation(); handleMenuClick(e); }}
            sx={{
              color: 'text.secondary',
              '&:hover': {
                backgroundColor: 'action.hover',
                color: 'text.primary'
              }
            }}
          >
            <MoreVertIcon />
          </IconButton>
        </Box>

        {/* Category and Rating */}
        <Box sx={{ display: 'flex', gap: 1, mb: 2, flexWrap: 'wrap' }}>
          {category && (
            <Chip
              label={category}
              size="small"
              sx={{
                bgcolor: type === 'testimonial' ? 'primary.50' : 'success.50',
                color: type === 'testimonial' ? 'primary.700' : 'success.700',
                fontWeight: 500,
                fontSize: '0.75rem'
              }}
            />
          )}
          {rating && (
            <Chip
              icon={<StarIcon sx={{ fontSize: 16, color: '#ffc107' }} />}
              label={`${rating}/5`}
              size="small"
              sx={{
                bgcolor: 'warning.50',
                color: 'warning.700',
                fontWeight: 500,
                fontSize: '0.75rem'
              }}
            />
          )}
        </Box>

        {/* Content */}
        <Typography
          variant="body2"
          sx={{
            color: 'text.secondary',
            lineHeight: 1.6,
            mb: 2,
            flexGrow: 1,
            display: '-webkit-box',
            WebkitLineClamp: 4,
            WebkitBoxOrient: 'vertical',
            overflow: 'hidden'
          }}
        >
          {truncatedContent}
        </Typography>

        <Divider sx={{ my: 2 }} />

        {/* Footer */}
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            {date && (
              <Typography
                variant="caption"
                sx={{
                  color: 'text.disabled',
                  display: 'flex',
                  alignItems: 'center',
                  gap: 0.5
                }}
              >
                <CalendarIcon sx={{ fontSize: 14 }} />
                {new Date(date).toLocaleDateString()}
              </Typography>
            )}
          </Box>
        </Box>
      </CardContent>

      {/* Menu */}
      <Menu
        anchorEl={anchorEl}
        open={open}
        onClose={handleMenuClose}
        transformOrigin={{ horizontal: 'right', vertical: 'top' }}
        anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
      >
        <MenuItem onClick={handleEdit}>
          <MoreVertIcon sx={{ mr: 1, fontSize: 20 }} />
          Edit
        </MenuItem>
        <MenuItem onClick={handleDelete} sx={{ color: 'error.main' }}>
          <MoreVertIcon sx={{ mr: 1, fontSize: 20 }} />
          Delete
        </MenuItem>
      </Menu>
    </Card>
  );
};

export default EnhancedCard; 