"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { ArrowRight } from "lucide-react";
import { cn } from "@/lib/cn";
import {
  RESOURCE_POSTS,
  RESOURCE_TABS,
  type ResourceTab,
} from "@/lib/resources-posts";

const TILE_CLS: Record<ResourceTab, { bg: string; chip: string; text: string }> = {
  construction: { bg: "bg-brand-tint", chip: "bg-white text-brand", text: "CONSTRUCTION ERP" },
  manufacturing: { bg: "bg-accent-soft", chip: "bg-white text-accent-dark", text: "MANUFACTURING ERP" },
  basics: { bg: "bg-paper", chip: "bg-white text-muted", text: "ERP BASICS" },
  "case-studies": { bg: "bg-navy", chip: "bg-white text-navy", text: "CASE STUDY" },
  updates: { bg: "bg-brand", chip: "bg-white text-brand", text: "PRODUCT UPDATE" },
};

function formatDate(iso: string): string {
  const d = new Date(iso + "T00:00:00");
  if (Number.isNaN(d.getTime())) return iso;
  return d.toLocaleDateString("en-IN", { day: "numeric", month: "short", year: "numeric" });
}

export default function ResourceGuides({ initialQuery = "" }: { initialQuery?: string }) {
  const [tab, setTab] = useState<ResourceTab | "all">("all");
  const [query, setQuery] = useState(initialQuery);
  const [visible, setVisible] = useState(9);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return RESOURCE_POSTS.filter(
      (p) =>
        (tab === "all" || p.tab === tab) &&
        (!q ||
          p.title.toLowerCase().includes(q) ||
          p.excerpt.toLowerCase().includes(q))
    );
  }, [tab, query]);

  const featured = RESOURCE_POSTS.find((p) => p.featured);

  return (
    <div className="mx-container">
      {featured && tab === "all" && !query && (
        <Link
          href={`/resources/${featured.slug}`}
          className="group mb-8 mt-12 grid overflow-hidden rounded-2xl border border-line bg-white shadow-soft lg:grid-cols-[1fr_1fr]"
        >
          <div className="relative min-h-[220px] overflow-hidden bg-navy" aria-hidden="true">
            {featured.coverImage ? (
              <Image
                src={featured.coverImage}
                alt=""
                fill
                sizes="(max-width: 1024px) 100vw, 50vw"
                className="object-cover"
              />
            ) : null}
          </div>
          <div className="p-8 max-sm:p-6">
            <p className="text-xs text-muted">
              Construction ERP · {formatDate(featured.date)} · {featured.readMins} min read
            </p>
            <h2 className="mt-2 font-display text-[clamp(22px,2.6vw,30px)] font-bold leading-snug text-ink">
              {featured.title}
            </h2>
            <p className="mt-3 line-clamp-2 text-[15px] leading-relaxed text-muted">
              {featured.excerpt}
            </p>
            <span className="mt-5 inline-flex items-center gap-1.5 text-[14px] font-semibold text-brand group-hover:text-brand-dark">
              Read the guide <ArrowRight size={16} aria-hidden="true" />
            </span>
          </div>
        </Link>
      )}

      <div className="mb-8 flex flex-wrap items-center gap-3">
        <div className="flex gap-1 overflow-x-auto" role="tablist" aria-label="Filter articles by topic">
          {(["all", ...RESOURCE_TABS.map((t) => t.id)] as const).map((t) => {
            const label = t === "all" ? `All (${RESOURCE_POSTS.length})` : `${RESOURCE_TABS.find((x) => x.id === t)?.label} (${RESOURCE_POSTS.filter((p) => p.tab === t).length})`;
            const selected = tab === t;
            return (
              <button
                key={t}
                type="button"
                role="tab"
                aria-selected={selected}
                onClick={() => { setTab(t); setVisible(9); }}
                className={cn(
                  "shrink-0 rounded-full border px-4 py-2 text-[13px] font-semibold transition-colors",
                  selected
                    ? "border-navy bg-navy text-white"
                    : "border-line bg-white text-muted hover:border-ink hover:text-ink"
                )}
              >
                {label}
              </button>
            );
          })}
        </div>
        <input
          type="search"
          value={query}
          onChange={(e) => { setQuery(e.target.value); setVisible(9); }}
          placeholder="Filter articles…"
          aria-label="Filter articles"
          className="ml-auto h-10 min-w-[180px] rounded-full border border-line bg-white px-4 text-sm text-ink placeholder:text-muted focus:border-brand focus:outline-none max-sm:ml-0 max-sm:w-full"
        />
      </div>

      {filtered.length === 0 ? (
        <p className="rounded-2xl border border-line bg-white p-10 text-center text-[15px] text-muted">
          No articles match. Try a different keyword or tab.
        </p>
      ) : (
        <div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
          {filtered.slice(0, visible).map((p) => {
            const tile = TILE_CLS[p.tab];
            return (
              <Link
                key={p.slug}
                href={`/resources/${p.slug}`}
                className="group flex flex-col overflow-hidden rounded-2xl border border-line bg-white shadow-soft"
              >
                <div className={cn("relative min-h-[160px] overflow-hidden", !p.coverImage && tile.bg)} aria-hidden="true">
                  {p.coverImage ? (
                    <Image
                      src={p.coverImage}
                      alt=""
                      fill
                      sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw"
                      className="object-cover"
                      loading="lazy"
                    />
                  ) : null}
                </div>
                <div className="flex flex-1 flex-col p-7">
                  <h3 className="font-display text-[18px] font-bold leading-snug text-ink group-hover:text-brand">
                    {p.title}
                  </h3>
                  <p className="mt-2 line-clamp-2 text-[14px] leading-relaxed text-muted">{p.excerpt}</p>
                  <p className="mt-3 text-xs text-muted">
                    {formatDate(p.date)} · {p.readMins} min read
                  </p>
                </div>
              </Link>
            );
          })}
        </div>
      )}

      {visible < filtered.length && (
        <div className="mt-8 text-center">
          <button
            type="button"
            onClick={() => setVisible((v) => v + 9)}
            className="inline-flex min-h-[44px] items-center justify-center rounded-lg border border-line bg-white px-6 text-sm font-semibold text-ink hover:border-brand hover:text-brand"
          >
            Load more articles
          </button>
        </div>
      )}
    </div>
  );
}
