import { useQuery } from '@tanstack/react-query';
import { Link } from 'wouter';
import { ArrowLeft, ChevronLeft, ChevronRight, Menu, X } from 'lucide-react';
import VideoCard from '@/components/video-card';
import BunnyVideoModal from '@/components/bunny-video-modal';
import { Button } from '@/components/ui/button';
import { useState } from 'react';
import type { Video } from '@shared/schema';

export default function FolxStadlPage() {
  const [selectedVideo, setSelectedVideo] = useState<Video | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const itemsPerPage = 10;

  const { data, isLoading } = useQuery<{videos: Video[], total: number}>({
    queryKey: ['/api/videos?limit=200'],
    select: (response) => response || { videos: [], total: 0 }
  });

  const videos = data?.videos || [];

  // Filter only FOLX STADL S4 videos (including both formats)
  const folxStadlVideos = videos.filter(video => 
    video.title.includes("FOLX STADL S4")
  );

  // Pagination logic
  const totalPages = Math.ceil(folxStadlVideos.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const currentVideos = folxStadlVideos.slice(startIndex, endIndex);

  const handleVideoClick = (video: Video) => {
    setSelectedVideo(video);
    setIsModalOpen(true);
  };

  const handleCloseModal = () => {
    setIsModalOpen(false);
    setSelectedVideo(null);
  };

  if (isLoading) {
    return (
      <div className="min-h-screen bg-bunny-dark flex items-center justify-center">
        <div className="text-white text-xl">Loading...</div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-bunny-dark text-white">
      {/* Header */}
      <div className="border-b border-white/10 bg-black/20 backdrop-blur-sm sticky top-0 z-40">
        <div className="max-w-7xl mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            {/* Left side - Back button and title */}
            <div className="flex items-center gap-4">
              <Link href="/">
                <button className="flex items-center gap-2 text-bunny-light hover:text-white transition-colors">
                  <ArrowLeft className="w-5 h-5" />
                  <span className="hidden sm:inline">Zurück</span>
                </button>
              </Link>
              <h1 className="text-2xl sm:text-3xl font-bold text-white uppercase tracking-wide">FOLX STADL</h1>
            </div>

            {/* Right side - Mobile menu button */}
            <div className="md:hidden">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
                className="text-white hover:bg-white/10"
                data-testid="button-mobile-menu-folx"
              >
                {isMobileMenuOpen ? <X className="w-6 h-6" /> : <Menu className="w-6 h-6" />}
              </Button>
            </div>

            {/* Desktop navigation */}
            <div className="hidden md:flex items-center space-x-6">
              <nav className="flex space-x-6">
                <Link href="/" className="text-bunny-light hover:text-white transition-colors">
                  Home
                </Link>
              </nav>
            </div>
          </div>

          {/* Mobile menu dropdown */}
          {isMobileMenuOpen && (
            <div className="md:hidden mt-4 pt-4 border-t border-white/10">
              <nav className="flex flex-col space-y-3">
                <Link 
                  href="/" 
                  className="text-bunny-light hover:text-white transition-colors py-2"
                  onClick={() => setIsMobileMenuOpen(false)}
                >
                  Home
                </Link>
                <div className="text-bunny-muted py-2 border-t border-white/5">
                  FOLX STADL
                </div>
              </nav>
            </div>
          )}
        </div>
      </div>

      {/* Main Content */}
      <div className="max-w-7xl mx-auto px-4 py-8">

        {/* Video List with Descriptions */}
        <div className="space-y-6">
          {currentVideos.map((video, index) => (
            <div key={video.id} className="bg-black/20 backdrop-blur-sm rounded-lg p-4">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                {/* Video Card */}
                <div className="md:col-span-1">
                  <VideoCard
                    video={video}
                    onClick={handleVideoClick}
                    className="w-full hover:scale-102 transition-all duration-300 rounded-lg overflow-hidden"
                    hideOverlay={true}
                  />
                </div>
                
                {/* Video Description */}
                <div className="md:col-span-2 space-y-3">
                  <h3 className="text-xl font-bold text-white">{video.title}</h3>
                  <p className="text-bunny-light text-sm leading-relaxed">
                    {video.description || "Keine Beschreibung für diese Sendung verfügbar."}
                  </p>
                  <div className="flex items-center gap-4 text-xs text-bunny-muted">
                    <span>{Math.floor(video.duration / 60)}:{(video.duration % 60).toString().padStart(2, '0')} min</span>
                    <span>{video.views} Aufrufe</span>
                  </div>
                </div>
              </div>
            </div>
          ))}

          {folxStadlVideos.length === 0 && (
            <div className="text-center py-16">
              <p className="text-bunny-muted text-lg">Keine FOLX STADL Videos gefunden</p>
            </div>
          )}
        </div>

        {/* Bottom Pagination */}
        {totalPages > 1 && (
          <div className="mt-8 flex justify-center gap-2">
            <Button
              variant="outline"
              onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
              disabled={currentPage === 1}
              className="border-white/20 text-white hover:bg-white/10"
            >
              <ChevronLeft className="w-4 h-4" />
              Vorherige
            </Button>
            
            <div className="flex gap-1">
              {Array.from({ length: Math.min(totalPages, 5) }, (_, i) => {
                let pageNum;
                if (totalPages <= 5) {
                  pageNum = i + 1;
                } else if (currentPage <= 3) {
                  pageNum = i + 1;
                } else if (currentPage >= totalPages - 2) {
                  pageNum = totalPages - 4 + i;
                } else {
                  pageNum = currentPage - 2 + i;
                }
                
                return (
                  <Button
                    key={pageNum}
                    variant={currentPage === pageNum ? "default" : "outline"}
                    size="sm"
                    onClick={() => setCurrentPage(pageNum)}
                    className={currentPage === pageNum 
                      ? "bg-gradient-to-r from-cyan-400 to-purple-500 text-white" 
                      : "border-white/20 text-white hover:bg-white/10"
                    }
                  >
                    {pageNum}
                  </Button>
                );
              })}
            </div>

            <Button
              variant="outline"
              onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
              disabled={currentPage === totalPages}
              className="border-white/20 text-white hover:bg-white/10"
            >
              Nächste
              <ChevronRight className="w-4 h-4" />
            </Button>
          </div>
        )}

      </div>

      {/* Video Modal */}
      {selectedVideo && (
        <BunnyVideoModal
          video={selectedVideo}
          isOpen={isModalOpen}
          onClose={handleCloseModal}
          videos={folxStadlVideos}
          onVideoChange={setSelectedVideo}
        />
      )}
    </div>
  );
}