import Image from "next/image";
import { BlogCard } from "@/components/blogs/blog-card";
import { LocalizedText } from "@/components/localized-text";
import {
  fetchWebsiteBlogs,
  mapWebsiteBlogToBlog,
  type WebsiteBlog,
  type WebsiteBlogFilters,
} from "@/lib/website-blogs";
import { Search } from "lucide-react";

type BlogsPageProps = {
  searchParams?: Promise<Record<string, string | string[] | undefined>>;
};

function getParam(
  searchParams: Record<string, string | string[] | undefined>,
  key: string,
) {
  const value = searchParams[key];
  return Array.isArray(value) ? value[0] || "" : value || "";
}

function NoBlogDataState({ message }: { message?: string }) {
  return (
    <div className="flex min-h-[430px] items-center justify-center rounded-2xl border border-[var(--theme-border-soft)] bg-[linear-gradient(180deg,#ffffff_0%,var(--theme-surface)_100%)] px-5 py-14 text-center shadow-sm">
      <div className="flex max-w-md flex-col items-center">
        <div className="relative mb-0 h-24 w-32">
          <Image
            src="/placeholder.png"
            alt=""
            fill
            className="object-contain"
            priority
          />
        </div>

        <h2 className="text-5xl font-black text-foreground">
          <LocalizedText textKey="blogs.guideBlogs" />
        </h2>
        <p className="mt-2 text-sm font-medium leading-6 text-muted-foreground">
          <LocalizedText textKey="blogs.availableSoon" />
        </p>

        <p className="mt-4 max-w-xs text-xs font-medium leading-5 text-muted-foreground">
          {message || (
            <LocalizedText textKey="blogs.availableSoonDescription" />
          )}
        </p>
      </div>
    </div>
  );
}

export default async function BlogsPage({ searchParams }: BlogsPageProps) {
  const params = (await searchParams) || {};
  const filters: WebsiteBlogFilters = {
    search: getParam(params, "search"),
  };

  let apiBlogs: WebsiteBlog[] = [];
  let error = "";

  try {
    apiBlogs = await fetchWebsiteBlogs(filters);
  } catch (err) {
    error = err instanceof Error ? err.message : "Failed to load blogs.";
  }

  const blogs = apiBlogs.map(mapWebsiteBlogToBlog);
  const hasBlogData = !error && blogs.length > 0;

  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="home.travelInsights" />
        </h1>
        <p className="text-muted-foreground">
          <LocalizedText textKey="home.travelInsightsDesc" />
        </p>
      </div>

      {hasBlogData && (
        <form action="/blogs" 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={filters.search}
              placeholder="Search blogs by title, guide, 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 blogs"
            />
            <button
              type="submit"
              className="ml-3 inline-flex h-full shrink-0 items-center justify-center 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>
      )}

      <div className="grid gap-10">
        <div className="space-y-6">
          {error && (
            <NoBlogDataState message="Main data is empty or Try again from the home page." />
          )}

          {!error && blogs.length > 0 && (
            <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
              {blogs.map((blog) => (
                <BlogCard key={blog.id} blog={blog} />
              ))}
            </div>
          )}

          {!error && blogs.length === 0 && <NoBlogDataState />}
        </div>
      </div>
    </div>
  );
}
