'use client';

import * as React from 'react';
import {
  Box,
  Card,
  CardContent,
  CardMedia,
  Chip,
  IconButton,
  Menu,
  MenuItem,
  Typography,
  useTheme,
  Stack,
  Avatar,
} from '@mui/material';
import { DotsThreeVertical as DotsThreeVerticalIcon } from '@phosphor-icons/react/dist/ssr/DotsThreeVertical';
import { Eye as EyeIcon } from '@phosphor-icons/react/dist/ssr/Eye';
import { PencilSimple as PencilSimpleIcon } from '@phosphor-icons/react/dist/ssr/PencilSimple';
import { Trash as TrashIcon } from '@phosphor-icons/react/dist/ssr/Trash';
import { VideoCamera as VideoCameraIcon } from '@phosphor-icons/react/dist/ssr/VideoCamera';
import { FileText as FileTextIcon } from '@phosphor-icons/react/dist/ssr/FileText';
import { Article as ArticleIcon } from '@phosphor-icons/react/dist/ssr/Article';
import dayjs from 'dayjs';
import type { TrainingContent } from '@/services/training.service';

interface TrainingContentCardProps {
  content: TrainingContent;
  onEdit: (content: TrainingContent) => void;
  onDelete: (content: TrainingContent) => void;
  onDetail: (content: TrainingContent) => void;
}

export function TrainingContentCard({
  content,
  onEdit,
  onDelete,
  onDetail,
}: TrainingContentCardProps): React.JSX.Element {
  const theme = useTheme();
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
  const open = Boolean(anchorEl);

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

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

  const handleEdit = (event: React.MouseEvent) => {
    event.stopPropagation();
    handleMenuClose();
    onEdit(content);
  };

  const handleDelete = (event: React.MouseEvent) => {
    event.stopPropagation();
    handleMenuClose();
    onDelete(content);
  };

  const handleDetail = () => {
    onDetail(content);
  };

  // Determine content type and styling
  const getContentType = () => {
    if (content.videoMediaData) return { type: 'video', icon: VideoCameraIcon, color: '#ef4444' };
    if (content.documentMediaData) return { type: 'document', icon: FileTextIcon, color: '#3b82f6' };
    if (content.blogContent) return { type: 'blog', icon: ArticleIcon, color: '#10b981' };
    return { type: 'unknown', icon: FileTextIcon, color: '#6b7280' };
  };

  const contentTypeInfo = getContentType();
  const IconComponent = contentTypeInfo.icon;

  const getPreviewImage = () => {
    // For videos, prioritize thumbnail if available
    if (content.videoMediaData?.thumbnailUrl) {
      return content.videoMediaData.thumbnailUrl;
    }
    
    // For videos without thumbnail, use a placeholder or video file
    if (content.videoMediaData?.fileUrl) {
      // You might want to return a video placeholder image here
      return content.videoMediaData.fileUrl;
    }
    
    // For documents, you might want to show a document icon/placeholder
    if (content.documentMediaData?.fileUrl) {
      // Return a document placeholder or icon
      return null; // Documents typically don't have preview images
    }
    
    // For blogs, you might want to show a blog placeholder
    if (content.blogContent) {
      return null; // Blogs don't have preview images
    }
    
    return null;
  };

  const previewImage = getPreviewImage();

  return (
    <Card
      onClick={handleDetail}
      sx={{
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        cursor: 'pointer',
        borderRadius: 3,
        overflow: 'hidden',
        background: theme.palette.mode === 'dark' 
          ? 'linear-gradient(145deg, #1e293b 0%, #334155 100%)' 
          : 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
        border: theme.palette.mode === 'dark' 
          ? '1px solid #475569' 
          : '1px solid rgba(255, 255, 255, 0.2)',
        boxShadow: theme.palette.mode === 'dark' 
          ? '0 4px 20px rgba(0, 0, 0, 0.3)' 
          : '0 4px 20px rgba(0, 0, 0, 0.08)',
        transition: 'all 0.3s ease',
        '&:hover': {
          transform: 'translateY(-4px)',
          boxShadow: theme.palette.mode === 'dark' 
            ? '0 8px 40px rgba(0, 0, 0, 0.4)' 
            : '0 8px 40px rgba(0, 0, 0, 0.12)',
        },
      }}
    >
      {/* Header */}
      <Box
        sx={{
          position: 'relative',
          background: `linear-gradient(135deg, ${contentTypeInfo.color}15 0%, ${contentTypeInfo.color}25 100%)`,
          p: 2,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
        }}
      >
        <Stack direction="row" alignItems="center" spacing={2}>
          <Avatar
            sx={{
              bgcolor: contentTypeInfo.color,
              width: 40,
              height: 40,
            }}
          >
            <IconComponent size={20} color="white" />
          </Avatar>
          <Box>
            <Chip
              label={contentTypeInfo.type.charAt(0).toUpperCase() + contentTypeInfo.type.slice(1)}
              size="small"
              sx={{
                bgcolor: `${contentTypeInfo.color}20`,
                color: contentTypeInfo.color,
                fontWeight: 600,
                border: `1px solid ${contentTypeInfo.color}40`,
              }}
            />
          </Box>
        </Stack>

        <IconButton
          onClick={handleMenuClick}
          size="small"
          sx={{
            color: theme.palette.mode === 'dark' ? '#94a3b8' : '#64748b',
            '&:hover': {
              bgcolor: theme.palette.mode === 'dark' ? 'rgba(148, 163, 184, 0.1)' : 'rgba(100, 116, 139, 0.1)',
            },
          }}
        >
          <DotsThreeVerticalIcon size={20} />
        </IconButton>
      </Box>

      {/* Preview Image/Video */}
      {previewImage && (
        <Box
          sx={{
            position: 'relative',
            height: 180,
            overflow: 'hidden',
          }}
        >
          <CardMedia
            component="img"
            height="180"
            image={previewImage}
            alt={content.title || 'Training content'}
            sx={{
              objectFit: 'cover',
              transition: 'transform 0.3s ease',
              '&:hover': {
                transform: 'scale(1.05)',
              },
            }}
          />
          {content.videoMediaData && (
            <Box
              sx={{
                position: 'absolute',
                top: '50%',
                left: '50%',
                transform: 'translate(-50%, -50%)',
                bgcolor: 'rgba(0, 0, 0, 0.7)',
                borderRadius: '50%',
                p: 1,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <VideoCameraIcon size={24} color="white" />
            </Box>
          )}
        </Box>
      )}

      {/* Content */}
      <CardContent sx={{ flexGrow: 1, p: 3 }}>
        {content.title && (
          <Typography
            variant="h6"
            component="h3"
            gutterBottom
            sx={{
              fontWeight: 600,
              color: theme.palette.mode === 'dark' ? '#f1f5f9' : '#1e293b',
              display: '-webkit-box',
              WebkitLineClamp: 2,
              WebkitBoxOrient: 'vertical',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              lineHeight: 1.4,
              minHeight: '2.8em',
            }}
          >
            {content.title}
          </Typography>
        )}

        {content.description && (
          <Typography
            variant="body2"
            color="text.secondary"
            sx={{
              display: '-webkit-box',
              WebkitLineClamp: 3,
              WebkitBoxOrient: 'vertical',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              lineHeight: 1.5,
              mb: 2,
            }}
          >
            {content.description}
          </Typography>
        )}

        {content.blogContent && !content.description && (
          <Typography
            variant="body2"
            color="text.secondary"
            sx={{
              display: '-webkit-box',
              WebkitLineClamp: 3,
              WebkitBoxOrient: 'vertical',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              lineHeight: 1.5,
              mb: 2,
            }}
          >
            {content.blogContent.replace(/<[^>]*>/g, '')} {/* Strip HTML tags for preview */}
          </Typography>
        )}

        {/* Footer */}
        <Box
          sx={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            mt: 'auto',
            pt: 2,
            borderTop: `1px solid ${theme.palette.mode === 'dark' ? '#475569' : '#e2e8f0'}`,
          }}
        >
          <Typography variant="caption" color="text.secondary">
            {dayjs(content.createdAt).format('MMM D, YYYY')}
          </Typography>
          <Chip
            label="Active"
            size="small"
            color="success"
            variant="outlined"
          />
        </Box>
      </CardContent>

      {/* Menu */}
      <Menu
        anchorEl={anchorEl}
        open={open}
        onClose={handleMenuClose}
        PaperProps={{
          sx: {
            minWidth: 160,
            borderRadius: 2,
            boxShadow: theme.palette.mode === 'dark' 
              ? '0 8px 32px rgba(0, 0, 0, 0.4)' 
              : '0 8px 32px rgba(0, 0, 0, 0.15)',
          },
        }}
      >
        <MenuItem onClick={handleDetail} sx={{ py: 1.5 }}>
          <EyeIcon size={18} style={{ marginRight: 12 }} />
          View Details
        </MenuItem>
        <MenuItem onClick={handleEdit} sx={{ py: 1.5 }}>
          <PencilSimpleIcon size={18} style={{ marginRight: 12 }} />
          Edit Content
        </MenuItem>
        <MenuItem onClick={handleDelete} sx={{ py: 1.5, color: 'error.main' }}>
          <TrashIcon size={18} style={{ marginRight: 12 }} />
          Delete Content
        </MenuItem>
      </Menu>
    </Card>
  );
}
