"use client";

import { useMemo, useState } from "react";
import Image from "next/image";
import { Globe2, Sparkles } from "lucide-react";
import { Container } from "@/components/common/Container";
import { SectionHeading } from "@/components/common/SectionHeading";
import { SearchBar } from "@/components/common/SearchBar";
import { Reveal } from "@/components/motion/Reveal";
import { COUNTRIES } from "@/data/countries";
import { useTranslation } from "@/hooks/useTranslation";
import { useCurrencyInfo } from "@/hooks/queries/useSettings";
import type { ApiCurrency, ApiImagePaths } from "@/api/sendRemittance.api";

function flagUrl(cur: ApiCurrency, paths: ApiImagePaths): string {
  return `${paths.base_url}${paths.path_location}/${cur.flag}`;
}

interface CountryItem {
  key: string;
  name: string;
  currency: string;
  flagImg?: string;
  flag?: string;
  popular?: boolean;
}

export function SupportedCountries() {
  const { t } = useTranslation();
  const [query, setQuery] = useState("");
  const { data: apiData } = useCurrencyInfo();

  const countries = useMemo<CountryItem[]>(() => {
    if (apiData?.receiver_currency?.length) {
      const seen = new Set<string>();
      return apiData.receiver_currency.reduce<CountryItem[]>((acc, cur) => {
        const dedupeKey = `${cur.country}-${cur.code}`;
        if (seen.has(dedupeKey)) return acc;
        seen.add(dedupeKey);
        acc.push({
          key: String(cur.id),
          name: cur.country,
          currency: cur.code,
          flagImg: flagUrl(cur, apiData.image_paths),
        });
        return acc;
      }, []);
    }
    return COUNTRIES.map((c) => ({
      key: c.code,
      name: c.name,
      currency: c.currency,
      flag: c.flag,
      popular: c.popular,
    }));
  }, [apiData]);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return countries;
    return countries.filter(
      (c) =>
        c.name.toLowerCase().includes(q) ||
        c.currency.toLowerCase().includes(q),
    );
  }, [query, countries]);

  return (
    <section className="section">
      <Container>
        <SectionHeading
          eyebrow={t("countries.eyebrow")}
          title={t("countries.title")}
          subtitle={t("countries.subtitle")}
        />
        <Reveal delay={0.15} className="mx-auto mt-10 max-w-xl">
          <SearchBar
            value={query}
            onChange={setQuery}
            placeholder={t("countries.searchPlaceholder")}
            ariaLabel={t("countries.searchPlaceholder")}
          />
        </Reveal>

        {filtered.length === 0 ? (
          <Reveal className="mx-auto mt-12 flex max-w-md flex-col items-center justify-center gap-3 rounded-3xl border border-dashed border-slate-200 bg-white/60 p-12 text-center dark:border-white/[0.06] dark:bg-white/[0.04]">
            <Globe2 className="h-10 w-10 text-slate-400" />
            <p className="text-sm text-slate-500 dark:text-slate-400">
              {t("countries.noResults")}
            </p>
          </Reveal>
        ) : (
          <div className="mt-12 grid grid-cols-2 gap-3 sm:grid-cols-3 sm:gap-4 lg:grid-cols-4">
            {filtered.map((country, idx) => (
              <Reveal key={country.key} delay={(idx % 6) * 0.04}>
                <div className="group relative flex h-full items-center gap-3 overflow-hidden rounded-2xl border border-slate-200/70 bg-white/80 p-4 transition-all duration-300 ease-snappy hover:-translate-y-0.5 hover:border-brand-300 hover:shadow-soft dark:border-white/[0.06] dark:bg-white/[0.04] dark:hover:border-brand-400/40">
                  {country.flagImg ? (
                    <Image
                      src={country.flagImg}
                      alt={country.name}
                      width={32}
                      height={32}
                      className="h-8 w-8 shrink-0 rounded-full object-cover transition-transform duration-300 group-hover:scale-105"
                    />
                  ) : (
                    <span
                      className="text-2xl transition-transform duration-300 group-hover:scale-105"
                      aria-hidden
                    >
                      {country.flag}
                    </span>
                  )}
                  <div className="min-w-0 flex-1">
                    <p className="truncate text-sm font-semibold text-slate-900 dark:text-white">
                      {country.name}
                    </p>
                    <p className="text-xs text-slate-500 dark:text-slate-400">
                      {country.currency}
                    </p>
                  </div>
                  {country.popular && (
                    <span
                      aria-label={t("countries.popularAria")}
                      className="absolute -top-px end-3 rounded-b-md bg-gradient-to-b from-amber-400 to-amber-500 px-1.5 py-0.5 text-2xs font-bold uppercase tracking-wider text-white shadow-sm"
                    >
                      <Sparkles className="inline h-2.5 w-2.5" />
                    </span>
                  )}
                </div>
              </Reveal>
            ))}
          </div>
        )}

        <Reveal className="mx-auto mt-10 max-w-xl text-center">
          <p className="text-sm text-slate-500 dark:text-slate-400">
            {t("countries.footnote")}
          </p>
        </Reveal>
      </Container>
    </section>
  );
}
