import { useRef, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Trash2, Star, Upload, ChevronLeft, ChevronRight, X } from 'lucide-react'
import { api } from '@/lib/api'
import { Button } from '@/components/Button'

interface ImageDto { id: string; url: string; isMain: boolean; sortOrder: number }

interface Props { productId: string }

export function ProductImageGallery({ productId }: Props) {
  const qc = useQueryClient()
  const fileInput = useRef<HTMLInputElement>(null)
  const [lightboxIdx, setLightboxIdx] = useState<number | null>(null)

  const url = `/api/catalog/products/${productId}/images`

  const list = useQuery({
    queryKey: [url],
    queryFn: async () => (await api.get<ImageDto[]>(url)).data,
  })

  const upload = useMutation({
    mutationFn: async (file: File) => {
      const fd = new FormData()
      fd.append('file', file)
      return (await api.post<ImageDto>(url, fd, { headers: { 'Content-Type': 'multipart/form-data' } })).data
    },
    onSuccess: () => qc.invalidateQueries({ queryKey: [url] }),
  })

  const remove = useMutation({
    mutationFn: async (id: string) => { await api.delete(`${url}/${id}`) },
    onSuccess: () => qc.invalidateQueries({ queryKey: [url] }),
  })

  const setMain = useMutation({
    mutationFn: async (id: string) => { await api.post(`${url}/${id}/main`) },
    onSuccess: () => qc.invalidateQueries({ queryKey: [url] }),
  })

  const images = list.data ?? []

  const onFiles = async (files: FileList | null) => {
    if (!files) return
    for (const f of Array.from(files)) {
      await upload.mutateAsync(f)
    }
    if (fileInput.current) fileInput.current.value = ''
  }

  const closeLb = () => setLightboxIdx(null)
  const lbPrev = () => setLightboxIdx((i) => (i === null ? null : (i - 1 + images.length) % images.length))
  const lbNext = () => setLightboxIdx((i) => (i === null ? null : (i + 1) % images.length))

  return (
    <div className="space-y-3">
      <div className="flex items-center gap-2">
        <input
          ref={fileInput}
          type="file"
          accept="image/jpeg,image/png,image/webp,image/gif"
          multiple
          hidden
          onChange={(e) => onFiles(e.target.files)}
        />
        <Button type="button" variant="secondary" size="sm" onClick={() => fileInput.current?.click()} disabled={upload.isPending}>
          <Upload className="w-3.5 h-3.5" /> {upload.isPending ? 'Загружаю…' : 'Загрузить'}
        </Button>
        <span className="text-xs text-slate-500">JPG/PNG/WEBP/GIF, до 10 МБ</span>
      </div>

      {images.length === 0 ? (
        <div className="text-sm text-slate-400">Изображений нет.</div>
      ) : (
        <div className="grid grid-cols-4 sm:grid-cols-6 md:grid-cols-8 gap-2">
          {images.map((img, i) => (
            <div key={img.id} className="relative group aspect-square rounded-lg overflow-hidden border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-900">
              <button
                type="button"
                onClick={() => setLightboxIdx(i)}
                className="w-full h-full"
                title="Увеличить"
              >
                <img
                  src={img.url}
                  alt=""
                  className="w-full h-full object-cover"
                  loading="lazy"
                />
              </button>
              {img.isMain && (
                <div className="absolute top-1 left-1 bg-amber-400 text-amber-900 text-[10px] px-1 rounded font-semibold">основное</div>
              )}
              <div className="absolute bottom-1 right-1 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                {!img.isMain && (
                  <button
                    type="button"
                    onClick={(e) => { e.stopPropagation(); setMain.mutate(img.id) }}
                    className="p-1 rounded bg-white/90 hover:bg-white text-amber-600"
                    title="Сделать основным"
                  >
                    <Star className="w-3.5 h-3.5" />
                  </button>
                )}
                <button
                  type="button"
                  onClick={(e) => { e.stopPropagation(); if (confirm('Удалить это изображение?')) remove.mutate(img.id) }}
                  className="p-1 rounded bg-white/90 hover:bg-white text-red-600"
                  title="Удалить"
                >
                  <Trash2 className="w-3.5 h-3.5" />
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {lightboxIdx !== null && images[lightboxIdx] && (
        <div
          className="fixed inset-0 z-50 bg-black/80 flex items-center justify-center"
          onClick={closeLb}
        >
          <button
            type="button"
            onClick={(e) => { e.stopPropagation(); closeLb() }}
            className="absolute top-4 right-4 text-white hover:text-slate-300"
            title="Закрыть"
          >
            <X className="w-6 h-6" />
          </button>
          {images.length > 1 && (
            <>
              <button
                type="button"
                onClick={(e) => { e.stopPropagation(); lbPrev() }}
                className="absolute left-4 text-white hover:text-slate-300 p-2"
              >
                <ChevronLeft className="w-8 h-8" />
              </button>
              <button
                type="button"
                onClick={(e) => { e.stopPropagation(); lbNext() }}
                className="absolute right-4 text-white hover:text-slate-300 p-2"
              >
                <ChevronRight className="w-8 h-8" />
              </button>
            </>
          )}
          <img
            src={images[lightboxIdx].url}
            alt=""
            className="max-w-[90vw] max-h-[90vh] object-contain"
            onClick={(e) => e.stopPropagation()}
          />
          <div className="absolute bottom-4 text-white/80 text-sm">
            {lightboxIdx + 1} / {images.length}
          </div>
        </div>
      )}
    </div>
  )
}
