"use client";

import React, { useMemo, useState } from "react";
import Link from "next/link";
import { Search, ChevronDown } from "lucide-react";
import type { SampleCategory } from "@/services/joomlaService";

interface SampleCategoryGridProps {
  categories: SampleCategory[];
  /** Where each subject card links, e.g. `/free-samples` or `/questions`. */
  basePath?: string;
  searchPlaceholder?: string;
  /**
   * The live template only prints this inflated count on the Samples branch
   * of `default_children.php` — the equivalent span on the Questions branch
   * has its count logic entirely commented out, so that page shows no number
   * at all. Defaults to matching Samples; Questions passes `false`.
   */
  showCount?: boolean;
}

/**
 * The live site doesn't show the real published-article count next to each
 * subject — it inflates it with this exact tiered multiplier (copied from
 * `default_children.php`'s count-badge logic: `$sample_cat_list['count']`
 * driving `> 100 ? *15 : > 40 ? *10 : > 20 ? *4 : as-is`). `cat.count` itself
 * stays the real `count_published` value from the API everywhere else (e.g.
 * the "Business Law" badge here reads real=22 but displays 88, matching what
 * the live site would show for that same real count).
 */
function displaySampleCount(realCount: number): number {
  if (realCount > 100) return realCount * 15;
  if (realCount > 40) return realCount * 10;
  if (realCount > 20) return realCount * 4;
  return realCount;
}

/**
 * Real-time client-side filter over the real subject list — the data itself
 * comes from the server component that renders this. The "paper type"
 * dropdown reuses the same real subjects rather than a separate, fabricated
 * taxonomy: there's no genuine document-type data behind the reference
 * design's version of it, so this gives it a real, working purpose instead
 * of being decorative.
 */
export const SampleCategoryGrid: React.FC<SampleCategoryGridProps> = ({
  categories,
  basePath = "/free-samples",
  searchPlaceholder = "Search your samples",
  showCount = true,
}) => {
  const [query, setQuery] = useState("");

  const grouped = useMemo(() => {
    const filtered = categories.filter((c) => c.title.toLowerCase().includes(query.trim().toLowerCase()));
    const byLetter = new Map<string, SampleCategory[]>();
    for (const cat of filtered) {
      const letter = cat.title.charAt(0).toUpperCase();
      if (!byLetter.has(letter)) byLetter.set(letter, []);
      byLetter.get(letter)!.push(cat);
    }
    return [...byLetter.entries()].sort(([a], [b]) => a.localeCompare(b));
  }, [categories, query]);

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row gap-3">
        <div className="relative sm:w-64 shrink-0">
          <select
            onChange={(e) => setQuery(e.target.value)}
            value={categories.some((c) => c.title === query) ? query : ""}
            className="w-full appearance-none bg-white rounded-lg border border-slate-200 pl-3 pr-9 py-2.5 text-sm text-slate-700 shadow-sm focus:outline-none focus:ring-2 focus:ring-[#5C7A36]/40"
            aria-label="Choose the academic paper type"
          >
            <option value="">Choose the Academic Paper Type</option>
            {categories.map((c) => (
              <option key={c.id} value={c.title}>
                {c.title}
              </option>
            ))}
          </select>
          <ChevronDown className="w-4 h-4 text-slate-400 absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none" />
        </div>

        <div className="flex items-center bg-white rounded-lg border border-slate-200 px-3 py-2.5 flex-1 shadow-sm focus-within:ring-2 focus-within:ring-[#5C7A36]/40 transition-shadow">
          <Search className="w-4 h-4 text-slate-400 shrink-0 mr-2" />
          <input
            type="text"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder={searchPlaceholder}
            className="w-full text-sm text-slate-800 placeholder-slate-400 focus:outline-none"
            aria-label="Search sample subjects"
          />
        </div>
      </div>

      {grouped.length === 0 ? (
        <p className="text-sm text-slate-500 animate-in fade-in">No subjects match &ldquo;{query}&rdquo;.</p>
      ) : (
        // A true masonry layout (column 1 fills A→B→C→D top-to-bottom, then
        // column 2, then column 3) needs CSS multi-column, not CSS Grid: grid
        // lays items out row-by-row, so a short card like "A" still shares a
        // row with taller siblings and leaves a gap even with items-start.
        // `columns-*` + `break-inside-avoid` on each card gives independent
        // per-column stacking instead.
        <div className="columns-1 sm:columns-2 lg:columns-3 gap-4">
          {grouped.map(([letter, cats], i) => (
            <div
              key={letter}
              style={{ animationDelay: `${i * 40}ms`, animationFillMode: "backwards" }}
              className="animate-in fade-in slide-in-from-bottom-2 duration-300 break-inside-avoid mb-4 bg-white rounded-xl border border-gray-200 overflow-hidden hover:shadow-md hover:border-[#5C7A36]/40  transition-all"
            >
              <div className="bg-green-800/80 text-white font-bold text-sm w-8 h-8 flex items-center justify-center m-3 rounded">
                {letter}
              </div>
              <div className="divide-y divide-slate-100">
                {cats.map((cat) => (
                  <Link
                    key={cat.id}
                    href={`${basePath}/${cat.alias}`}
                    className="group flex items-center justify-between px-4 py-2.5 text-sm text-slate-700 hover:bg-green-100/60 hover:text-green-800/80 transition-colors"
                  >
                    <span className="group-hover:translate-x-0.5 transition-transform">{cat.title}</span>
                    {showCount && (
                      <span className="text-xs text-slate-400">
                        {basePath === "/answers" ? cat.count : displaySampleCount(cat.count)}
                      </span>
                    )}
                  </Link>
                ))}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};
