'use client';
import React, {useState} from 'react';
import Link from 'next/link';
import {useTranslations} from 'next-intl';
import {FaChevronLeft, FaChevronRight, FaUser, FaUsers} from 'react-icons/fa';
import {getVilleActeurs} from '@/services/villeService';
import {getEpciActeurs} from '@/services/epciService';
import type {ActeurVille, ActeursVillePage} from '@/types/ville';
import './ActeursVille.css';
import {acteurHref} from '@/utils/acteurHref';

/** Territoire dont on liste les acteurs : une commune ou une intercommunalité (EPCI). */
export type ActeursCible = {type: 'ville' | 'epci'; id: string};

const CHARGEURS: Record<ActeursCible['type'], (id: string, page: number, itemsPerPage: number) => Promise<ActeursVillePage>> = {
  ville: getVilleActeurs,
  epci: getEpciActeurs,
};

interface ActeursVilleProps {
  cible: ActeursCible;
  locale: string;
  /** Première page, chargée côté serveur. */
  initial: ActeursVillePage;
}

/**
 * Bloc « acteurs » des fiches ville et EPCI : cartes avec photo, activité, lien vers la bonne fiche
 * et listes cliquables ; pagination quand le territoire compte beaucoup d'acteurs.
 */
export default function ActeursVille({cible, locale, initial}: ActeursVilleProps) {
  const t = useTranslations('VilleDetailsPage');
  const [page, setPage] = useState<ActeursVillePage>(initial);
  const [chargement, setChargement] = useState(false);

  if (page.total === 0 || page.items.length === 0) {
    return null;
  }

  const nbPages = Math.max(1, Math.ceil(page.total / page.itemsPerPage));

  const aller = async (numero: number) => {
    setChargement(true);
    const suivante = await CHARGEURS[cible.type](cible.id, numero, page.itemsPerPage);
    setPage(suivante.items.length > 0 ? suivante : {...page, page: numero});
    setChargement(false);
  };

  return (
    <div className="tk-acteurs-ville" aria-busy={chargement}>
      <div className="row g-4">
        {page.items.map((acteur) => (
          <div key={acteur.aenId} className="col-12 col-sm-6 col-lg-4">
            <article className={`tk-acteur-card${acteur.actif ? '' : ' tk-acteur-card--inactif'}`}>
              <Link href={acteurHref(locale, acteur)} className="tk-acteur-card__media">
                {acteur.photoUrl ? (
                  <img src={acteur.photoUrl} alt={acteur.aenLibelle} loading="lazy" />
                ) : (
                  <span className="tk-acteur-card__placeholder" data-testid="acteur-sans-photo" aria-hidden="true">
                    {acteur.type === 'artiste' ? <FaUser /> : <FaUsers />}
                  </span>
                )}
                <span className="tk-acteur-card__nom">{acteur.aenLibelle}</span>
              </Link>
              <div className="tk-acteur-card__body">
                <span className={`tk-acteur-card__etat ${acteur.actif ? 'tk-acteur-card__etat--actif' : 'tk-acteur-card__etat--inactif'}`}>
                  {t(acteur.actif ? 'active' : 'inactive')}
                </span>
                {acteur.listes.length > 0 && (
                  <ul className="tk-acteur-card__listes" aria-label={t('lists_label')}>
                    {acteur.listes.map((liste) => (
                      <li key={liste.lieId}>
                        <Link href={`/${locale}/listes/${liste.lieId}`} className="tk-acteur-card__liste">{liste.lieNom}</Link>
                      </li>
                    ))}
                  </ul>
                )}
              </div>
            </article>
          </div>
        ))}
      </div>
      {nbPages > 1 && (
        <nav className="tk-acteurs-ville__pagination" aria-label="pagination">
          <button type="button" className="btn btn-outline-secondary btn-sm" onClick={() => aller(page.page - 1)} disabled={page.page <= 1 || chargement} aria-label={t('previous_page')}>
            <FaChevronLeft aria-hidden="true" />
          </button>
          <span className="tk-acteurs-ville__page">{t('page_of', {page: page.page, total: nbPages})}</span>
          <button type="button" className="btn btn-outline-secondary btn-sm" onClick={() => aller(page.page + 1)} disabled={page.page >= nbPages || chargement} aria-label={t('next_page')}>
            <FaChevronRight aria-hidden="true" />
          </button>
        </nav>
      )}
    </div>
  );
}
