import { useState } from "react";
import {
  Dialog,
  DialogContent,
} from "@/components/ui/dialog";
import { Play, X, Image as ImageIcon } from "lucide-react";
import { Button } from "@/components/ui/button";

interface MediaGalleryProps {
  media: string | null;
  telegramFileUrl?: string;
}

export function MediaGallery({ media, telegramFileUrl }: MediaGalleryProps) {
  const [lightboxOpen, setLightboxOpen] = useState(false);
  const [lightboxSrc, setLightboxSrc] = useState("");
  const [lightboxType, setLightboxType] = useState<"image" | "video">("image");

  if (!media) return null;

  const mediaItems = media.split(",").filter(Boolean);

  if (mediaItems.length === 0) return null;

  const getMediaType = (url: string): "image" | "video" => {
    if (url.includes("video") || url.endsWith(".mp4") || url.endsWith(".mov")) {
      return "video";
    }
    return "image";
  };

  const getMediaUrl = (fileId: string) => {
    if (telegramFileUrl) {
      return `${telegramFileUrl}/${fileId}`;
    }
    return `/api/media/${fileId}`;
  };

  const openLightbox = (url: string, type: "image" | "video") => {
    setLightboxSrc(url);
    setLightboxType(type);
    setLightboxOpen(true);
  };

  return (
    <>
      <div className="grid grid-cols-3 gap-2">
        {mediaItems.map((item, index) => {
          const type = getMediaType(item);
          const url = getMediaUrl(item.trim());

          return (
            <button
              key={index}
              onClick={() => openLightbox(url, type)}
              className="relative aspect-square rounded-md overflow-hidden bg-muted hover-elevate cursor-pointer group"
              data-testid={`media-item-${index}`}
            >
              {type === "video" ? (
                <div className="absolute inset-0 flex items-center justify-center bg-muted">
                  <Play className="h-8 w-8 text-muted-foreground" />
                </div>
              ) : (
                <img
                  src={url}
                  alt={`Медиафайл ${index + 1}`}
                  className="h-full w-full object-cover"
                  onError={(e) => {
                    const target = e.target as HTMLImageElement;
                    target.style.display = "none";
                    target.parentElement!.innerHTML = `
                      <div class="absolute inset-0 flex items-center justify-center bg-muted">
                        <svg class="h-6 w-6 text-muted-foreground" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                        </svg>
                      </div>
                    `;
                  }}
                />
              )}
              <div className="absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors" />
            </button>
          );
        })}
      </div>

      <Dialog open={lightboxOpen} onOpenChange={setLightboxOpen}>
        <DialogContent className="max-w-4xl p-0 bg-transparent border-none">
          <Button
            variant="ghost"
            size="icon"
            className="absolute right-2 top-2 z-50 bg-background/80 backdrop-blur"
            onClick={() => setLightboxOpen(false)}
          >
            <X className="h-4 w-4" />
          </Button>
          <div className="relative rounded-lg overflow-hidden bg-background">
            {lightboxType === "video" ? (
              <video
                src={lightboxSrc}
                controls
                autoPlay
                className="max-h-[80vh] w-full"
              />
            ) : (
              <img
                src={lightboxSrc}
                alt="Медиафайл"
                className="max-h-[80vh] w-full object-contain"
              />
            )}
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}
