import React from 'react';
import Link from 'next/link';
import {Col, Container, Row} from 'react-bootstrap';
import {
  FaBuilding,
  FaUsers,
  FaCalendarAlt,
  FaMapMarkerAlt,
  FaGlobe,
  FaExternalLinkAlt,
  FaArrowRight,
} from 'react-icons/fa';

import EpciActeursMap from '@/components/Epci/EpciActeursMap';
import EpciLogoDisplay from '@/components/Epci/EpciLogoDisplay';
import EventCardBootstrap from '@/components/Evenements/EvenementCardBootstrap/EventCardBootstrap';
import ErrorCustomComponent from '@/components/global/ErrorCustomComponent';
import VisitCounter from '@/components/shared/VisitCounter/VisitCounter';
import ActeursVille from '@/components/Ville/ActeursVille';
import initTranslations from '@/i18n';
import {getEpci, getEpciActeurs, getEpciActeursCarte, getEpciEvents, getEpciStats} from '@/services/epciService';
import {ficheMetadata} from '@/utils/ficheTitle';
import {villeHref} from '@/utils/villeHref';

type PageProps = {params: Promise<{locale: string; epciId: string}>};

export async function generateMetadata(props: PageProps) {
  const {epciId} = await props.params;

  return ficheMetadata(async () => (await getEpci(epciId)).suaNom);
}

export default async function EpciDetailPage(
  props: {
    params: Promise<{locale: string; epciId: string}>;
  }
) {
  const params = await props.params;
  const {locale, epciId} = params;
  const {messages} = await initTranslations({locale});
  const t = (messages?.EpciDetailsPage ?? {}) as Record<string, string>;

  try {
    const [epci, stats, evenements, acteurs, carte] = await Promise.all([
      getEpci(epciId),
      getEpciStats(epciId),
      getEpciEvents(epciId),
      getEpciActeurs(epciId),
      getEpciActeursCarte(epciId),
    ]);
    const lienAgenda = `/${locale}/evenements?epci=${epciId}`;
    const tousLesEvenements = (t.see_all_events_of || 'Tous les événements de {epci}').replace('{epci}', epci.suaNom);

    return (
      <>
        {/* Hero Section */}
        <section className="tk-detail-hero">
          <div className="tk-detail-hero-bg"></div>
          <Container className="tk-detail-hero-content">
            <Row className="align-items-center g-4 justify-content-center">
              <Col xs={8} sm={6} md={4} lg={3}>
                <div className="tk-epci-detail-logo">
                  <EpciLogoDisplay
                    suaId={epci.suaId}
                    suaNom={epci.suaNom}
                    suaPhrasePartenaire={epci.suaPhrasePartenaire}
                    suaUrl={epci.suaUrl}
                  />
                </div>
              </Col>

              <Col xs={12} md={8} lg={9}>
                <div className="tk-detail-hero-info text-center text-md-start">
                  <span className="tk-badge tk-badge-success mb-3">
                    <FaBuilding className="me-2" />
                    EPCI
                  </span>
                  <h1 className="tk-detail-hero-title">{epci.suaNom}</h1>
                  <div className="mb-3">
                    <VisitCounter tableCible="geolocale_subdivision_autre" cibleId={epci.suaId} />
                  </div>

                  {epci.suaNomCommunication && (
                    <p className="text-white-50 mb-3">
                      {epci.suaNomCommunication}
                    </p>
                  )}

                  {epci.suaUrl && (
                    <a
                      href={epci.suaUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="tk-badge tk-badge-outline-green mb-3"
                      style={{textDecoration: 'none'}}
                    >
                      <FaGlobe className="me-1" />
                      Site web
                      <FaExternalLinkAlt className="ms-1" style={{fontSize: '0.7em'}} />
                    </a>
                  )}

                  {epci.refExterne && (
                    <p className="text-white-50 mb-0" style={{fontSize: '0.85rem'}}>
                      Réf. externe : {epci.refExterne}
                    </p>
                  )}

                  {/* Stats */}
                  <div className="tk-stats-row mt-4">
                    {stats.communes > 0 && (
                      <div className="tk-stat">
                        <FaMapMarkerAlt className="tk-stat-icon" />
                        <span className="tk-stat-value">{stats.communes}</span>
                        <span className="tk-stat-label">communes</span>
                      </div>
                    )}
                    {stats.acteurs > 0 && (
                      <div className="tk-stat">
                        <FaUsers className="tk-stat-icon" />
                        <span className="tk-stat-value">{stats.acteurs}</span>
                        <span className="tk-stat-label">acteurs</span>
                      </div>
                    )}
                    {stats.evenements > 0 && (
                      <div className="tk-stat">
                        <FaCalendarAlt className="tk-stat-icon" />
                        <span className="tk-stat-value">{stats.evenements}</span>
                        <span className="tk-stat-label">événements</span>
                      </div>
                    )}
                    {stats.lieux > 0 && (
                      <div className="tk-stat">
                        <FaBuilding className="tk-stat-icon" />
                        <span className="tk-stat-value">{stats.lieux}</span>
                        <span className="tk-stat-label">lieux</span>
                      </div>
                    )}
                  </div>
                </div>
              </Col>
            </Row>
          </Container>
        </section>

        {/* Main Content */}
        <section className="tk-section">
          <Container>
            {/* Communes Section */}
            {epci.villes && epci.villes.length > 0 && (
              <div className="tk-section-card">
                <div className="tk-section-card-header">
                  <h2 className="tk-section-card-title">
                    <span className="tk-section-card-title-icon tk-section-card-title-icon-green">
                      <FaMapMarkerAlt />
                    </span>
                    Communes ({epci.villes.length})
                  </h2>
                </div>
                <div className="tk-section-card-body">
                  <Row className="g-3">
                    {epci.villes.map((ville) => (
                      <Col key={ville.vilId} xs={12} sm={6} md={4} lg={3}>
                        <Link
                          href={villeHref(locale, ville.vilId, ville.vilNom)}
                          className="tk-link-card"
                        >
                          <FaMapMarkerAlt style={{color: 'var(--tk-green)', flexShrink: 0}} />
                          <span className="tk-link-card-text">
                            {ville.vilNom}
                            {ville.vilCodepostal && (
                              <small className="d-block" style={{color: 'var(--tk-gray-500)', fontSize: '0.8em'}}>
                                {ville.vilCodepostal}
                              </small>
                            )}
                          </span>
                          <FaArrowRight className="tk-link-card-arrow" />
                        </Link>
                      </Col>
                    ))}
                  </Row>
                </div>
              </div>
            )}

            {/* Carte de l'EPCI et de ses acteurs actifs (spec L171) */}
            <EpciActeursMap locale={locale} carte={carte} />

            {/* Bloc agenda : toujours présent, lien vers l'agenda filtré sur l'EPCI (spec L172) */}
            <div className="tk-section-card" data-testid="epci-agenda">
              <div className="tk-section-card-header">
                <h2 className="tk-section-card-title">
                  <span className="tk-section-card-title-icon tk-section-card-title-icon-orange">
                    <FaCalendarAlt />
                  </span>
                  {t.next_events || 'Prochains événements'}
                </h2>
              </div>
              <div className="tk-section-card-body">
                {evenements.length > 0 ? (
                  <Row className="g-4">
                    {evenements.map((event) => (
                      <Col key={event.eveId} xs={12} md={6}>
                        <EventCardBootstrap
                          eveDate={event.eveDate}
                          eveId={event.eveId}
                          groupes={event.aenParticipants}
                          tevLibelle={event.eveTev.tevLibelle}
                        />
                      </Col>
                    ))}
                  </Row>
                ) : (
                  <p className="text-muted">{t.no_upcoming_events || 'Aucun événement à venir'}</p>
                )}
                <div className={`text-center ${evenements.length > 0 ? 'mt-5' : 'mt-3'}`}>
                  <Link className="tk-btn tk-btn-primary" href={lienAgenda}>
                    {tousLesEvenements}
                    <FaArrowRight className="ms-2" />
                  </Link>
                </div>
              </div>
            </div>

            {/* Acteurs des communes de l'EPCI, paginés (spec L173) */}
            {acteurs.total > 0 && (
              <div className="tk-section-card">
                <div className="tk-section-card-header">
                  <h2 className="tk-section-card-title">
                    <span className="tk-section-card-title-icon tk-section-card-title-icon-green">
                      <FaUsers />
                    </span>
                    {t.actors || "Acteurs de l'intercommunalité"}
                    <span className="tk-section-card-count ms-2">({acteurs.total})</span>
                  </h2>
                </div>
                <div className="tk-section-card-body">
                  <ActeursVille cible={{type: 'epci', id: epciId}} locale={locale} initial={acteurs} />
                </div>
              </div>
            )}

            {/* Stats détaillées */}
            {(stats.evenements > 0 || stats.evenementsN1 > 0) && (
              <div className="tk-section-card">
                <div className="tk-section-card-header">
                  <h2 className="tk-section-card-title">
                    <span className="tk-section-card-title-icon tk-section-card-title-icon-orange">
                      <FaCalendarAlt />
                    </span>
                    Activité événementielle
                  </h2>
                </div>
                <div className="tk-section-card-body">
                  <Row className="g-4 text-center">
                    <Col xs={6}>
                      <div className="d-flex flex-column align-items-center">
                        <span className="tk-stat-value fs-2 text-dark">
                          {stats.evenements}
                        </span>
                        <span className="tk-stat-label text-muted">
                          événements cette année
                        </span>
                      </div>
                    </Col>
                    <Col xs={6}>
                      <div className="d-flex flex-column align-items-center">
                        <span className="tk-stat-value fs-2 text-dark">
                          {stats.evenementsN1}
                        </span>
                        <span className="tk-stat-label text-muted">
                          événements l&apos;année précédente
                        </span>
                      </div>
                    </Col>
                  </Row>
                </div>
              </div>
            )}
          </Container>
        </section>
      </>
    );
  } catch (error) {
    const errorMessage =
      error instanceof Error ? error.message : 'An error occurred';
    const statusCode = errorMessage.includes('not found') ? 404 : 500;
    return (
      <ErrorCustomComponent
        message={`Erreur lors du chargement de l'EPCI : ${errorMessage}`}
        statusCode={statusCode}
      />
    );
  }
}
