"use client";

import { useMemo, useState } from "react";
import type { AtlasCondition } from "@/data/atlas/conditions";
import type { AtlasRegion } from "@/data/atlas/regions";
import { ConditionCard } from "./ConditionCard";

type Props = {
  conditions: AtlasCondition[];
  regions: AtlasRegion[];
};

export function ConditionsBrowser({ conditions, regions }: Props) {
  const [query, setQuery] = useState("");
  const [regionFilter, setRegionFilter] = useState<string>("all");

  const regionNameBySlug = useMemo(() => {
    const map = new Map<string, string>();
    for (const r of regions) map.set(r.slug, r.name);
    return map;
  }, [regions]);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return conditions
      .filter((c) => (regionFilter === "all" ? true : c.regionSlug === regionFilter))
      .filter((c) => {
        if (!q) return true;
        return (
          c.name.toLowerCase().includes(q) ||
          c.summary.toLowerCase().includes(q) ||
          c.category.toLowerCase().includes(q)
        );
      })
      .sort((a, b) => a.name.localeCompare(b.name));
  }, [conditions, query, regionFilter]);

  return (
    <div>
      <div className="flex flex-col gap-4 rounded-xl border border-[var(--color-line)] bg-white p-5 md:flex-row md:items-center">
        <div className="flex-1">
          <label
            htmlFor="atlas-condition-search"
            className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]"
          >
            Search conditions
          </label>
          <input
            id="atlas-condition-search"
            type="search"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="e.g. ACL, rotator cuff, scoliosis"
            className="mt-2 block w-full rounded-lg border border-[var(--color-line)] bg-white px-4 py-2.5 text-[15px] text-[var(--color-ink)] outline-none transition-colors placeholder:text-[var(--color-slate)]/70 focus:border-[var(--color-blue)]"
          />
        </div>
        <div className="md:w-64">
          <label
            htmlFor="atlas-region-filter"
            className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]"
          >
            Region
          </label>
          <select
            id="atlas-region-filter"
            value={regionFilter}
            onChange={(e) => setRegionFilter(e.target.value)}
            className="mt-2 block w-full rounded-lg border border-[var(--color-line)] bg-white px-4 py-2.5 text-[15px] text-[var(--color-ink)] outline-none transition-colors focus:border-[var(--color-blue)]"
          >
            <option value="all">All regions</option>
            {regions.map((r) => (
              <option key={r.slug} value={r.slug}>
                {r.name}
              </option>
            ))}
          </select>
        </div>
      </div>

      <div className="mt-6 text-[13px] font-semibold text-[var(--color-slate)]">
        {filtered.length} of {conditions.length} conditions
      </div>

      {filtered.length === 0 ? (
        <div className="mt-10 rounded-xl border border-dashed border-[var(--color-line)] bg-[var(--color-mist)]/40 p-10 text-center">
          <p className="font-display text-[18px] font-bold text-[var(--color-ink)]">
            No conditions match that search.
          </p>
          <p className="mt-2 text-[14px] text-[var(--color-slate)]">
            Try a different keyword or clear the region filter.
          </p>
        </div>
      ) : (
        <div className="mt-8 grid gap-5 md:grid-cols-2 lg:grid-cols-3">
          {filtered.map((c, i) => (
            <ConditionCard
              key={c.slug}
              slug={c.slug}
              name={c.name}
              summary={c.summary}
              category={c.category}
              regionName={regionNameBySlug.get(c.regionSlug)}
              index={i}
            />
          ))}
        </div>
      )}
    </div>
  );
}
