import { useQuery } from "@tanstack/react-query";
import { Media } from "@shared/schema";
import { Card, CardContent } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { AspectRatio } from "@/components/ui/aspect-ratio";
import { Skeleton } from "@/components/ui/skeleton";
import Lightbox from "yet-another-react-lightbox";
import "yet-another-react-lightbox/styles.css";
import { useState } from "react";

export default function GalleryPage() {
  const [isOpen, setIsOpen] = useState(false);
  const [selectedImageIndex, setSelectedImageIndex] = useState(0);

  const { data: media, isLoading } = useQuery<Media[]>({
    queryKey: ["/api/media"],
  });

  const photos = media?.filter(item => item.type === "image") || [];
  const videos = media?.filter(item => item.type === "video") || [];

  const LoadingGrid = ({ columns = 3 }: { columns?: number }) => (
    <div className={`grid md:grid-cols-${columns} gap-4`}>
      {[...Array(6)].map((_, i) => (
        <Card key={i}>
          <CardContent className="p-2">
            <Skeleton className="w-full aspect-video" />
          </CardContent>
        </Card>
      ))}
    </div>
  );

  // Helper function to get Vimeo embed URL
  const getVimeoEmbedUrl = (url: string) => {
    // If it's already an embed URL, return as is
    if (url.includes('player.vimeo.com')) return url;

    try {
      // Extract video ID from various Vimeo URL formats
      const patterns = [
        /vimeo\.com\/(\d+)/, // Regular URL
        /vimeo\.com\/showcase\/\d+\/video\/(\d+)/, // Showcase URL
        /vimeo\.com\/channels\/\w+\/(\d+)/, // Channels URL
        /vimeo\.com\/groups\/\w+\/videos\/(\d+)/, // Groups URL
      ];

      for (const pattern of patterns) {
        const matches = url.match(pattern);
        if (matches && matches[1]) {
          return `https://player.vimeo.com/video/${matches[1]}?h=&autoplay=0`;
        }
      }

      // If no pattern matches, return original URL
      console.warn('Unrecognized Vimeo URL format:', url);
      return url;
    } catch (error) {
      console.error('Error processing Vimeo URL:', error);
      return url;
    }
  };

  return (
    <div className="space-y-8">
      <h1 className="text-3xl font-bold text-center">Event Gallery</h1>

      <Tabs defaultValue="photos">
        <TabsList className="grid w-full max-w-md mx-auto grid-cols-2">
          <TabsTrigger value="photos">Photos</TabsTrigger>
          <TabsTrigger value="videos">Videos</TabsTrigger>
        </TabsList>

        <TabsContent value="photos" className="mt-6">
          {isLoading ? (
            <LoadingGrid columns={3} />
          ) : (
            <div className="grid md:grid-cols-3 gap-4">
              {photos.map((photo, index) => (
                <Card 
                  key={photo.id} 
                  className="cursor-pointer transition-transform hover:scale-105"
                  onClick={() => {
                    setSelectedImageIndex(index);
                    setIsOpen(true);
                  }}
                >
                  <CardContent className="p-2">
                    <AspectRatio ratio={16 / 9}>
                      <img
                        src={photo.url}
                        alt={photo.title}
                        className="rounded-md object-cover w-full h-full"
                      />
                    </AspectRatio>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
          <Lightbox
            open={isOpen}
            close={() => setIsOpen(false)}
            index={selectedImageIndex}
            slides={photos.map(photo => ({ src: photo.url }))}
          />
        </TabsContent>

        <TabsContent value="videos" className="mt-6">
          {isLoading ? (
            <LoadingGrid columns={2} />
          ) : (
            <div className="grid md:grid-cols-2 gap-6">
              {videos.map((video) => (
                <Card key={video.id}>
                  <CardContent className="p-2">
                    <AspectRatio ratio={16 / 9}>
                      <iframe
                        src={getVimeoEmbedUrl(video.url)}
                        title={video.title}
                        className="w-full h-full rounded-md"
                        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                        allowFullScreen
                      />
                    </AspectRatio>
                    <h3 className="mt-2 font-medium">{video.title}</h3>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </TabsContent>
      </Tabs>
    </div>
  );
}