"use client";

import { useMemo, useState } from "react";
import { Search } from "lucide-react";
import { Tile, type AppTile } from "@/components/tile";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";

const ALL = "Vše";

export function TileGrid({ apps }: { apps: AppTile[] }) {
  const [query, setQuery] = useState("");
  const [activeCategory, setActiveCategory] = useState(ALL);

  const categories = useMemo(() => {
    const all = Array.from(new Set(apps.map((a) => a.category)));
    return [ALL, ...all];
  }, [apps]);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return apps.filter((a) => {
      const matchesQuery =
        !q ||
        a.title.toLowerCase().includes(q) ||
        a.description.toLowerCase().includes(q) ||
        a.category.toLowerCase().includes(q);
      const matchesCategory =
        activeCategory === ALL || a.category === activeCategory;
      return matchesQuery && matchesCategory;
    });
  }, [apps, query, activeCategory]);

  return (
    <div className="flex flex-col gap-5">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div className="relative w-full sm:max-w-xs">
          <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--color-text-quaternary)]" />
          <Input
            placeholder="Hledat aplikace…"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            className="pl-9"
          />
        </div>
        <div className="no-scrollbar -mx-1 flex shrink-0 gap-1.5 overflow-x-auto px-1">
          {categories.map((cat) => {
            const isActive = cat === activeCategory;
            return (
              <button
                key={cat}
                type="button"
                onClick={() => setActiveCategory(cat)}
                className={cn(
                  "system-xs-medium shrink-0 rounded-lg border px-3 py-1.5 transition-colors",
                  isActive
                    ? "border-[var(--color-primary)] bg-[color-mix(in_srgb,var(--color-primary)_10%,transparent)] text-[var(--color-primary)]"
                    : "border-[var(--color-border-default)] bg-[var(--color-card)] text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-tertiary)] hover:text-[var(--color-text-secondary)]",
                )}
              >
                {cat}
              </button>
            );
          })}
        </div>
      </div>

      {filtered.length === 0 ? (
        <div className="rounded-lg border-[0.5px] border-dashed border-[var(--color-border-hover)] bg-[var(--color-card)] p-12 text-center">
          <p className="system-sm-medium text-[var(--color-text-tertiary)]">
            Žádné aplikace neodpovídají vyhledávání.
          </p>
        </div>
      ) : (
        <div className="grid auto-rows-[1fr] grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
          {filtered.map((app) => (
            <Tile key={app.id} app={app} />
          ))}
        </div>
      )}
    </div>
  );
}
