'use client';

import React, { useState, useRef } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { InteractiveQuestion, MediaItem } from '@/types';
import { 
  Play, 
  Pause, 
  Volume2, 
  VolumeX, 
  Download, 
  FileText, 
  Image as ImageIcon,
  Video,
  Music,
  Maximize,
  X,
  ChevronLeft,
  ChevronRight
} from 'lucide-react';

interface MediaGalleryProps {
  question: InteractiveQuestion;
  questionIndex: number;
  onAnswerChange: (answer: any) => void;
  adminLanguage: string;
}

export default function MediaGallery({
  question,
  questionIndex,
  onAnswerChange,
  adminLanguage
}: MediaGalleryProps) {
  const [currentMediaIndex, setCurrentMediaIndex] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [isMuted, setIsMuted] = useState(false);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [completedMedia, setCompletedMedia] = useState<Set<string>>(new Set());
  const [progress, setProgress] = useState<{ [key: string]: number }>({});
  
  const videoRef = useRef<HTMLVideoElement>(null);
  const audioRef = useRef<HTMLAudioElement>(null);

  const mediaItems = question.mediaItems || [];
  const currentMedia = mediaItems[currentMediaIndex];

  const handleMediaComplete = (mediaId: string) => {
    setCompletedMedia(prev => new Set([...Array.from(prev), mediaId]));
    
    // Update progress
    const newProgress = { ...progress };
    newProgress[mediaId] = 100;
    setProgress(newProgress);

    // Report completion to parent
    onAnswerChange({
      completedMedia: Array.from(new Set([...Array.from(completedMedia), mediaId])),
      currentMediaIndex,
      totalMedia: mediaItems.length,
      progress: newProgress
    });
  };

  const handlePlayPause = () => {
    if (currentMedia?.type === 'video' && videoRef.current) {
      if (isPlaying) {
        videoRef.current.pause();
      } else {
        videoRef.current.play();
      }
      setIsPlaying(!isPlaying);
    } else if (currentMedia?.type === 'audio' && audioRef.current) {
      if (isPlaying) {
        audioRef.current.pause();
      } else {
        audioRef.current.play();
      }
      setIsPlaying(!isPlaying);
    }
  };

  const handleMuteToggle = () => {
    if (videoRef.current) {
      videoRef.current.muted = !isMuted;
    }
    if (audioRef.current) {
      audioRef.current.muted = !isMuted;
    }
    setIsMuted(!isMuted);
  };

  const handleDownload = (media: MediaItem) => {
    // Create download link
    const link = document.createElement('a');
    link.href = media.src;
    link.download = media.title || 'media-file';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const navigateMedia = (direction: 'prev' | 'next') => {
    if (direction === 'prev' && currentMediaIndex > 0) {
      setCurrentMediaIndex(currentMediaIndex - 1);
    } else if (direction === 'next' && currentMediaIndex < mediaItems.length - 1) {
      setCurrentMediaIndex(currentMediaIndex + 1);
    }
    setIsPlaying(false);
  };

  const getMediaIcon = (type: string) => {
    switch (type) {
      case 'video': return <Video className="w-5 h-5" />;
      case 'audio': return <Music className="w-5 h-5" />;
      case 'image': return <ImageIcon className="w-5 h-5" />;
      case 'document': return <FileText className="w-5 h-5" />;
      default: return <FileText className="w-5 h-5" />;
    }
  };

  const renderMediaContent = () => {
    if (!currentMedia) return null;

    switch (currentMedia.type) {
      case 'video':
        return (
          <div className="relative bg-black rounded-lg overflow-hidden">
            <video
              ref={videoRef}
              src={currentMedia.src}
              className="w-full h-64 object-contain"
              onPlay={() => setIsPlaying(true)}
              onPause={() => setIsPlaying(false)}
              onEnded={() => handleMediaComplete(currentMedia.id)}
              controls={false}
            />
            
            {/* Video Controls */}
            <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-4">
              <div className="flex items-center justify-between text-white">
                <div className="flex items-center gap-2">
                  <Button
                    size="sm"
                    variant="ghost"
                    onClick={handlePlayPause}
                    className="text-white hover:bg-white/20"
                  >
                    {isPlaying ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}
                  </Button>
                  
                  <Button
                    size="sm"
                    variant="ghost"
                    onClick={handleMuteToggle}
                    className="text-white hover:bg-white/20"
                  >
                    {isMuted ? <VolumeX className="w-4 h-4" /> : <Volume2 className="w-4 h-4" />}
                  </Button>
                </div>
                
                <Button
                  size="sm"
                  variant="ghost"
                  onClick={() => setIsFullscreen(true)}
                  className="text-white hover:bg-white/20"
                >
                  <Maximize className="w-4 h-4" />
                </Button>
              </div>
            </div>
          </div>
        );

      case 'audio':
        return (
          <div className="bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg p-6">
            <audio
              ref={audioRef}
              src={currentMedia.src}
              onPlay={() => setIsPlaying(true)}
              onPause={() => setIsPlaying(false)}
              onEnded={() => handleMediaComplete(currentMedia.id)}
              className="hidden"
            />
            
            <div className="flex items-center justify-center gap-4">
              <div className="w-16 h-16 bg-blue-500 rounded-full flex items-center justify-center">
                <Music className="w-8 h-8 text-white" />
              </div>
              
              <div className="flex-1">
                <h3 className="font-semibold text-lg">{currentMedia.title}</h3>
                <p className="text-gray-600 text-sm">{currentMedia.description}</p>
              </div>
              
              <div className="flex items-center gap-2">
                <Button onClick={handlePlayPause} variant="outline">
                  {isPlaying ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}
                </Button>
                
                <Button onClick={handleMuteToggle} variant="outline" size="sm">
                  {isMuted ? <VolumeX className="w-4 h-4" /> : <Volume2 className="w-4 h-4" />}
                </Button>
              </div>
            </div>
          </div>
        );

      case 'image':
        return (
          <div className="relative">
            <img
              src={currentMedia.src}
              alt={currentMedia.title}
              className="w-full h-64 object-cover rounded-lg"
              onLoad={() => handleMediaComplete(currentMedia.id)}
            />
            
            <Button
              className="absolute top-2 right-2"
              size="sm"
              variant="secondary"
              onClick={() => setIsFullscreen(true)}
            >
              <Maximize className="w-4 h-4" />
            </Button>
          </div>
        );

      case 'document':
        return (
          <div className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center">
            <FileText className="w-16 h-16 text-gray-400 mx-auto mb-4" />
            <h3 className="font-semibold text-lg mb-2">{currentMedia.title}</h3>
            <p className="text-gray-600 mb-4">{currentMedia.description}</p>
            
            <div className="flex justify-center gap-2">
              <Button
                onClick={() => window.open(currentMedia.src, '_blank')}
                variant="outline"
              >
                Buka Dokumen
              </Button>
              
              <Button
                onClick={() => handleDownload(currentMedia)}
                variant="outline"
              >
                <Download className="w-4 h-4 mr-2" />
                Download
              </Button>
            </div>
          </div>
        );

      default:
        return (
          <div className="text-center text-gray-500 p-8">
            <p>Tipe media tidak didukung</p>
          </div>
        );
    }
  };

  return (
    <Card className="w-full max-w-4xl mx-auto">
      <CardHeader>
        <CardTitle className="flex items-center justify-between">
          <span className="flex items-center gap-2">
            📚 {question.question || 'Media Gallery'}
          </span>
          <Badge variant="outline">
            {currentMediaIndex + 1} / {mediaItems.length}
          </Badge>
        </CardTitle>
        
        {question.content?.description && (
          <p className="text-gray-600">{question.content.description}</p>
        )}
      </CardHeader>

      <CardContent className="space-y-6">
        {/* Media Navigation */}
        <div className="flex items-center justify-between">
          <Button
            onClick={() => navigateMedia('prev')}
            disabled={currentMediaIndex === 0}
            variant="outline"
            size="sm"
          >
            <ChevronLeft className="w-4 h-4 mr-1" />
            Sebelumnya
          </Button>
          
          <div className="flex items-center gap-2">
            {getMediaIcon(currentMedia?.type || 'document')}
            <span className="font-medium">{currentMedia?.title}</span>
            {completedMedia.has(currentMedia?.id || '') && (
              <Badge className="bg-green-500">✓ Selesai</Badge>
            )}
          </div>
          
          <Button
            onClick={() => navigateMedia('next')}
            disabled={currentMediaIndex === mediaItems.length - 1}
            variant="outline"
            size="sm"
          >
            Selanjutnya
            <ChevronRight className="w-4 h-4 ml-1" />
          </Button>
        </div>

        {/* Media Content */}
        <div className="space-y-4">
          {renderMediaContent()}
          
          {/* Media Description */}
          {currentMedia?.description && (
            <div className="bg-gray-50 rounded-lg p-4">
              <p className="text-gray-700">{currentMedia.description}</p>
              {currentMedia.duration && (
                <p className="text-sm text-gray-500 mt-2">
                  Durasi: {Math.floor(currentMedia.duration / 60)}:{(currentMedia.duration % 60).toString().padStart(2, '0')}
                </p>
              )}
            </div>
          )}
        </div>

        {/* Progress Indicator */}
        <div className="space-y-2">
          <div className="flex justify-between text-sm text-gray-600">
            <span>Progress Media</span>
            <span>{completedMedia.size} / {mediaItems.length} selesai</span>
          </div>
          
          <div className="w-full bg-gray-200 rounded-full h-2">
            <div 
              className="bg-blue-600 h-2 rounded-full transition-all duration-300"
              style={{ width: `${(completedMedia.size / mediaItems.length) * 100}%` }}
            />
          </div>
        </div>

        {/* Media List */}
        <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
          {mediaItems.map((media, index) => (
            <button
              key={media.id}
              onClick={() => setCurrentMediaIndex(index)}
              className={`p-3 rounded-lg border text-left transition-colors ${
                index === currentMediaIndex
                  ? 'border-blue-500 bg-blue-50'
                  : 'border-gray-200 hover:border-gray-300'
              }`}
            >
              <div className="flex items-center gap-2 mb-1">
                {getMediaIcon(media.type)}
                <span className="text-sm font-medium truncate">{media.title}</span>
              </div>
              
              <div className="flex items-center justify-between">
                <span className="text-xs text-gray-500 capitalize">{media.type}</span>
                {completedMedia.has(media.id) && (
                  <Badge className="bg-green-500 text-xs">✓</Badge>
                )}
              </div>
            </button>
          ))}
        </div>
      </CardContent>

      {/* Fullscreen Modal */}
      {isFullscreen && (
        <div className="fixed inset-0 bg-black bg-opacity-90 flex items-center justify-center z-50">
          <div className="relative max-w-6xl max-h-full p-4">
            <Button
              onClick={() => setIsFullscreen(false)}
              className="absolute top-2 right-2 z-10"
              variant="secondary"
              size="sm"
            >
              <X className="w-4 h-4" />
            </Button>
            
            {currentMedia?.type === 'image' ? (
              <img
                src={currentMedia.src}
                alt={currentMedia.title}
                className="max-w-full max-h-full object-contain"
              />
            ) : currentMedia?.type === 'video' ? (
              <video
                src={currentMedia.src}
                controls
                className="max-w-full max-h-full"
                autoPlay
              />
            ) : null}
          </div>
        </div>
      )}
    </Card>
  );
}