import { useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useTheme } from "next-themes";
import { Search, RefreshCw, AlertCircle } from "lucide-react";
import { TextHoverEffect } from "@/components/ui/text-hover-effect";
import ProjectCard from "@/components/ProjectCard";
import {
  fetchProjects,
  CATEGORY_LABELS,
  CATEGORY_ORDER,
  type LiveProject,
  type ProjectCategory,
} from "@/lib/projects";

const PAGE_SIZE = 12;

type Filter = ProjectCategory | "all";

const ProjectShowcase = () => {
  const { resolvedTheme } = useTheme();
  const cardBg = resolvedTheme === "dark" ? "hsl(0 0% 6%)" : "hsl(0 0% 96%)";

  const [filter, setFilter] = useState<Filter>("all");
  const [search, setSearch] = useState("");
  const [visible, setVisible] = useState(PAGE_SIZE);

  const { data, isLoading, isError, isFetching, refetch } = useQuery({
    queryKey: ["projects"],
    queryFn: ({ signal }) => fetchProjects(signal),
    staleTime: 5 * 60 * 1000,
    refetchOnWindowFocus: false,
    retry: 1,
  });

  const projects = data?.projects ?? [];

  const filtered = useMemo(() => {
    const term = search.trim().toLowerCase();
    return projects.filter((project) => {
      if (filter !== "all" && project.category !== filter) return false;
      if (!term) return true;
      return (
        project.name.toLowerCase().includes(term) ||
        project.repo.toLowerCase().includes(term) ||
        project.description.toLowerCase().includes(term) ||
        (project.subdomain ?? "").toLowerCase().includes(term)
      );
    });
  }, [projects, filter, search]);

  const shown = filtered.slice(0, visible);

  const chips: { key: Filter; label: string; count: number }[] = [
    { key: "all", label: "Alle", count: projects.length },
    ...CATEGORY_ORDER.filter((c) => (data?.counts?.[c] ?? 0) > 0).map((c) => ({
      key: c as Filter,
      label: CATEGORY_LABELS[c],
      count: data?.counts?.[c] ?? 0,
    })),
  ];

  const applyFilter = (key: Filter) => {
    setFilter(key);
    setVisible(PAGE_SIZE);
  };

  const stand = data?.generatedAt
    ? new Date(data.generatedAt).toLocaleTimeString("de-DE", { hour: "2-digit", minute: "2-digit" })
    : null;

  return (
    <section id="projects" className="relative bg-background pb-24 pt-8 md:pb-32 md:pt-12">
      {/* Überschrift */}
      <div className="relative z-10 -mb-4 flex h-[14rem] items-center justify-center">
        <TextHoverEffect text="Projekte" />
      </div>

      <div className="container mx-auto px-6">
        {/* Live-Status */}
        <div className="mb-8 flex flex-col gap-4 md:flex-row md:items-end md:justify-between">
          <div>
            <div className="label-tag mb-3">Live aus unserem Git</div>
            <p className="max-w-2xl leading-relaxed text-muted-foreground">
              Kein gepflegtes Portfolio, sondern der echte Stand: jedes Repository, das gerade auf{" "}
              <span className="text-foreground">git.webklar.com</span> liegt – inklusive letztem Commit
              und Hosting-Status. Öffentlich erreichbare Seiten zeigen wir als echte Live-Vorschau.
            </p>
          </div>
          {data && (
            <div className="shrink-0 text-[11px] uppercase tracking-wider text-muted-foreground md:text-right">
              <div className="font-display text-3xl font-medium tracking-tight text-foreground">
                {data.total}
              </div>
              <div>Repositories</div>
              {stand && (
                <div className="mt-1 inline-flex items-center gap-1.5">
                  <RefreshCw className={`h-3 w-3 ${isFetching ? "animate-spin" : ""}`} />
                  Stand {stand} Uhr
                </div>
              )}
            </div>
          )}
        </div>

        {/* Filter + Suche */}
        {projects.length > 0 && (
          <div className="mb-8 flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
            <div className="flex flex-wrap gap-2">
              {chips.map((chip) => (
                <button
                  key={chip.key}
                  type="button"
                  onClick={() => applyFilter(chip.key)}
                  className={`rounded-full border px-4 py-1.5 text-[11px] uppercase tracking-wider transition-colors ${
                    filter === chip.key
                      ? "border-foreground bg-foreground text-background"
                      : "border-border text-muted-foreground hover:border-foreground/40 hover:text-foreground"
                  }`}
                >
                  {chip.label}
                  <span className="ml-2 opacity-60">{chip.count}</span>
                </button>
              ))}
            </div>

            <div className="relative lg:w-72">
              <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <input
                type="search"
                value={search}
                onChange={(event) => {
                  setSearch(event.target.value);
                  setVisible(PAGE_SIZE);
                }}
                placeholder="Projekt oder Repository suchen"
                className="w-full rounded-full border border-border bg-transparent py-2 pl-9 pr-4 text-sm text-foreground placeholder:text-muted-foreground focus:border-foreground/40 focus:outline-none"
              />
            </div>
          </div>
        )}

        {/* Ladezustand */}
        {isLoading && (
          <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
            {Array.from({ length: 6 }).map((_, index) => (
              <div
                key={index}
                className="animate-pulse overflow-hidden rounded-[10px] border border-border"
              >
                <div className="aspect-[16/10] w-full bg-secondary/50" />
                <div className="space-y-3 p-6">
                  <div className="h-4 w-2/3 rounded bg-secondary/60" />
                  <div className="h-3 w-full rounded bg-secondary/40" />
                  <div className="h-3 w-1/2 rounded bg-secondary/40" />
                </div>
              </div>
            ))}
          </div>
        )}

        {/* Fehler */}
        {isError && (
          <div className="flex flex-col items-start gap-4 rounded-[10px] border border-border p-8 md:flex-row md:items-center md:justify-between">
            <div className="flex items-start gap-3">
              <AlertCircle className="mt-0.5 h-5 w-5 shrink-0 text-muted-foreground" />
              <div>
                <p className="mb-1 font-display uppercase tracking-tight text-foreground">
                  Projekte gerade nicht abrufbar
                </p>
                <p className="text-sm text-muted-foreground">
                  Die Live-Verbindung zu unserem Git antwortet nicht. Schreiben Sie uns – wir zeigen
                  Ihnen die passenden Referenzen persönlich.
                </p>
              </div>
            </div>
            <button
              type="button"
              onClick={() => refetch()}
              className="shrink-0 rounded-full border border-border px-5 py-2 text-[11px] uppercase tracking-wider text-muted-foreground transition-colors hover:border-foreground/40 hover:text-foreground"
            >
              Erneut versuchen
            </button>
          </div>
        )}

        {/* Karten */}
        {!isLoading && !isError && (
          <>
            <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
              {shown.map((project: LiveProject) => (
                <ProjectCard key={project.id} project={project} cardBg={cardBg} />
              ))}
            </div>

            {filtered.length === 0 && (
              <p className="py-12 text-center text-sm text-muted-foreground">
                Kein Projekt gefunden. Andere Kategorie oder Suchbegriff probieren.
              </p>
            )}

            {visible < filtered.length && (
              <div className="mt-10 flex justify-center">
                <button
                  type="button"
                  onClick={() => setVisible((current) => current + PAGE_SIZE)}
                  className="rounded-full border border-border px-8 py-3 text-[11px] uppercase tracking-wider text-muted-foreground transition-colors hover:border-foreground/40 hover:text-foreground"
                >
                  Mehr laden
                  <span className="ml-2 opacity-60">
                    {filtered.length - visible} weitere
                  </span>
                </button>
              </div>
            )}
          </>
        )}
      </div>
    </section>
  );
};

export default ProjectShowcase;
