"use client";

import { useMemo, useState } from "react";
import AstrologerCard from "./AstrologerCard";
import Image from "next/image";
import { FaSearch } from "react-icons/fa";

interface Props {
  astrologers: any[];
}

const splitSkills = (value?: string): string[] =>
  (value || "")
    .split(",")
    .map((k) => k.trim())
    .filter(Boolean);

export default function AstrologerList({
  astrologers = [],
}: Props) {
  const [search, setSearch] = useState("");
  const [category, setCategory] = useState("All");

  // Filter chips come from the astrologers' own skills (allSkill is a
  // comma-separated string, e.g. "Career, Life Coach, Numerology"),
  // most common first. The old chips read a `category` field the API
  // never returns, so only "All" ever showed.
  const categories = useMemo(() => {
    const counts = new Map<string, { label: string; count: number }>();

    astrologers.forEach((x) => {
      new Set(splitSkills(x.allSkill || x.primarySkill).map((k) => k.toLowerCase())).forEach(
        (key) => {
          const label = splitSkills(x.allSkill || x.primarySkill).find(
            (k) => k.toLowerCase() === key,
          )!;
          const entry = counts.get(key);
          if (entry) entry.count += 1;
          else counts.set(key, { label, count: 1 });
        },
      );
    });

    const skills = Array.from(counts.values())
      .sort((a, b) => b.count - a.count || a.label.localeCompare(b.label))
      .map((entry) => entry.label);

    return ["All", ...skills];
  }, [astrologers]);

  // A periodic list refresh can drop the selected skill — fall back
  // to All instead of showing an empty list with no active chip.
  const activeCategory = categories.includes(category) ? category : "All";

  // Filtered Data
  const filtered = useMemo(() => {
    const term = search.trim().toLowerCase();

    return astrologers.filter((item) => {
      // Name, any skill (primary or all) or any known language.
      const matchSearch =
        !term ||
        [item.name, item.primarySkill, item.allSkill, item.languageKnown].some((field) =>
          String(field ?? "").toLowerCase().includes(term),
        );

      const matchCategory =
        activeCategory === "All" ||
        splitSkills(item.allSkill || item.primarySkill).some(
          (k) => k.toLowerCase() === activeCategory.toLowerCase(),
        );

      return matchSearch && matchCategory;
    });
  }, [astrologers, search, activeCategory]);

  return (
    <>
      {/* Search + Category */}

      <div className="row mb-4 align-items-center">

        <div className="col-lg-4 mb-3 mb-lg-0">

          <div className="position-relative search-box">

            <FaSearch className="search-icon" />

            <input
              type="text"
              className="form-control search-input ps-5"
              placeholder="Search by name, skill or language..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
            />

          </div>

        </div>

        <div className="col-lg-8">

          <div
            className="d-flex gap-2 flex-nowrap pb-1"
            style={{ overflowX: "auto", scrollbarWidth: "none" }}
          >

            {categories.map((cat) => (
              <button
                key={cat}
                className={`btn rounded-pill flex-shrink-0 text-nowrap ${
                  activeCategory === cat
                    ? "btn-warning"
                    : "btn-outline-light"
                }`}
                onClick={() =>
                  setCategory(cat)
                }
              >
                {cat}
              </button>
            ))}

          </div>

        </div>

      </div>

      {filtered.length === 0 ? (
        <div className="text-center py-5 text-white">
          No Astrologers Found
        </div>
      ) : (
        <div className="row g-4">

          {filtered.map((item) => (
            <div
              className="col-lg-4 col-md-6"
              key={item.id}
            >
              <AstrologerCard astrologer={item} />
            </div>
          ))}

        </div>
      )}
    </>
  );
}