"use client";

import { useState } from "react";
import Link from "next/link";

interface Country {
  id: number;
  name: string;
  slug: string;
  count: number;
}

export function SidebarCountryList({ countries }: { countries: Country[] }) {
  const [expanded, setExpanded] = useState(false);
  const [search, setSearch] = useState("");

  const filtered = search
    ? countries.filter((c) => c.name.toLowerCase().includes(search.toLowerCase()))
    : countries;

  return (
    <div className="mt-2">
      <button
        onClick={() => setExpanded(!expanded)}
        className="text-xs text-text-muted hover:text-white flex items-center gap-1 py-1.5 px-2 w-full"
      >
        <svg
          className={`w-3 h-3 transition-transform ${expanded ? "rotate-90" : ""}`}
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
        </svg>
        {expanded ? "Hide" : "Show"} {countries.length} more countries
      </button>

      {expanded && (
        <div className="mt-1">
          <input
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search countries..."
            className="w-full text-xs bg-surface-light border border-surface-light rounded px-2 py-1.5 text-text placeholder-text-muted focus:outline-none focus:border-primary mb-1"
          />
          <ul className="max-h-48 overflow-y-auto space-y-0.5">
            {filtered.slice(0, 50).map((country) => (
              <li key={country.id}>
                <Link
                  href={`/escorts/${country.slug}`}
                  className="text-xs text-text-muted hover:text-white flex items-center justify-between py-1 px-2 rounded hover:bg-surface-light"
                >
                  <span>{country.name}</span>
                  {country.count > 0 && (
                    <span className="text-xs text-text-muted">{country.count}</span>
                  )}
                </Link>
              </li>
            ))}
            {filtered.length === 0 && (
              <li className="text-xs text-text-muted py-2 px-2">No countries found</li>
            )}
          </ul>
        </div>
      )}
    </div>
  );
}
