import Link from "next/link";
import Image from "next/image";
import { getProjects } from "@/lib/api";

type Project = {
  slug: string;
  title: string;
  summary?: string | null;
  tags?: string[] | null;
  cover_image?: string | null;
  type?: string | null;
  category?: string | null;
};

const FILTERS = [
  { key: "all", label: "All" },
  { key: "saas", label: "SaaS" },
  { key: "ecommerce", label: "E-commerce" },
  { key: "automation", label: "Automation" },
  { key: "integrations", label: "Integrations" },
] as const;

function classNames(...xs: Array<string | false | null | undefined>) {
  return xs.filter(Boolean).join(" ");
}

function PlaceholderCover() {
  return (
    <div className="relative h-full w-full overflow-hidden rounded-xl border border-slate-200 bg-white">
      <div className="absolute inset-0">
        <div className="absolute -top-10 -left-10 h-44 w-44 rounded-full bg-cyan-400/10 blur-3xl" />
        <div className="absolute -bottom-10 -right-10 h-44 w-44 rounded-full bg-blue-500/10 blur-3xl" />
        <div className="absolute inset-0 bg-[radial-gradient(circle_at_25%_25%,rgba(34,211,238,0.10),transparent_55%),radial-gradient(circle_at_80%_30%,rgba(59,130,246,0.08),transparent_55%)]" />
      </div>

      <div className="absolute inset-0 opacity-60">
        <div className="absolute inset-0 bg-[linear-gradient(to_right,rgba(15,23,42,0.06)_1px,transparent_1px),linear-gradient(to_bottom,rgba(15,23,42,0.06)_1px,transparent_1px)] bg-[size:26px_26px]" />
        <div className="absolute inset-0 [mask-image:radial-gradient(65%_55%_at_50%_40%,black,transparent)] bg-white" />
      </div>

      <svg
        className="absolute inset-0"
        viewBox="0 0 800 360"
        preserveAspectRatio="none"
        aria-hidden="true"
      >
        <g fill="none" stroke="rgba(15,23,42,0.18)" strokeWidth="1">
          <path d="M110 90 L260 90 L320 150 L520 150 L610 220" />
          <path d="M160 250 L260 210 L420 210 L520 260 L680 260" />
          <path d="M240 70 L240 150 L360 150" />
          <path d="M520 110 L520 190 L610 190" />
        </g>
        <g fill="rgba(34,211,238,0.45)">
          <circle cx="110" cy="90" r="6" />
          <circle cx="260" cy="90" r="6" />
          <circle cx="320" cy="150" r="6" />
          <circle cx="520" cy="150" r="6" />
          <circle cx="610" cy="220" r="6" />
        </g>
        <g fill="rgba(59,130,246,0.35)">
          <circle cx="160" cy="250" r="6" />
          <circle cx="260" cy="210" r="6" />
          <circle cx="420" cy="210" r="6" />
          <circle cx="520" cy="260" r="6" />
          <circle cx="680" cy="260" r="6" />
        </g>
      </svg>

      <div className="absolute left-4 top-4 inline-flex items-center gap-2 rounded-full border border-slate-200 bg-white/80 px-3 py-1 text-[11px] font-mono uppercase tracking-wider text-slate-600 backdrop-blur">
        <span className="h-1.5 w-1.5 rounded-full bg-cyan-500/90" />
        system snapshot
      </div>
    </div>
  );
}

function TagPill({ children }: { children: React.ReactNode }) {
  return (
    <span className="inline-flex items-center rounded-full border border-slate-200 bg-white px-2.5 py-1 text-xs font-medium text-slate-700">
      {children}
    </span>
  );
}

function MetricPillar({
  title,
  desc,
  icon,
}: {
  title: string;
  desc: string;
  icon: React.ReactNode;
}) {
  return (
    <div className="rounded-2xl border border-slate-200 bg-white p-6">
      <div className="flex items-start gap-3">
        <div className="mt-0.5 inline-flex h-9 w-9 items-center justify-center rounded-xl border border-slate-200 bg-slate-50">
          {icon}
        </div>
        <div>
          <div className="text-sm font-semibold text-slate-900">{title}</div>
          <p className="mt-1 text-sm leading-6 text-slate-600">{desc}</p>
        </div>
      </div>
    </div>
  );
}

export default async function WorkPage({
  searchParams,
}: {
  searchParams?: { type?: string };
}) {
  const projects = (await getProjects()) as Project[];

  const active = (searchParams?.type || "all").toLowerCase();
  const filtered =
    active === "all"
      ? projects
      : projects.filter((p) => (p.category || "").toLowerCase() === active);

  const curated = filtered.slice(0, 6);

  return (
    <main className="bg-white">
      {/* HERO */}
      <section className="relative overflow-hidden border-b border-slate-200">
        <div className="pointer-events-none absolute inset-0">
          <div className="absolute -top-28 -left-28 h-80 w-80 rounded-full bg-cyan-400/10 blur-3xl" />
          <div className="absolute -bottom-28 -right-28 h-80 w-80 rounded-full bg-blue-500/10 blur-3xl" />
          <div className="absolute inset-0 bg-[radial-gradient(circle_at_25%_20%,rgba(34,211,238,0.10),transparent_55%),radial-gradient(circle_at_80%_30%,rgba(59,130,246,0.08),transparent_55%)]" />
        </div>

        <div className="relative mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-12 sm:py-14">
          <div className="flex flex-col gap-6 sm:gap-7">
            <div>
              <div className="text-[11px] font-mono uppercase tracking-widest text-slate-500">
                Adblast IT
              </div>
              <h1 className="mt-2 text-3xl sm:text-4xl font-semibold tracking-tight text-slate-900">
                Work
              </h1>
              <p className="mt-3 max-w-2xl text-base text-slate-600">
                Real systems shipped for scale, security, and speed.
              </p>
            </div>

            <div className="flex flex-wrap items-center gap-2">
              {FILTERS.map((f) => {
                const isActive = active === f.key;
                const href = f.key === "all" ? "/work" : `/work?type=${f.key}`;
                return (
                  <Link
                    key={f.key}
                    href={href}
                    className={classNames(
                      "inline-flex items-center rounded-full px-4 py-2 text-sm font-medium transition border",
                      isActive
                        ? "border-slate-900 bg-slate-900 text-white"
                        : "border-slate-200 bg-white text-slate-700 hover:border-slate-300 hover:bg-slate-50"
                    )}
                  >
                    {f.label}
                  </Link>
                );
              })}

              <div className="ml-auto hidden sm:block text-xs text-slate-500">
                Confidential-friendly: curated and anonymized when needed.
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* GRID */}
      <section className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-10 sm:py-12">
        {curated.length === 0 ? (
          <div className="rounded-2xl border border-slate-200 bg-white p-8 text-slate-600">
            No case studies found for this filter yet.
          </div>
        ) : (
          <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
            {curated.map((p) => (
              <Link
                key={p.slug}
                href={`/work/${p.slug}`}
                className={classNames(
                  "group rounded-2xl border border-slate-200 bg-white p-5 transition",
                  "hover:border-slate-300 hover:bg-slate-50/40"
                )}
              >
                <div className="aspect-[16/9] w-full">
                  {p.cover_image ? (
                    <div className="relative h-full w-full overflow-hidden rounded-xl border border-slate-200 bg-white">
                      <Image
                        src={p.cover_image}
                        alt={p.title}
                        fill
                        className="object-cover"
                        sizes="(max-width: 1024px) 100vw, 33vw"
                      />
                      <div className="absolute inset-0 bg-gradient-to-t from-white/50 via-transparent to-transparent" />
                    </div>
                  ) : (
                    <PlaceholderCover />
                  )}
                </div>

                <div className="mt-4 flex items-start justify-between gap-3">
                  <h3 className="text-base font-semibold text-slate-900">
                    {p.title}
                  </h3>

                  <span className="inline-flex items-center gap-2 rounded-full border border-slate-200 bg-white px-3 py-1 text-[11px] font-mono uppercase tracking-wider text-slate-600">
                    <span className="h-1.5 w-1.5 rounded-full bg-cyan-500/90" />
                    {p.type === "concept_demo" ? "Concept" : "Case Study"}
                  </span>
                </div>

                {p.summary ? (
                  <p className="mt-2 text-sm leading-6 text-slate-600 line-clamp-2">
                    {p.summary}
                  </p>
                ) : (
                  <p className="mt-2 text-sm leading-6 text-slate-500">
                    A concise outcome summary will be added.
                  </p>
                )}

                <div className="mt-4 flex flex-wrap gap-2">
                  {(p.tags || []).slice(0, 4).map((t) => (
                    <TagPill key={t}>{t}</TagPill>
                  ))}
                </div>

                <div className="mt-5 inline-flex items-center gap-2 text-sm font-medium text-slate-700">
                  <span className="group-hover:text-slate-900">
                    View case study →
                  </span>
                </div>
              </Link>
            ))}
          </div>
        )}
      </section>

      {/* METRICS */}
      <section className="border-t border-slate-200 bg-[#FAFAFA]">
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-12 sm:py-14">
          <div className="text-center">
            <h2 className="text-xl sm:text-2xl font-semibold text-slate-900">
              How we measure success
            </h2>
            <p className="mt-3 max-w-2xl mx-auto text-sm sm:text-base text-slate-600">
              Calm delivery, measurable outcomes — built for long-term value.
            </p>
          </div>

          <div className="mt-10 grid gap-6 lg:grid-cols-3">
            <MetricPillar
              title="Reliability"
              desc="Predictable behavior under load. Defensive design, retries, and resilience patterns."
              icon={
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                  <path
                    d="M12 2l8 4v6c0 5-3.4 9.4-8 10-4.6-.6-8-5-8-10V6l8-4z"
                    stroke="currentColor"
                    strokeWidth="1.6"
                  />
                </svg>
              }
            />
            <MetricPillar
              title="Maintainability"
              desc="Clear boundaries, readable modules, and documentation that keeps teams moving fast."
              icon={
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                  <path
                    d="M4 19V5a2 2 0 012-2h10a2 2 0 012 2v14"
                    stroke="currentColor"
                    strokeWidth="1.6"
                  />
                  <path
                    d="M8 7h8M8 11h8M8 15h6"
                    stroke="currentColor"
                    strokeWidth="1.6"
                  />
                </svg>
              }
            />
            <MetricPillar
              title="Performance"
              desc="Efficient queries, caching strategy, and lean payloads — optimized for speed and cost."
              icon={
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                  <path
                    d="M12 20a8 8 0 108-8"
                    stroke="currentColor"
                    strokeWidth="1.6"
                  />
                  <path
                    d="M12 12l5-3"
                    stroke="currentColor"
                    strokeWidth="1.6"
                  />
                </svg>
              }
            />
          </div>
        </div>
      </section>

      {/* FOOTER STRIP */}
      <footer className="border-t border-slate-200 bg-white">
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-8 text-center">
          <div className="font-mono text-xs text-slate-500 uppercase tracking-wider">
            Laravel · Next.js · TypeScript · Docker · Cloud
          </div>
        </div>
      </footer>
    </main>
  );
}
