"use client";

import { Suspense } from "react";
import { useSearchParams } from "next/navigation";
import useSWR from "swr";
import { fetcher } from "@/lib/fetcher";
import { TourCard } from "@/components/tour-card";
import { FilterSidebar } from "@/components/filter-sidebar";
import { Button } from "@/components/ui/button";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Loader2, ChevronLeft, ChevronRight } from "lucide-react";

interface Tour {
  id: string;
  title: string;
  slug: string;
  description: string;
  city: string;
  durationMin: number | null;
  priceCents: number | null;
  tags: string[];
  avgRating: number | null;
  reviewCount: number;
  image: string | null;
  guide: {
    id: string;
    name: string | null;
    avatarPath: string | null;
  };
  createdAt: Date;
}

interface Pagination {
  page: number;
  limit: number;
  totalCount: number;
  totalPages: number;
  hasNextPage: boolean;
  hasPreviousPage: boolean;
}

interface ToursResponse {
  tours: Tour[];
  pagination: Pagination;
}

function FilterSidebarSkeleton() {
  return <div className="h-96 bg-muted animate-pulse rounded-lg" />;
}

export function ToursContent() {
  const searchParams = useSearchParams();
  
  // Use SWR for data fetching with caching
  const { data, error, isLoading } = useSWR<ToursResponse>(
    `/api/tours/public?${searchParams.toString()}`,
    fetcher,
    {
      revalidateOnFocus: false,
      dedupingInterval: 30000, // Dedupe requests within 30 seconds
      keepPreviousData: true, // Keep previous data while fetching new data
    }
  );

  const tours = data?.tours || [];
  const pagination = data?.pagination || null;

  const handlePageChange = (newPage: number) => {
    const params = new URLSearchParams(searchParams.toString());
    params.set("page", newPage.toString());
    window.location.href = `/tours?${params.toString()}`;
  };

  if (isLoading && !data) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
          <div className="lg:col-span-1">
            <Suspense fallback={<FilterSidebarSkeleton />}>
              <FilterSidebar />
            </Suspense>
          </div>
          <div className="lg:col-span-3">
            <div className="flex items-center justify-center py-12">
              <Loader2 className="h-8 w-8 animate-spin text-primary" />
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="container mx-auto px-4 py-8">
        <Alert variant="destructive">
          <AlertDescription>Failed to load tours. Please try again later.</AlertDescription>
        </Alert>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
        {/* Filter Sidebar */}
        <div className="lg:col-span-1">
          <Suspense fallback={<FilterSidebarSkeleton />}>
            <FilterSidebar />
          </Suspense>
        </div>

        {/* Tours Grid */}
        <div className="lg:col-span-3">
          {/* Results count */}
          {pagination && (
            <div className="mb-6 text-sm text-muted-foreground">
              Showing {tours.length} of {pagination.totalCount} tours
            </div>
          )}

          {/* Tours Grid */}
          {tours.length === 0 ? (
            <div className="text-center py-12">
              <p className="text-lg text-muted-foreground mb-4">
                No tours found matching your criteria
              </p>
              <Button
                variant="outline"
                onClick={() => (window.location.href = "/tours")}
              >
                Clear Filters
              </Button>
            </div>
          ) : (
            <>
              <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6 mb-8">
                {tours.map((tour) => (
                  <TourCard
                    key={tour.id}
                    id={tour.id}
                    title={tour.title}
                    slug={tour.slug}
                    description={tour.description}
                    city={tour.city}
                    durationMin={tour.durationMin}
                    priceCents={tour.priceCents}
                    tags={tour.tags}
                    avgRating={tour.avgRating}
                    reviewCount={tour.reviewCount}
                    imageUrl={tour.image}
                    guideName={tour.guide.name || "Unknown Guide"}
                  />
                ))}
              </div>

              {/* Pagination */}
              {pagination && pagination.totalPages > 1 && (
                <div className="flex items-center justify-center gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handlePageChange(pagination.page - 1)}
                    disabled={!pagination.hasPreviousPage}
                  >
                    <ChevronLeft className="h-4 w-4 mr-1" />
                    Previous
                  </Button>

                  <div className="flex items-center gap-1">
                    {Array.from({ length: pagination.totalPages }, (_, i) => i + 1)
                      .filter((page) => {
                        const current = pagination.page;
                        return (
                          page === 1 ||
                          page === pagination.totalPages ||
                          (page >= current - 1 && page <= current + 1)
                        );
                      })
                      .map((page, idx, arr) => {
                        const showEllipsis =
                          idx > 0 && arr[idx - 1] !== page - 1;
                        return (
                          <div key={page} className="flex items-center">
                            {showEllipsis && (
                              <span className="px-2 text-muted-foreground">
                                ...
                              </span>
                            )}
                            <Button
                              variant={
                                page === pagination.page ? "default" : "outline"
                              }
                              size="sm"
                              onClick={() => handlePageChange(page)}
                            >
                              {page}
                            </Button>
                          </div>
                        );
                      })}
                  </div>

                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handlePageChange(pagination.page + 1)}
                    disabled={!pagination.hasNextPage}
                  >
                    Next
                    <ChevronRight className="h-4 w-4 ml-1" />
                  </Button>
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}
