"use client"

import { useState, useEffect } from 'react'
import { X, Download, ZoomIn, ZoomOut } from 'lucide-react'
import { Button } from '@/components/ui/button'

interface ImageLightboxProps {
  imageUrl: string
  fileName: string
  fileSize?: number
  isOpen: boolean
  onClose: () => void
}

export function ImageLightbox({ imageUrl, fileName, fileSize, isOpen, onClose }: ImageLightboxProps) {
  const [zoom, setZoom] = useState(1)
  const [position, setPosition] = useState({ x: 0, y: 0 })
  const [isDragging, setIsDragging] = useState(false)
  const [dragStart, setDragStart] = useState({ x: 0, y: 0 })

  // Сброс состояния при открытии/закрытии
  useEffect(() => {
    if (isOpen) {
      setZoom(1)
      setPosition({ x: 0, y: 0 })
    }
  }, [isOpen])

  // Закрытие по ESC
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && isOpen) {
        onClose()
      }
    }

    if (isOpen) {
      document.addEventListener('keydown', handleKeyDown)
      document.body.style.overflow = 'hidden'
    }

    return () => {
      document.removeEventListener('keydown', handleKeyDown)
      document.body.style.overflow = 'unset'
    }
  }, [isOpen, onClose])

  const formatFileSize = (bytes?: number) => {
    if (!bytes) return ''
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
  }

  const handleDownload = async () => {
    console.log('🔽 Скачиваем изображение из lightbox:', fileName)
    
    try {
      const downloadUrl = `/api/download-file?url=${encodeURIComponent(imageUrl)}&filename=${encodeURIComponent(fileName)}`
      
      const link = document.createElement('a')
      link.href = downloadUrl
      link.download = fileName || 'image'
      link.style.display = 'none'
      
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      console.log('✅ Скачивание запущено из lightbox')
    } catch (error) {
      console.error('❌ Ошибка скачивания из lightbox:', error)
      window.open(imageUrl, '_blank')
    }
  }

  const handleZoomIn = () => {
    setZoom(prev => Math.min(prev * 1.5, 5))
  }

  const handleZoomOut = () => {
    setZoom(prev => Math.max(prev / 1.5, 0.5))
  }

  const handleMouseDown = (e: React.MouseEvent) => {
    if (zoom > 1) {
      setIsDragging(true)
      setDragStart({
        x: e.clientX - position.x,
        y: e.clientY - position.y
      })
    }
  }

  const handleMouseMove = (e: React.MouseEvent) => {
    if (isDragging && zoom > 1) {
      setPosition({
        x: e.clientX - dragStart.x,
        y: e.clientY - dragStart.y
      })
    }
  }

  const handleMouseUp = () => {
    setIsDragging(false)
  }

  if (!isOpen) return null

  return (
    <div className="fixed inset-0 z-50 bg-black/90 flex items-center justify-center">
      {/* Фон для закрытия */}
      <div 
        className="absolute inset-0" 
        onClick={onClose}
      />
      
      {/* Панель управления */}
      <div className="absolute top-4 right-4 flex items-center space-x-2 z-10">
        <Button
          onClick={handleZoomOut}
          variant="outline"
          size="icon"
          className="bg-black/50 border-white/20 text-white hover:bg-white/10"
        >
          <ZoomOut className="h-4 w-4" />
        </Button>
        
        <Button
          onClick={handleZoomIn}
          variant="outline"
          size="icon"
          className="bg-black/50 border-white/20 text-white hover:bg-white/10"
        >
          <ZoomIn className="h-4 w-4" />
        </Button>
        
        <Button
          onClick={handleDownload}
          variant="outline"
          size="icon"
          className="bg-black/50 border-white/20 text-white hover:bg-white/10"
        >
          <Download className="h-4 w-4" />
        </Button>
        
        <Button
          onClick={onClose}
          variant="outline"
          size="icon"
          className="bg-black/50 border-white/20 text-white hover:bg-white/10"
        >
          <X className="h-4 w-4" />
        </Button>
      </div>

      {/* Информация о файле */}
      <div className="absolute top-4 left-4 z-10">
        <div className="bg-black/50 backdrop-blur rounded-lg px-3 py-2">
          <p className="text-white font-medium text-sm">{fileName}</p>
          {fileSize && (
            <p className="text-white/60 text-xs">{formatFileSize(fileSize)}</p>
          )}
          <p className="text-white/60 text-xs">Zoom: {Math.round(zoom * 100)}%</p>
        </div>
      </div>

      {/* Изображение */}
      <div className="relative max-w-full max-h-full overflow-hidden">
                 {/* eslint-disable-next-line @next/next/no-img-element */}
         <img
           src={imageUrl}
           alt={fileName}
           className={`max-w-full max-h-full object-contain transition-transform ${
             zoom > 1 ? 'cursor-move' : 'cursor-zoom-in'
           }`}
          style={{
            transform: `scale(${zoom}) translate(${position.x / zoom}px, ${position.y / zoom}px)`,
          }}
          onMouseDown={handleMouseDown}
          onMouseMove={handleMouseMove}
          onMouseUp={handleMouseUp}
          onMouseLeave={handleMouseUp}
          onClick={(e) => {
            e.stopPropagation()
            if (zoom === 1) {
              handleZoomIn()
            }
          }}
          draggable={false}
        />
      </div>

      {/* Инструкция */}
      <div className="absolute bottom-4 left-1/2 transform -translate-x-1/2 z-10">
        <div className="bg-black/50 backdrop-blur rounded-lg px-4 py-2">
          <p className="text-white/80 text-xs text-center">
            ESC - закрыть • Клик - увеличить • Перетаскивание при зуме
          </p>
        </div>
      </div>
    </div>
  )
} 