import { useState, useRef, DragEvent } from 'react';
import { Button } from '../ui/button';
import { Upload, Trash2, X, RefreshCw } from 'lucide-react';
import api from '../../lib/api';
import { Term, MediaKind } from '../../types/term';
import { toast } from 'sonner';

interface VideoUploadProps {
  term: Term;
  onSuccess: () => void;
  onCancel: () => void;
}

const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB
const ALLOWED_TYPES = ['video/mp4', 'video/webm', 'video/quicktime'];

export function VideoUpload({ term, onSuccess, onCancel }: VideoUploadProps) {
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [isDragging, setIsDragging] = useState(false);
  const [regeneratingGif, setRegeneratingGif] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const existingVideos = term.media?.filter(m => m.kind === MediaKind.VIDEO) || [];
  const existingGifs = term.media?.filter(m => m.kind === MediaKind.GIF) || [];

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

  const validateFile = (file: File): boolean => {
    if (!ALLOWED_TYPES.includes(file.type)) {
      toast.error('Nevažeći tip datoteke. Dozvoljeni su samo MP4, WebM i MOV formati.');
      return false;
    }

    if (file.size > MAX_FILE_SIZE) {
      toast.error(`Datoteka je prevelika. Maksimalna veličina je ${MAX_FILE_SIZE / 1024 / 1024}MB.`);
      return false;
    }

    return true;
  };

  const handleFileSelect = (file: File) => {
    if (validateFile(file)) {
      setSelectedFile(file);
    }
  };

  const handleDragOver = (e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    setIsDragging(true);
  };

  const handleDragLeave = (e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    setIsDragging(false);
  };

  const handleDrop = (e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    setIsDragging(false);

    const files = e.dataTransfer.files;
    if (files.length > 0) {
      handleFileSelect(files[0]);
    }
  };

  const handleUpload = async () => {
    if (!selectedFile) return;

    try {
      setIsUploading(true);
      setUploadProgress(0);

      const formData = new FormData();
      formData.append('video', selectedFile);

      await api.post(`/api/terms/${term.id}/media`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        onUploadProgress: (progressEvent) => {
          const progress = progressEvent.total
            ? Math.round((progressEvent.loaded * 100) / progressEvent.total)
            : 0;
          setUploadProgress(progress);
        },
      });

      toast.success('Video uspješno učitan');
      setSelectedFile(null);
      onSuccess();
    } catch (err: any) {
      toast.error(err.response?.data?.message || 'Greška pri učitavanju videa');
    } finally {
      setIsUploading(false);
      setUploadProgress(0);
    }
  };

  const handleDeleteVideo = async (mediaId: string) => {
    if (!confirm('Jeste li sigurni da želite obrisati ovaj video?')) return;

    try {
      await api.delete(`/api/terms/${term.id}/media/${mediaId}`);
      toast.success('Video uspješno obrisan');
      onSuccess();
    } catch (err: any) {
      toast.error(err.response?.data?.message || 'Greška pri brisanju videa');
    }
  };

  const handleRegenerateGif = async (videoMediaId: string) => {
    setRegeneratingGif(videoMediaId);
    try {
      await api.post(`/api/terms/${term.id}/media/${videoMediaId}/regenerate-gif`);
      toast.success('GIF uspješno regeneriran');
      onSuccess();
    } catch (err: any) {
      toast.error(err.response?.data?.message || 'Greška pri regeneraciji GIF-a');
    } finally {
      setRegeneratingGif(null);
    }
  };

  return (
    <div className="space-y-4">
      {/* Existing Videos */}
      {existingVideos.length > 0 && (
        <div className="space-y-2">
          <h3 className="font-medium">Postojeći videozapisi</h3>
          {existingVideos.map((media) => {
            // Find corresponding GIF for this video
            const gifFilename = media.url.replace(/\.(mp4|webm|mov)$/i, '.gif').replace('/uploads/videos/', '/uploads/gifs/');
            const correspondingGif = existingGifs.find(g => g.url === gifFilename);

            return (
              <div key={media.id} className="flex items-center gap-4 p-4 border rounded-lg">
                <div className="flex gap-2">
                  <video
                    src={getVideoUrl(media.url)}
                    className="w-48 h-32 object-cover rounded"
                    controls
                  />
                  {correspondingGif && (
                    <img
                      src={getVideoUrl(correspondingGif.url)}
                      alt="GIF preview"
                      className="w-48 h-32 object-cover rounded border-2 border-orange-500"
                      title="GIF preview"
                    />
                  )}
                </div>
                <div className="flex-1">
                  <p className="text-sm text-gray-600">{media.url}</p>
                  {media.durationMs && (
                    <p className="text-xs text-gray-500">
                      Trajanje: {(media.durationMs / 1000).toFixed(1)}s
                    </p>
                  )}
                  {correspondingGif && (
                    <p className="text-xs text-green-600 mt-1">✓ GIF preview dostupan</p>
                  )}
                </div>
                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handleRegenerateGif(media.id)}
                    disabled={regeneratingGif === media.id}
                    title="Regeneriraj GIF preview"
                  >
                    <RefreshCw className={`h-4 w-4 ${regeneratingGif === media.id ? 'animate-spin' : ''}`} />
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => handleDeleteVideo(media.id)}
                  >
                    <Trash2 className="h-4 w-4 text-red-600" />
                  </Button>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Upload Area */}
      <div className="space-y-2">
        <h3 className="font-medium">Dodaj novi video</h3>
        <div
          onDragOver={handleDragOver}
          onDragLeave={handleDragLeave}
          onDrop={handleDrop}
          className={`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${
            isDragging ? 'border-primary bg-primary/5' : 'border-gray-300'
          }`}
        >
          <input
            ref={fileInputRef}
            type="file"
            accept=".mp4,.webm,.mov,video/mp4,video/webm,video/quicktime"
            onChange={(e) => {
              const files = e.target.files;
              if (files && files.length > 0) {
                handleFileSelect(files[0]);
              }
            }}
            className="hidden"
          />

          {selectedFile ? (
            <div className="space-y-4">
              <div className="flex items-center justify-center gap-2">
                <video
                  src={URL.createObjectURL(selectedFile)}
                  className="w-64 h-48 object-cover rounded"
                  controls
                />
              </div>
              <p className="text-sm text-gray-600">{selectedFile.name}</p>
              <p className="text-xs text-gray-500">
                Veličina: {(selectedFile.size / 1024 / 1024).toFixed(2)} MB
              </p>
              <div className="flex gap-2 justify-center">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setSelectedFile(null)}
                  disabled={isUploading}
                >
                  <X className="h-4 w-4 mr-2" />
                  Ukloni
                </Button>
                <Button
                  type="button"
                  onClick={handleUpload}
                  disabled={isUploading}
                >
                  <Upload className="h-4 w-4 mr-2" />
                  {isUploading ? `Učitavanje... ${uploadProgress}%` : 'Učitaj'}
                </Button>
              </div>
              {isUploading && (
                <div className="w-full bg-gray-200 rounded-full h-2">
                  <div
                    className="bg-primary h-2 rounded-full transition-all"
                    style={{ width: `${uploadProgress}%` }}
                  />
                </div>
              )}
            </div>
          ) : (
            <div className="space-y-4">
              <Upload className="h-12 w-12 mx-auto text-gray-400" />
              <div>
                <p className="text-gray-600">Povucite i ispustite video ovdje</p>
                <p className="text-sm text-gray-500">ili</p>
              </div>
              <Button
                type="button"
                variant="outline"
                onClick={() => fileInputRef.current?.click()}
              >
                Odaberite datoteku
              </Button>
              <p className="text-xs text-gray-500">
                Podržani formati: MP4, WebM, MOV (max {MAX_FILE_SIZE / 1024 / 1024}MB)
              </p>
            </div>
          )}
        </div>
      </div>

      {/* Actions */}
      <div className="flex justify-end">
        <Button type="button" variant="outline" onClick={onCancel}>
          Zatvori
        </Button>
      </div>
    </div>
  );
}

