"use client";

import { useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { TechChip } from "@/components/site/TechChip";
import { GridOverlay } from "@/components/site/GridOverlay";
import type { Project, Media } from "@/payload-types";

type StatusFilter = "all" | "active" | "production" | "prototype" | "archived";

const STATUS_FILTERS: { label: string; value: StatusFilter }[] = [
  { label: "All", value: "all" },
  { label: "Active", value: "active" },
  { label: "Production", value: "production" },
  { label: "Prototype", value: "prototype" },
  { label: "Archived", value: "archived" },
];

const STATUS_PILL: Record<string, string> = {
  active: "bg-primary/10 text-primary border border-primary/20",
  production: "bg-tertiary/10 text-tertiary border border-tertiary/20",
  prototype: "bg-secondary/10 text-secondary border border-secondary/20",
  archived: "bg-surface-container-highest text-on-surface-variant border border-outline-variant/15",
};

function isMedia(val: unknown): val is Media {
  return typeof val === "object" && val !== null && "url" in val;
}

interface Props {
  projects: Project[];
}

export function ProjectsGrid({ projects }: Props) {
  const [active, setActive] = useState<StatusFilter>("all");

  const filtered =
    active === "all" ? projects : projects.filter((p) => p.status === active);

  return (
    <div>
      {/* Filter row */}
      <div className="mb-12 flex gap-2 overflow-x-auto pb-2 scrollbar-none">
        {STATUS_FILTERS.map((f) => (
          <button
            key={f.value}
            onClick={() => setActive(f.value)}
            className={`shrink-0 rounded-sm px-5 py-2 label-sm uppercase tracking-widest transition-colors ${
              active === f.value
                ? "bg-primary text-on-primary"
                : "bg-surface-container-high text-on-surface-variant hover:bg-surface-container-highest hover:text-on-surface"
            }`}
          >
            {f.label}
          </button>
        ))}
      </div>

      {/* Grid */}
      {filtered.length === 0 ? (
        <p className="body-md py-24 text-center text-on-surface-variant">
          No projects found.
        </p>
      ) : (
        <div className="grid grid-cols-1 gap-0 md:grid-cols-2 xl:grid-cols-3">
          {filtered.map((project, i) => {
            const hero = isMedia(project.heroImage) ? project.heroImage : null;
            const techVisible = project.tech?.slice(0, 4) ?? [];
            const overflow = (project.tech?.length ?? 0) - 4;

            return (
              <Link
                key={project.id}
                href={`/projects/${project.slug}`}
                className={`group relative flex flex-col overflow-hidden transition-colors ${
                  i % 2 === 0
                    ? "bg-surface-container-low"
                    : "bg-surface-container"
                }`}
              >
                {/* Image */}
                <div className="relative aspect-video w-full overflow-hidden">
                  <GridOverlay opacity={0.12} />
                  {hero?.url ? (
                    <Image
                      src={hero.url}
                      alt={hero.alt}
                      fill
                      className="object-cover grayscale opacity-50 group-hover:grayscale-0 group-hover:opacity-100 transition-all duration-700"
                      sizes="(max-width: 768px) 100vw, (max-width: 1280px) 50vw, 33vw"
                    />
                  ) : (
                    <div className="absolute inset-0 bg-surface-container-highest" />
                  )}
                  <div className="absolute inset-0 bg-gradient-to-t from-surface-container-low via-transparent to-transparent" />
                </div>

                {/* Content */}
                <div className="flex flex-1 flex-col gap-4 p-8">
                  <div className="flex items-center gap-3">
                    <span
                      className={`label-sm rounded-sm px-2.5 py-1 uppercase tracking-widest ${STATUS_PILL[project.status] ?? STATUS_PILL.archived}`}
                    >
                      {project.status}
                    </span>
                    {project.year && (
                      <span className="label-sm text-on-surface-variant">
                        {project.year}
                      </span>
                    )}
                  </div>

                  <h2 className="title-lg text-on-surface group-hover:text-primary transition-colors leading-tight">
                    {project.title}
                  </h2>

                  <p className="body-md flex-1 text-on-surface-variant leading-relaxed line-clamp-3">
                    {project.summary}
                  </p>

                  {techVisible.length > 0 && (
                    <div className="flex flex-wrap gap-2 pt-2">
                      {techVisible.map((t, ti) =>
                        t.label ? (
                          <TechChip key={t.id ?? ti} accent="secondary">
                            {t.label}
                          </TechChip>
                        ) : null,
                      )}
                      {overflow > 0 && (
                        <TechChip accent="primary">+{overflow}</TechChip>
                      )}
                    </div>
                  )}
                </div>
              </Link>
            );
          })}
        </div>
      )}
    </div>
  );
}
