"use client";

import { useState, useRef, useCallback } from 'react';
import Image from 'next/image';
import { Button } from '@/components/ui/button';
import { TextInput } from '@/components/ui/TextInput/TextInput';
import { env } from '@/lib/env';
import { BUILD_VARIANTS } from '@/lib/constants';
import { Upload, X, ImageIcon, Film, Loader2 } from 'lucide-react';

interface UploadedMedia {
  id: string;
  filename: string;
  originalName: string;
  url: string;
  size: number;
  mimetype: string;
}

type MediaType = "image" | "video" | "gif";

interface MediaUploadProps {
  currentMediaUrl?: string;
  currentMediaType?: MediaType;
  onMediaSelect: (url: string, type: MediaType) => void;
  onMediaRemove: () => void;
  funnelId?: string;
}

export function MediaUpload({ 
  currentMediaUrl,
  currentMediaType = "image",
  onMediaSelect, 
  onMediaRemove, 
  funnelId 
}: MediaUploadProps) {
  const [isUploading, setIsUploading] = useState(false);
  const [dragActive, setDragActive] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [uploadedMedia, setUploadedMedia] = useState<UploadedMedia[]>([]);
  const [showGallery, setShowGallery] = useState(false);
  const [isLoadingGallery, setIsLoadingGallery] = useState(false);
  
  const fileInputRef = useRef<HTMLInputElement>(null);

  const getMediaType = (mimetype: string): MediaType => {
    if (mimetype.includes('gif')) return 'gif';
    if (mimetype.includes('video')) return 'video';
    return 'image';
  };

  const loadMedia = useCallback(async () => {
    if (process.env.NEXT_PUBLIC_FUNNEL_BUILD_VARIANT === 'frontend') {
      return;
    }

    setIsLoadingGallery(true);
    try {
      const params = new URLSearchParams();
      if (funnelId) params.append('funnelId', funnelId);
      params.append('limit', '20');

      const response = await fetch(`/api/images?${params}`);
      if (response.ok) {
        const data = await response.json();
        setUploadedMedia(data.images);
      } else {
        console.error('Failed to load media');
      }
    } catch (error) {
      console.error('Error loading media:', error);
    } finally {
      setIsLoadingGallery(false);
    }
  }, [funnelId]);

  const handleFileUpload = async (file: File) => {
    if (process.env.NEXT_PUBLIC_FUNNEL_BUILD_VARIANT === 'frontend') {
      setError('Загрузка файлов недоступна в frontend режиме');
      return;
    }

    setIsUploading(true);
    setError(null);

    try {
      const formData = new FormData();
      formData.append('file', file);
      if (funnelId) formData.append('funnelId', funnelId);

      const response = await fetch('/api/images/upload', {
        method: 'POST',
        body: formData,
      });

      if (response.ok) {
        const uploadedFile = await response.json();
        const mediaType = getMediaType(uploadedFile.mimetype);
        onMediaSelect(uploadedFile.url, mediaType);
        setUploadedMedia(prev => [uploadedFile, ...prev]);
      } else {
        const errorData = await response.json();
        setError(errorData.error || 'Ошибка загрузки файла');
      }
    } catch (error) {
      setError('Произошла ошибка при загрузке файла');
      console.error('Upload error:', error);
    } finally {
      setIsUploading(false);
    }
  };

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      handleFileUpload(file);
    }
  };

  const handleDrag = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === "dragenter" || e.type === "dragover") {
      setDragActive(true);
    } else if (e.type === "dragleave") {
      setDragActive(false);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);

    const file = e.dataTransfer.files?.[0];
    if (file && (file.type.startsWith('image/') || file.type.startsWith('video/'))) {
      handleFileUpload(file);
    } else {
      setError('Пожалуйста, выберите изображение или видео файл');
    }
  };

  const openGallery = () => {
    setShowGallery(true);
    loadMedia();
  };

  const isFullMode = env.NEXT_PUBLIC_FUNNEL_BUILD_VARIANT !== BUILD_VARIANTS.FRONTEND;

  const getMediaIcon = () => {
    if (currentMediaType === 'video' || currentMediaType === 'gif') {
      return <Film className="h-4 w-4 text-muted-foreground" />;
    }
    return <ImageIcon className="h-4 w-4 text-muted-foreground" />;
  };

  const getMediaLabel = () => {
    if (currentMediaType === 'video') return 'Загруженное видео';
    if (currentMediaType === 'gif') return 'Загруженный GIF';
    return 'Загруженное изображение';
  };

  return (
    <div className="space-y-3">
      {/* Текущий медиа файл */}
      {currentMediaUrl && (
        <div className="relative">
          <div className="rounded-lg border border-border p-2 bg-muted/5">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                {getMediaIcon()}
                <span className="text-sm text-muted-foreground truncate">
                  {currentMediaUrl.startsWith('/api/images/') ? getMediaLabel() : currentMediaUrl}
                </span>
              </div>
              <Button
                variant="ghost"
                onClick={onMediaRemove}
                className="h-6 w-6 p-0 text-destructive hover:bg-destructive/10"
              >
                <X className="h-3 w-3" />
              </Button>
            </div>
          </div>
          {/* Превью */}
          <div className="mt-2 rounded-lg border border-border overflow-hidden bg-black">
            {currentMediaType === 'image' ? (
              <Image
                src={currentMediaUrl}
                alt="Preview"
                width={200}
                height={120}
                className="object-cover w-full h-auto max-h-[120px]"
                unoptimized
              />
            ) : (
              <video
                src={currentMediaUrl}
                autoPlay
                loop
                muted
                playsInline
                className="w-full h-auto max-h-[120px] object-cover"
              />
            )}
          </div>
        </div>
      )}

      {!currentMediaUrl && (
        <div className="space-y-3">
          {/* URL Input */}
          <div>
            <label className="block text-sm font-medium text-muted-foreground mb-1">
              Ссылка на медиа файл
            </label>
            <TextInput
              placeholder="https://example.com/video.mp4 или image.jpg"
              value=""
              onChange={(e) => {
                const url = e.target.value;
                // Определяем тип по расширению
                let type: MediaType = "image";
                if (url.match(/\.(mp4|mov|webm)$/i)) type = "video";
                else if (url.match(/\.gif$/i)) type = "gif";
                onMediaSelect(url, type);
              }}
            />
            <p className="text-xs text-muted-foreground mt-1">
              Поддерживаются: изображения (JPG, PNG, WebP), видео (MP4, MOV, WebM), GIF
            </p>
          </div>

          {/* Upload Section */}
          {isFullMode && (
            <>
              <div className="text-center text-sm text-muted-foreground">или</div>
              
              {/* Drag & Drop Zone */}
              <div
                className={`
                  relative border-2 border-dashed rounded-lg p-6 text-center transition-colors
                  ${dragActive 
                    ? 'border-primary bg-primary/5' 
                    : 'border-border hover:border-primary/50'
                  }
                  ${isUploading ? 'pointer-events-none opacity-50' : 'cursor-pointer'}
                `}
                onDragEnter={handleDrag}
                onDragLeave={handleDrag}
                onDragOver={handleDrag}
                onDrop={handleDrop}
                onClick={() => fileInputRef.current?.click()}
              >
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/*,video/*,.gif"
                  onChange={handleFileSelect}
                  className="hidden"
                />
                
                {isUploading ? (
                  <div className="flex flex-col items-center gap-2">
                    <Loader2 className="h-8 w-8 animate-spin text-primary" />
                    <p className="text-sm text-muted-foreground">Загрузка...</p>
                  </div>
                ) : (
                  <div className="flex flex-col items-center gap-2">
                    <div className="flex gap-2">
                      <Upload className="h-8 w-8 text-muted-foreground" />
                      <Film className="h-8 w-8 text-muted-foreground" />
                    </div>
                    <p className="text-sm text-muted-foreground">
                      Перетащите медиа файл сюда или нажмите для выбора
                    </p>
                    <p className="text-xs text-muted-foreground">
                      Изображения, видео (MP4, MOV, WebM), GIF. Максимум 10MB
                    </p>
                  </div>
                )}
              </div>

              {/* Gallery Button */}
              <Button
                variant="outline"
                onClick={openGallery}
                disabled={isUploading}
                className="w-full"
              >
                <ImageIcon className="h-4 w-4 mr-2" />
                Выбрать из загруженных
              </Button>
            </>
          )}
        </div>
      )}

      {/* Error Message */}
      {error && (
        <div className="text-sm text-destructive bg-destructive/10 border border-destructive/20 rounded p-2">
          {error}
        </div>
      )}

      {/* Gallery Modal */}
      {showGallery && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-background rounded-lg p-6 max-w-2xl max-h-[80vh] overflow-auto">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold">Выберите медиа файл</h3>
              <Button
                variant="ghost"
                onClick={() => setShowGallery(false)}
              >
                <X className="h-4 w-4" />
              </Button>
            </div>

            {isLoadingGallery ? (
              <div className="flex items-center justify-center py-8">
                <Loader2 className="h-6 w-6 animate-spin" />
              </div>
            ) : uploadedMedia.length > 0 ? (
              <div className="grid grid-cols-3 gap-3">
                {uploadedMedia.map((media, index) => {
                  const mediaType = getMediaType(media.mimetype);
                  return (
                    <div
                      key={media.filename || `media-${index}`}
                      className="relative aspect-square border border-border rounded cursor-pointer hover:bg-muted/50 overflow-hidden"
                      onClick={() => {
                        onMediaSelect(media.url, mediaType);
                        setShowGallery(false);
                      }}
                    >
                      {mediaType === 'image' ? (
                        <Image
                          src={media.url}
                          alt={media.originalName}
                          fill
                          className="object-cover"
                          unoptimized={media.url.startsWith('/api/images/')}
                        />
                      ) : (
                        <video
                          src={media.url}
                          muted
                          loop
                          playsInline
                          className="w-full h-full object-cover"
                          onMouseEnter={(e) => e.currentTarget.play()}
                          onMouseLeave={(e) => {
                            e.currentTarget.pause();
                            e.currentTarget.currentTime = 0;
                          }}
                        />
                      )}
                      <div className="absolute top-1 right-1 bg-black/75 text-white text-xs px-2 py-0.5 rounded z-10">
                        {mediaType === 'video' && '🎬'}
                        {mediaType === 'gif' && '🎞️'}
                        {mediaType === 'image' && '🖼️'}
                      </div>
                      <div className="absolute bottom-0 left-0 right-0 bg-black/75 text-white text-xs p-1 truncate z-10">
                        {media.originalName}
                      </div>
                    </div>
                  );
                })}
              </div>
            ) : (
              <div className="text-center py-8 text-muted-foreground">
                Пока нет загруженных файлов
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
