'use client';

import { useState, useCallback } from 'react';
import Image from 'next/image';
import { Play, Eye, Calendar, X, ExternalLink } from 'lucide-react';

export default function VideoCard({ video }) {
  const [imageError, setImageError] = useState(false);
  const [isHovered, setIsHovered] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);

  // Calculate time ago from published_at
  const calculateTimeAgo = (dateString) => {
    if (!dateString) return 'Recently';
    
    // If it's already in "X days ago" format, return as is
    if (typeof dateString === 'string' && dateString.includes('ago')) {
      return dateString;
    }
    
    try {
      const date = new Date(dateString);
      if (isNaN(date.getTime())) {
        // If date parsing fails, try to parse custom format like "SEP 20, 25"
        const months = {
          'JAN': 0, 'FEB': 1, 'MAR': 2, 'APR': 3, 'MAY': 4, 'JUN': 5,
          'JUL': 6, 'AUG': 7, 'SEP': 8, 'OCT': 9, 'NOV': 10, 'DEC': 11
        };
        
        const parts = dateString.toUpperCase().replace(',', '').split(' ');
        if (parts.length === 3 && months[parts[0]]) {
          const month = months[parts[0]];
          const day = parseInt(parts[1]);
          let year = parseInt(parts[2]);
          
          // Handle 2-digit years (assume 2000s)
          if (year < 100) {
            year += 2000;
          }
          
          const parsedDate = new Date(year, month, day);
          if (!isNaN(parsedDate.getTime())) {
            return getTimeDifference(parsedDate);
          }
        }
        return dateString; // Return original if custom parsing fails
      }
      
      return getTimeDifference(date);
    } catch (error) {
      return dateString || 'Recently';
    }
  };

  // Helper function to calculate time difference
  const getTimeDifference = (date) => {
    const now = new Date();
    const diffInMs = now - date;
    const diffInDays = Math.floor(diffInMs / (1000 * 60 * 60 * 24));
    const diffInWeeks = Math.floor(diffInDays / 7);
    const diffInMonths = Math.floor(diffInDays / 30);
    const diffInYears = Math.floor(diffInDays / 365);

    if (diffInYears > 0) {
      return `${diffInYears} year${diffInYears > 1 ? 's' : ''} ago`;
    } else if (diffInMonths > 0) {
      return `${diffInMonths} month${diffInMonths > 1 ? 's' : ''} ago`;
    } else if (diffInWeeks > 0) {
      return `${diffInWeeks} week${diffInWeeks > 1 ? 's' : ''} ago`;
    } else if (diffInDays > 0) {
      return `${diffInDays} day${diffInDays > 1 ? 's' : ''} ago`;
    } else {
      return 'Today';
    }
  };
  
  // Format view_count
  const formatViewCount = (count) => {
    if (!count) return '0';
    
    if (typeof count === 'string' && (count.includes('K') || count.includes('M'))) {
      return count;
    }
    
    const num = parseInt(count);
    if (isNaN(num)) return '0';
    
    if (num >= 1000000) {
      return (num / 1000000).toFixed(1) + 'M';
    } else if (num >= 1000) {
      return (num / 1000).toFixed(1) + 'K';
    }
    return num.toString();
  };
  
  // Format duration
  const formatDuration = (duration) => {
    if (!duration) return '';
    
    if (typeof duration === 'string' && duration.includes(':')) {
      return duration;
    }
    
    const match = duration.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);
    if (match) {
      const hours = parseInt(match[1] || 0);
      const minutes = parseInt(match[2] || 0);
      const seconds = parseInt(match[3] || 0);
      
      if (hours > 0) {
        return `${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
      } else if (minutes > 0) {
        return `${minutes}:${seconds.toString().padStart(2, '0')}`;
      } else {
        return `0:${seconds.toString().padStart(2, '0')}`;
      }
    }
    
    return duration;
  };

  // Get the correct view count
  const getViewCount = () => {
    return video.view_count || '0';
  };

  // Extract YouTube ID from url or video_id
  const getYouTubeId = () => {
    // First try video_id if available
    if (video.video_id) return video.video_id;
    
    // Then try to extract from url
    if (video.url) {
      const match = video.url.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([^&]+)/);
      return match ? match[1] : '';
    }
    
    return '';
  };

  // Get thumbnail URL - prioritize database thumbnail field
  const getThumbnailUrl = () => {
    if (video.thumbnail) {
      return `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${video.thumbnail}`;
    }
    
    // Fallback to YouTube thumbnail if no custom thumbnail
    const videoId = getYouTubeId();
    if (videoId) {
      return `https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`;
    }
    
    return '/assets/default-video-thumbnail.jpg';
  };

  // Handle card click to open modal
  const handleCardClick = useCallback(() => {
    setIsModalOpen(true);
  }, []);

  // Close modal
  const handleCloseModal = useCallback((e) => {
    e?.stopPropagation();
    setIsModalOpen(false);
  }, []);

  // Prevent event bubbling for specific elements
  const handleLinkClick = (e) => {
    e.stopPropagation();
  };

  return (
    <>
      <div 
        className="group cursor-pointer"
        onMouseEnter={() => setIsHovered(true)}
        onMouseLeave={() => setIsHovered(false)}
        onClick={handleCardClick}
      >
        <div className="relative bg-white rounded-2xl shadow-lg hover:shadow-2xl transition-all duration-500 ease-out transform group-hover:-translate-y-2 border border-gray-100 overflow-hidden">
          {/* Thumbnail Container */}
          <div className="relative aspect-video overflow-hidden bg-gradient-to-br from-gray-100 to-gray-200">
            {!imageError ? (
              <>
                <Image
                  src={getThumbnailUrl()}
                  alt={video.title}
                  fill
                  className={`object-cover transition-all duration-700 ${
                    isHovered ? 'scale-110 brightness-110' : 'scale-100'
                  }`}
                  onError={() => setImageError(true)}
                />
                
                {/* Gradient Overlay */}
                <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
                
                {/* Play Button Overlay */}
                <div className={`absolute inset-0 flex items-center justify-center transition-all duration-300 ${
                  isHovered ? 'opacity-100 scale-100' : 'opacity-0 scale-90'
                }`}>
                  <div className="bg-white/20 backdrop-blur-sm rounded-full p-4 transform group-hover:scale-110 transition-transform duration-300">
                    <div className="bg-red-600 rounded-full p-3 shadow-lg">
                      <Play className="w-6 h-6 text-white fill-current ml-1" />
                    </div>
                  </div>
                </div>
              </>
            ) : (
              <div className="flex items-center justify-center w-full h-full bg-gradient-to-br from-gray-200 to-gray-300">
                <div className="text-center">
                  <Play className="w-12 h-12 text-gray-400 mx-auto mb-2" />
                  <span className="text-gray-500 text-sm font-medium">Video Thumbnail</span>
                </div>
              </div>
            )}
            
            {/* Duration Badge */}
            {video.duration && (
              <div className="absolute bottom-3 right-3 bg-black/80 text-white text-xs px-2 py-1 rounded-full backdrop-blur-sm font-medium">
                {formatDuration(video.duration)}
              </div>
            )}
            
            {/* Hover Effect Line */}
            <div className={`absolute bottom-0 left-0 w-0 h-1 bg-gradient-to-r from-red-500 to-pink-500 transition-all duration-500 ${
              isHovered ? 'w-full' : 'w-0'
            }`} />
          </div>
          
          {/* Content Container */}
          <div className="p-5">
            {/* Title */}
            <h3 className="font-bold text-gray-900 line-clamp-2 group-hover:text-red-600 transition-colors duration-300 text-lg leading-tight mb-3">
              {video.title}
            </h3>
            
            {/* Description */}
            <p className="text-gray-600 line-clamp-2 text-sm leading-relaxed mb-4">
              {video.description}
            </p>
            
            {/* Stats & Meta */}
            <div className="flex items-center justify-between pt-3 border-t border-gray-100">
              <div className="flex items-center space-x-4 text-sm text-gray-500">
                {/* Views */}
                <div className="flex items-center space-x-1">
                  <Eye className="w-4 h-4" />
                  <span className="font-medium">{formatViewCount(getViewCount())}</span>
                </div>
                
                {/* Date */}
                <div className="flex items-center space-x-1">
                  <Calendar className="w-4 h-4" />
                  <span className="font-medium">{calculateTimeAgo(video.published_at)}</span>
                </div>
              </div>
              
              {/* Watch Now CTA */}
              <div 
                className={`flex items-center space-x-1 text-sm font-semibold transition-all duration-300 ${
                  isHovered 
                    ? 'text-red-600 scale-105' 
                    : 'text-gray-400'
                }`}
                onClick={handleLinkClick}
              >
                <span>Watch</span>
                <Play className="w-3 h-3 fill-current" />
              </div>
            </div>
          </div>
          
          {/* Glow Effect */}
          <div className={`absolute inset-0 rounded-2xl bg-gradient-to-r from-red-500/10 to-pink-500/10 opacity-0 group-hover:opacity-100 transition-opacity duration-500 pointer-events-none`} />
        </div>
      </div>

      {/* Video Modal */}
      {isModalOpen && (
        <div className="fixed inset-0 z-[9999] flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm">
          <div 
            className="relative bg-white rounded-2xl shadow-2xl w-full max-w-4xl mx-auto overflow-hidden transform transition-all duration-300 scale-95 hover:scale-100"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Close Button */}
            <button
              onClick={handleCloseModal}
              className="absolute top-4 right-4 z-10 bg-white/90 hover:bg-white rounded-full p-2 shadow-lg transition-all duration-200 hover:scale-110 hover:shadow-xl group"
            >
              <X className="w-5 h-5 text-gray-700 group-hover:text-red-600" />
            </button>

            {/* Video Container */}
            <div className="relative aspect-video bg-black rounded-lg overflow-hidden">
              <iframe
                src={`https://www.youtube.com/embed/${getYouTubeId()}?autoplay=1&rel=0&modestbranding=1&showinfo=0&controls=0&fs=0&disablekb=1`}
                className="w-full h-full"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                allowFullScreen={false}
                title={video.title}
              />
            </div>

            {/* Video Info */}
            <div className="p-6">
              <div className="flex items-start justify-between mb-4">
                <h2 className="text-xl font-bold text-gray-900 pr-8">
                  {video.title}
                </h2>
              </div>

              <p className="text-gray-600 mb-4 leading-relaxed">
                {video.description}
              </p>

              <div className="flex items-center space-x-6 text-sm text-gray-500 border-t border-gray-100 pt-4">
                {/* Views */}
                <div className="flex items-center space-x-2">
                  <Eye className="w-4 h-4" />
                  <span className="font-medium">{formatViewCount(getViewCount())} views</span>
                </div>
                
                {/* Date */}
                <div className="flex items-center space-x-2">
                  <Calendar className="w-4 h-4" />
                  <span className="font-medium">Published {calculateTimeAgo(video.published_at)}</span>
                </div>
                
                {/* Duration */}
                {video.duration && (
                  <div className="flex items-center space-x-2">
                    <Play className="w-4 h-4" />
                    <span className="font-medium">{formatDuration(video.duration)}</span>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
}