"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, Image as ImageIcon, Loader2 } from 'lucide-react';

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

interface ImageUploadProps {
  currentValue?: string;
  onImageSelect: (url: string) => void;
  onImageRemove: () => void;
  funnelId?: string;
}

export function ImageUpload({ 
  currentValue, 
  onImageSelect, 
  onImageRemove, 
  funnelId 
}: ImageUploadProps) {
  const [isUploading, setIsUploading] = useState(false);
  const [dragActive, setDragActive] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [uploadedImages, setUploadedImages] = useState<UploadedImage[]>([]);
  const [showGallery, setShowGallery] = useState(false);
  const [isLoadingGallery, setIsLoadingGallery] = useState(false);
  
  const fileInputRef = useRef<HTMLInputElement>(null);

  const loadImages = useCallback(async () => {
    if (process.env.NEXT_PUBLIC_FUNNEL_BUILD_VARIANT === 'frontend') {
      return; // В frontend режиме загрузка недоступна
    }

    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();
        setUploadedImages(data.images);
      } else {
        console.error('Failed to load images');
      }
    } catch (error) {
      console.error('Error loading images:', 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 uploadedImage = await response.json();
        onImageSelect(uploadedImage.url);
        setUploadedImages(prev => [uploadedImage, ...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/')) {
      handleFileUpload(file);
    } else {
      setError('Пожалуйста, выберите файл изображения');
    }
  };

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

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

  return (
    <div className="space-y-3">
      {/* Текущее изображение */}
      {currentValue && (
        <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">
                <ImageIcon className="h-4 w-4 text-muted-foreground" />
                <span className="text-sm text-muted-foreground truncate">
                  {currentValue.startsWith('/api/images/') ? 'Загруженное изображение' : currentValue}
                </span>
              </div>
              <Button
                variant="ghost"
                onClick={onImageRemove}
                className="h-6 w-6 p-0 text-destructive hover:bg-destructive/10"
              >
                <X className="h-3 w-3" />
              </Button>
            </div>
          </div>
        </div>
      )}

      {!currentValue && (
        <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/image.jpg"
              value=""
              onChange={(e) => onImageSelect(e.target.value)}
            />
          </div>

          {/* Upload Section (только в full режиме) */}
          {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/*"
                  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">
                    <Upload className="h-8 w-8 text-muted-foreground" />
                    <p className="text-sm text-muted-foreground">
                      Перетащите изображение сюда или нажмите для выбора
                    </p>
                    <p className="text-xs text-muted-foreground">
                      PNG, JPG, GIF, WebP до 5MB
                    </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>
            ) : uploadedImages.length > 0 ? (
              <div className="grid grid-cols-3 gap-3">
                {uploadedImages.map((image, index) => (
                  <div
                    key={image.filename || `image-${index}`}
                    className="relative aspect-square border border-border rounded cursor-pointer hover:bg-muted/50 overflow-hidden"
                    onClick={() => {
                      onImageSelect(image.url);
                      setShowGallery(false);
                    }}
                  >
                    <Image
                      src={image.url}
                      alt={image.originalName}
                      fill
                      className="object-cover"
                      unoptimized={image.url.startsWith('/api/images/')}
                      onError={(e) => {
                        console.error('Image load error:', image.url, e);
                      }}
                      onLoad={() => {
                        console.log('Image loaded successfully:', image.url);
                      }}
                    />
                    <div className="absolute bottom-0 left-0 right-0 bg-black/75 text-white text-xs p-1 truncate z-10">
                      {image.originalName}
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-8 text-muted-foreground">
                Пока нет загруженных изображений
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
