'use client';

import * as React from 'react';
import { createPortal } from 'react-dom';
import { ChevronLeft, ChevronRight, X, ZoomIn } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { MediaImageSkeleton } from '@/components/ui/media-image-skeleton';
import { cn } from '@/lib/utils';

interface DocumentFullscreenViewerProps {
  images: { storageKey: string; url: string }[];
  initialIndex?: number;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function DocumentFullscreenViewer({ images, initialIndex = 0, open, onOpenChange }: DocumentFullscreenViewerProps) {
  const [index, setIndex] = React.useState(initialIndex);
  const [mounted, setMounted] = React.useState(false);

  React.useEffect(() => {
    setMounted(true);
  }, []);

  React.useEffect(() => {
    if (open) setIndex(initialIndex);
  }, [initialIndex, open]);

  React.useEffect(() => {
    if (!open) return;
    function onKeyDown(event: KeyboardEvent) {
      if (event.key === 'Escape') onOpenChange(false);
      if (event.key === 'ArrowLeft') setIndex((current) => Math.max(0, current - 1));
      if (event.key === 'ArrowRight') setIndex((current) => Math.min(images.length - 1, current + 1));
    }
    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [images.length, onOpenChange, open]);

  React.useEffect(() => {
    if (!open) return;
    const previous = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = previous;
    };
  }, [open]);

  if (!open || images.length === 0 || !mounted) return null;

  const current = images[index];

  return createPortal(
    <div className="fixed inset-0 z-[250] flex flex-col bg-[#0f1117]/96">
      <div className="flex items-center justify-between px-4 py-3 text-white">
        <div className="min-w-0">
          <p className="truncate text-sm font-medium">Фото документа</p>
          <p className="text-xs text-white/60">
            {index + 1} из {images.length}
          </p>
        </div>
        <Button
          type="button"
          size="icon"
          variant="ghost"
          className="text-white hover:bg-white/10"
          aria-label="Закрыть"
          onClick={() => onOpenChange(false)}
        >
          <X className="h-5 w-5" />
        </Button>
      </div>

      <div className="relative flex flex-1 items-center justify-center px-3 pb-4">
        {images.length > 1 ? (
          <Button
            type="button"
            size="icon"
            variant="ghost"
            className={cn(
              'absolute left-3 z-10 h-11 w-11 rounded-full text-white hover:bg-white/10',
              index <= 0 && 'pointer-events-none opacity-30'
            )}
            aria-label="Предыдущее фото"
            onClick={() => setIndex((value) => Math.max(0, value - 1))}
          >
            <ChevronLeft className="h-6 w-6" />
          </Button>
        ) : null}

        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img
          src={current.url}
          alt="Фото документа"
          className="max-h-[calc(100vh-140px)] max-w-full object-contain"
        />

        {images.length > 1 ? (
          <Button
            type="button"
            size="icon"
            variant="ghost"
            className={cn(
              'absolute right-3 z-10 h-11 w-11 rounded-full text-white hover:bg-white/10',
              index >= images.length - 1 && 'pointer-events-none opacity-30'
            )}
            aria-label="Следующее фото"
            onClick={() => setIndex((value) => Math.min(images.length - 1, value + 1))}
          >
            <ChevronRight className="h-6 w-6" />
          </Button>
        ) : null}
      </div>

      {images.length > 1 ? (
        <div className="flex gap-2 overflow-x-auto px-4 pb-4">
          {images.map((image, imageIndex) => (
            <button
              key={image.storageKey}
              type="button"
              className={cn(
                'h-14 w-14 shrink-0 overflow-hidden rounded-lg border-2',
                imageIndex === index ? 'border-[#3390ec]' : 'border-transparent opacity-70'
              )}
              onClick={() => setIndex(imageIndex)}
            >
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src={image.url} alt="" className="h-full w-full object-cover" />
            </button>
          ))}
        </div>
      ) : null}
    </div>,
    document.body
  );
}

interface DocumentPhotoThumbnailProps {
  url?: string;
  loading?: boolean;
  className?: string;
  onClick?: () => void;
}

export function DocumentPhotoThumbnail({ url, loading, className, onClick }: DocumentPhotoThumbnailProps) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={cn(
        'group relative aspect-[4/3] overflow-hidden rounded-2xl border border-[#eceef4] bg-[#f4f5f8] transition hover:border-[#20212b]',
        className
      )}
    >
      {loading ? <MediaImageSkeleton className="h-full w-full min-h-0" rounded="none" /> : null}
      {!loading && url ? (
        <>
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img src={url} alt="Фото документа" className="h-full w-full object-cover" />
          <div className="absolute inset-0 flex items-center justify-center bg-black/0 transition group-hover:bg-black/20">
            <ZoomIn className="h-6 w-6 text-white opacity-0 transition group-hover:opacity-100" />
          </div>
        </>
      ) : null}
      {!loading && !url ? <div className="flex h-full items-center justify-center text-xs text-[#667085]">Нет превью</div> : null}
    </button>
  );
}
