import { Suspense } from "react";
import Link from "next/link";
import { GuideCard } from "@/components/guides/guide-card";
import { LocalizedText } from "@/components/localized-text";
import { Button } from "@/components/ui/button";
import {
  Pagination,
  PaginationContent,
  PaginationItem,
} from "@/components/ui/pagination";
import {
  emptyWebsiteGuidesPagination,
  fetchWebsiteGuides,
  type WebsiteGuidesPagination,
} from "@/lib/website-guides";
import { Search } from "lucide-react";

export const revalidate = 60;

interface GuidesPageProps {
  searchParams: Promise<{
    search?: string;
    page?: string;
  }>;
}

function createPageHref(
  params: Awaited<GuidesPageProps["searchParams"]>,
  page: number,
) {
  const nextParams = new URLSearchParams();

  Object.entries(params).forEach(([key, value]) => {
    if (!value || key === "page") return;
    nextParams.set(key, value);
  });

  if (page > 1) {
    nextParams.set("page", String(page));
  }

  const queryString = nextParams.toString();
  return queryString ? `/guides?${queryString}` : "/guides";
}

function getVisiblePages(currentPage: number, totalPages: number) {
  const start = Math.max(1, currentPage - 2);
  const end = Math.min(totalPages, start + 4);
  const adjustedStart = Math.max(1, end - 4);

  return Array.from(
    { length: end - adjustedStart + 1 },
    (_, index) => adjustedStart + index,
  );
}

function GuidesPagination({
  pagination,
  params,
}: {
  pagination: WebsiteGuidesPagination;
  params: Awaited<GuidesPageProps["searchParams"]>;
}) {
  const totalPages =
    pagination.last_page ||
    Math.max(1, Math.ceil(pagination.total / pagination.per_page));

  if (totalPages <= 1) return null;

  const currentPage = pagination.current_page;
  const pages = getVisiblePages(currentPage, totalPages);

  return (
    <div className="mt-8 flex flex-col gap-4 border-t border-border/50 pt-6 text-sm text-muted-foreground sm:flex-row sm:items-center sm:justify-between">
      <p>
        Showing{" "}
        <span className="font-bold text-foreground">
          {pagination.from || 0}
        </span>{" "}
        -{" "}
        <span className="font-bold text-foreground">{pagination.to || 0}</span>{" "}
        of <span className="font-bold text-foreground">{pagination.total}</span>{" "}
        guides
      </p>

      <Pagination className="mx-0 w-auto justify-start sm:justify-end">
        <PaginationContent>
          <PaginationItem>
            <Button
              asChild={currentPage > 1}
              variant="outline"
              className="h-10 rounded-full"
              disabled={currentPage <= 1}
            >
              {currentPage > 1 ? (
                <Link href={createPageHref(params, currentPage - 1)}>
                  Previous
                </Link>
              ) : (
                <span>Previous</span>
              )}
            </Button>
          </PaginationItem>

          {pages.map((page) => (
            <PaginationItem key={page}>
              <Button
                asChild
                variant={page === currentPage ? "default" : "ghost"}
                size="icon"
                className="h-10 w-10 rounded-full"
              >
                <Link href={createPageHref(params, page)}>{page}</Link>
              </Button>
            </PaginationItem>
          ))}

          <PaginationItem>
            <Button
              asChild={currentPage < totalPages}
              variant="outline"
              className="h-10 rounded-full"
              disabled={currentPage >= totalPages}
            >
              {currentPage < totalPages ? (
                <Link href={createPageHref(params, currentPage + 1)}>Next</Link>
              ) : (
                <span>Next</span>
              )}
            </Button>
          </PaginationItem>
        </PaginationContent>
      </Pagination>
    </div>
  );
}

async function GuidesContent({ searchParams }: GuidesPageProps) {
  const params = await searchParams;
  let pagination = emptyWebsiteGuidesPagination;

  try {
    pagination = await fetchWebsiteGuides(
      {
        search: params.search,
        page: params.page || 1,
        per_page: 12,
      },
      { next: { revalidate } } as RequestInit,
    );
  } catch {
    pagination = emptyWebsiteGuidesPagination;
  }

  const guides = pagination.data;

  return (
    <main>
      <form action="/guides" className="mb-8">
        <div className="flex h-14 items-center overflow-hidden rounded-xl border border-border bg-white pl-4 shadow-sm transition-colors focus-within:border-[var(--theme-primary)] focus-within:ring-2 focus-within:ring-[var(--theme-secondary)]/15">
          <Search className="mr-3 h-5 w-5 shrink-0 text-slate-400" />
          <input
            name="search"
            type="search"
            defaultValue={params.search || ""}
            placeholder="Search guides by name, skills, language, or location..."
            className="min-w-0 flex-1 bg-transparent text-sm font-medium text-foreground outline-none placeholder:text-muted-foreground"
            aria-label="Search guides"
          />
          <button
            type="submit"
            className="ml-3 inline-flex h-full shrink-0 items-center justify-center rounded-r-xl bg-gradient-to-r from-[var(--theme-secondary)] to-[var(--theme-accent)] px-7 text-base font-semibold text-white shadow-md shadow-[var(--theme-secondary)]/25 transition hover:opacity-95"
          >
            Search
          </button>
        </div>
      </form>

      {guides.length > 0 ? (
        <>
          <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
            {guides.map((guide) => (
              <GuideCard key={guide.id} guide={guide} />
            ))}
          </div>
          <GuidesPagination pagination={pagination} params={params} />
        </>
      ) : (
        <div className="rounded-2xl border border-border/50 bg-white py-16 text-center shadow-sm">
          <p className="mb-2 text-lg text-muted-foreground">No guides found</p>
          <p className="text-sm text-muted-foreground">
            Try searching with a different name, skill, language, or location
          </p>
        </div>
      )}
    </main>
  );
}

export default function GuidesPage(props: GuidesPageProps) {
  return (
    <div className="container mx-auto px-4 pb-28 pt-28 md:pb-32 md:pt-32">
      <div className="mb-8">
        <h1 className="mb-2 text-3xl font-black text-foreground">
          <LocalizedText textKey="guides.findYourGuide" />
        </h1>
        <p className="text-muted-foreground">
          <LocalizedText textKey="guides.findYourGuideDescription" />
        </p>
      </div>

      <Suspense
        fallback={
          <div className="animate-pulse space-y-4">
            <div className="h-14 rounded-xl bg-muted" />
            <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
              {[...Array(8)].map((_, i) => (
                <div key={i} className="h-80 rounded-lg bg-muted" />
              ))}
            </div>
          </div>
        }
      >
        <GuidesContent {...props} />
      </Suspense>
    </div>
  );
}
