"use client";

import { useEffect, useState, useMemo } from "react";
import { useSearchParams } from "next/navigation";
import Link from "next/link";
import Image from "next/image";

type ProjectRow = {
  id: string | number;
  submission_id?: string | number;
  title?: string;
  uploader?: string;
  category?: string;
  tags?: string[];
  p_image?: { filename_disk?: string; title?: string };
};

export default function ProjectsPage() {
  const searchParams = useSearchParams();
  const initialQuery = searchParams.get("query") || "";

  const [query, setQuery] = useState(initialQuery);
  const [debouncedQuery, setDebouncedQuery] = useState(initialQuery);
  const [projects, setProjects] = useState<ProjectRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [categories] = useState([
    "assets",
    "documents",
    "fixtures",
    "projects",
    "templates",
    "test files",
    "tools",
  ]);

  useEffect(() => {
    const timer = setTimeout(() => setDebouncedQuery(query), 300);
    return () => clearTimeout(timer);
  }, [query]);

  useEffect(() => {
    const url = new URL(`${process.env.NEXT_PUBLIC_API_BASE_URL}/items/projects`);
    url.searchParams.set(
      "fields",
      "submission_id,id,title,uploader,category,tags,p_image.filename_disk,p_image.title"
    );
    url.searchParams.set("limit", "-1");

    fetch(url.toString(), { cache: "no-store" })
    .then((res) => res.json())
    .then((data) => {
      setProjects((data?.data as ProjectRow[]) || []);
      setLoading(false);
    })
    .catch(() => setLoading(false));
  }, []);

  const highlight = (text: string) => {
    if (!debouncedQuery) return text;
    const regex = new RegExp(`(${debouncedQuery})`, "gi");
    return text?.replace(regex, "<mark>$1</mark>");
  };

  const normalize = (str: unknown) => String(str ?? "").toLowerCase().replace(/[_\s]/g, "");

  const filtered = useMemo(() => {
    const q = normalize(debouncedQuery);
    return projects.filter((entry) => {
      const fieldsToSearch = [
        entry.title ?? "",
        entry.uploader ?? "",
        entry.category ?? "",
        Array.isArray(entry.tags) ? entry.tags.join(" ") : "",
      ];
      return fieldsToSearch.filter(Boolean).some((field) => normalize(field).includes(q));
    });
  }, [projects, debouncedQuery]);

  const tagCounts = useMemo(() => {
    const counts: Record<string, number> = {};
    projects.forEach((p) => {
      if (Array.isArray(p.tags)) {
        p.tags.forEach((tag) => {
          counts[tag] = (counts[tag] || 0) + 1;
        });
      }
    });
    return counts;
  }, [projects]);

  const popularTags = Object.entries(tagCounts)
  .sort((a, b) => (Number(b[1]) || 0) - (Number(a[1]) || 0))
  .slice(0, 10)
  .map(([tag]) => tag);

  const recentTags = [...projects]
  .sort(
    (a, b) =>
    Number(b.submission_id ?? b.id ?? 0) - Number(a.submission_id ?? a.id ?? 0)
  )
  .slice(0, 10)
  .flatMap((p) => p.tags || [])
  .filter((tag, i, self) => self.indexOf(tag) === i)
  .slice(0, 10);

  const uniqueUploaders = new Set(projects.map((p) => p.uploader).filter(Boolean)).size;
  const totalTags = Object.keys(tagCounts).length;

  const detailHref = (p: ProjectRow) => `/projects/${p.submission_id ?? p.id}`;
  const imageSrc = (p: ProjectRow) =>
  p.p_image?.filename_disk
  ? `https://forms.lasereverything.net/assets/${p.p_image.filename_disk}`
  : null;

  return (
    <div className="p-6 max-w-7xl mx-auto">
    <style jsx global>{`
      mark {
        background: #ffde59;
        color: #242424;
        padding: 0 2px;
        border-radius: 2px;
      }
      .card-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(500px, 1fr));
        gap: 1rem;
      }
      .project-card {
        display: flex;
        background-color: #242424;
        color: var(--card-foreground);
        border: 1px solid var(--border);
        border-radius: 0.5rem;
        overflow: hidden;
        height: 150px;
      }
      .project-image {
        width: 150px;
        height: 150px;
        object-fit: cover;
        background: #111;
      }
      .project-content {
        padding: 0.75rem;
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
      }
      .project-tags {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .project-tags span,
      .flex.flex-wrap span {
        display: inline-block;
        margin-right: 0.25rem;
        margin-bottom: 0.25rem;
        padding: 0.25rem 0.5rem;
        background-color: var(--muted);
        color: var(--foreground);
        border-radius: 0.25rem;
        font-size: 0.7rem;
        cursor: pointer;
        transition: background-color 0.2s ease;
      }
      .project-tags span:hover,
      .flex.flex-wrap span:hover {
        background-color: #ffde59;
        color: #000;
      }
      `}</style>

      <div className="grid md:grid-cols-2 xl:grid-cols-3 gap-4 mb-6">
      <div className="card bg-card text-card-foreground p-4">
      <h1 className="text-xl font-bold mb-2">Community Projects</h1>
      <input
      type="search"
      value={query}
      onChange={(e) => setQuery(e.target.value)}
      placeholder="Search projects..."
      className="w-full dark:bg-background border border-border rounded-md p-2"
      />
      <Link
      href="/"
      className="inline-block mt-4 px-4 py-2 bg-accent text-background rounded-md text-sm"
      >
      ← Back to Main Menu
      </Link>
      </div>

      <div className="card bg-card text-card-foreground p-4">
      <h2 className="text-md font-semibold mb-2">Popular Tags</h2>
      {popularTags.length > 0 ? (
        <div className="flex flex-wrap">
        {popularTags.map((tag, i) => (
          <span key={i} onClick={() => setQuery(tag)} title={tag}>
          {tag}
          </span>
        ))}
        </div>
      ) : (
        <p className="text-sm text-muted-foreground">No tags yet.</p>
      )}
      </div>

      <div className="card bg-card text-card-foreground p-4">
      <h2 className="text-md font-semibold mb-2">Recent Tags</h2>
      {recentTags.length > 0 ? (
        <div className="flex flex-wrap">
        {recentTags.map((tag, i) => (
          <span key={i} onClick={() => setQuery(tag)} title={tag}>
          {tag}
          </span>
        ))}
        </div>
      ) : (
        <p className="text-sm text-muted-foreground">No recent tags.</p>
      )}
      </div>

      <div className="card bg-card text-card-foreground p-4">
      <h2 className="text-md font-semibold mb-2">Project Stats</h2>
      <p className="text-sm text-muted-foreground">Total Projects: {projects.length}</p>
      <p className="text-sm text-muted-foreground">Unique Uploaders: {uniqueUploaders}</p>
      <p className="text-sm text-muted-foreground">Total Tags: {totalTags}</p>
      </div>

      <div className="card bg-card text-card-foreground p-4">
      <h2 className="text-md font-semibold mb-2">Browse by Category</h2>
      <div className="flex flex-wrap">
      {categories.map((cat, i) => (
        <span key={i} onClick={() => setQuery(cat)}>
        {cat === "test_files" ? "test files" : cat}
        </span>
      ))}
      </div>
      </div>

      <div className="card bg-card text-card-foreground p-4 flex flex-col justify-between">
      <div>
      <h2 className="text-md font-semibold mb-2">Submit a Project</h2>
      <p className="text-sm text-muted-foreground mb-2">
      Have a cool design, tool, or jig to share? Submit it to the community database.
      </p>
      </div>
      <button
      disabled
      className="bg-muted text-foreground text-sm px-4 py-2 rounded opacity-50 cursor-not-allowed"
      >
      Coming Soon
      </button>
      </div>
      </div>

      <hr className="my-8 border-border" />

      {loading ? (
        <p className="text-muted">Loading projects...</p>
      ) : filtered.length === 0 ? (
        <p className="text-muted">No projects found.</p>
      ) : (
        <div className="card-grid">
        {filtered.map((project) => {
          const key = String(project.submission_id ?? project.id);
          const href = detailHref(project);
          const src = imageSrc(project);
          return (
            <div key={key} className="project-card">
            {src ? (
              <Image
              src={src}
              alt={project.p_image?.title || "Project image"}
              width={150}
              height={150}
              className="project-image"
              />
            ) : (
              <div className="project-image flex items-center justify-center text-xs text-muted-foreground">
              No image
              </div>
            )}
            <div className="project-content">
            <div>
            <Link href={href} className="text-base font-semibold text-accent underline">
            {/* highlight title if searching */}
            <span
            dangerouslySetInnerHTML={{
              __html: highlight(project.title || "Untitled"),
            }}
            />
            </Link>
            <p className="text-xs text-muted-foreground">
            Uploaded by:{" "}
            <span
            dangerouslySetInnerHTML={{
              __html: highlight(project.uploader || "—"),
            }}
            />
            </p>
            <p className="text-xs text-muted-foreground">
            Category:{" "}
            <span
            dangerouslySetInnerHTML={{
              __html: highlight(project.category || "—"),
            }}
            />
            </p>
            </div>
            <div className="project-tags">
            {Array.isArray(project.tags) && project.tags.length > 0
              ? project.tags.map((tag, i) => (
                <span key={i} onClick={() => setQuery(tag)} title={tag}>
                {tag}
                </span>
              ))
              : ""}
              </div>
              </div>
              </div>
          );
        })}
        </div>
      )}
      </div>
  );
}
