import { Plus } from 'lucide-react';
import { Term, CefrLevel } from '../../types/term';
import { Button } from '../ui/button';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '../ui/dialog';

interface WordDetailModalProps {
  term: Term | null;
  open: boolean;
  onClose: () => void;
  onAddToSentence?: (term: Term) => void;
}

const cefrColors: Record<CefrLevel, string> = {
  [CefrLevel.A1]: 'bg-green-500',
  [CefrLevel.A2]: 'bg-green-400',
  [CefrLevel.B1]: 'bg-yellow-500',
  [CefrLevel.B2]: 'bg-yellow-400',
  [CefrLevel.C1]: 'bg-orange-500',
  [CefrLevel.C2]: 'bg-red-500',
};

const wordTypeColors: Record<string, string> = {
  NOUN: 'bg-green-600',           // Imenica - zelena
  VERB: 'bg-red-600',             // Glagol - crvena
  ADJECTIVE: 'bg-blue-600',       // Pridjev - plava
  ADVERB: 'bg-purple-600',        // Prilog - ljubičasta
  PRONOUN: 'bg-yellow-600',       // Zamjenica - žuta
  PREPOSITION: 'bg-orange-600',   // Prijedlog - narančasta
  CONJUNCTION: 'bg-pink-600',     // Veznik - roza
  INTERJECTION: 'bg-teal-600',    // Uzvik - tirkizna
  PHRASE: 'bg-indigo-600',        // Fraza - indigo
  OTHER: 'bg-gray-600',           // Ostalo - siva
};

const wordTypeLabels: Record<string, string> = {
  NOUN: 'Imenica',
  VERB: 'Glagol',
  ADJECTIVE: 'Pridjev',
  ADVERB: 'Prilog',
  PRONOUN: 'Zamjenica',
  PREPOSITION: 'Prijedlog',
  CONJUNCTION: 'Veznik',
  INTERJECTION: 'Uzvik',
  PHRASE: 'Fraza',
  OTHER: 'Ostalo',
};

export function WordDetailModal({ term, open, onClose, onAddToSentence }: WordDetailModalProps) {
  if (!term) return null;

  const videoMedia = term.media?.find(m => m.kind === 'VIDEO');
  const imageMedia = term.media?.find(m => m.kind === 'IMAGE' || m.kind === 'ILLUSTRATION');

  // Construct full video URL
  const API_URL = import.meta.env.VITE_API_URL !== undefined ? import.meta.env.VITE_API_URL : 'http://localhost:3000';
  const videoUrl = videoMedia?.url.startsWith('http')
    ? videoMedia.url
    : `${API_URL}${videoMedia?.url}`;

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle className="flex items-center justify-between">
            <span className={`${wordTypeColors[term.wordType] || 'bg-gray-600'} text-white text-2xl font-bold px-4 py-2 rounded`}>
              {term.wordText}
            </span>
            <span className={`${cefrColors[term.cefrLevel]} text-white text-sm font-bold px-3 py-1 rounded`}>
              {term.cefrLevel}
            </span>
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-6">
          {/* Word Type */}
          <div>
            <p className="text-sm text-gray-500 mb-1">Vrsta riječi</p>
            <p className="text-base font-medium">{wordTypeLabels[term.wordType] || term.wordType}</p>
          </div>

          {/* Video Player */}
          {videoMedia && (
            <div className="bg-gray-100 rounded-lg overflow-hidden">
              <video
                src={videoUrl}
                controls
                loop
                autoPlay
                muted
                className="w-full"
                style={{ maxHeight: '400px' }}
                onError={(e) => {
                  console.error('Video load error:', {
                    url: videoUrl,
                    originalUrl: videoMedia.url,
                    error: e
                  });
                }}
                onLoadedData={() => {
                  console.log('Video loaded successfully:', videoUrl);
                }}
              >
                Vaš preglednik ne podržava video reprodukciju.
              </video>
              {/* Debug info - remove in production */}
              <div className="text-xs text-gray-500 p-2">
                Video URL: {videoUrl}
              </div>
            </div>
          )}

          {/* Image (if no video) */}
          {!videoMedia && imageMedia && (
            <div className="flex justify-center bg-gray-100 rounded-lg p-6">
              <img 
                src={imageMedia.url} 
                alt={term.wordText}
                className="max-h-[300px] max-w-full object-contain"
              />
            </div>
          )}

          {/* Description */}
          {term.shortDescription && (
            <div>
              <p className="text-sm text-gray-500 mb-1">Opis</p>
              <p className="text-base">{term.shortDescription}</p>
            </div>
          )}

          {/* Examples */}
          {term.examples && term.examples.length > 0 && (
            <div>
              <p className="text-sm text-gray-500 mb-2">Primjeri</p>
              <div className="space-y-2">
                {term.examples.map((example) => (
                  <div key={example.id} className="bg-gray-50 p-3 rounded">
                    <p className="text-base">{example.exampleText}</p>
                    {example.notes && (
                      <p className="text-sm text-gray-600 mt-1">{example.notes}</p>
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Tags */}
          {term.tags && (
            <div>
              <p className="text-sm text-gray-500 mb-2">Oznake</p>
              <div className="flex flex-wrap gap-2">
                {JSON.parse(term.tags).map((tag: string, index: number) => (
                  <span
                    key={index}
                    className="bg-indigo-100 text-indigo-800 text-xs font-medium px-2.5 py-0.5 rounded"
                  >
                    {tag}
                  </span>
                ))}
              </div>
            </div>
          )}

          {/* Actions */}
          <div className="flex gap-3 pt-4 border-t">
            <Button variant="outline" onClick={onClose} className="flex-1">
              Zatvori
            </Button>
            {onAddToSentence && (
              <Button onClick={() => { onAddToSentence(term); onClose(); }} className="flex-1">
                <Plus className="h-4 w-4 mr-2" />
                Dodaj u rečenicu
              </Button>
            )}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

