import React from 'react';
import Link from 'next/link';
import {stageHref} from '@/utils/stageHref';
import {Col, Container, Row} from 'react-bootstrap';
import {NextIntlClientProvider} from 'next-intl';
import {
  FaArrowLeft,
  FaCalendarAlt,
  FaClock,
  FaEuroSign,
  FaGraduationCap,
  FaMapMarkerAlt,
  FaUsers,
} from 'react-icons/fa';

import ErrorCustomComponent from '@/components/global/ErrorCustomComponent';
import Lieu from '@/components/Evenements/EvenementDetails/Lieux/Lieu';
import PartageSocialDiv from '@/components/Evenements/EvenementDetails/PartageSocialDiv/PartageSocialDiv';
import initTranslations from '@/i18n';
import {getFormationSession} from '@/services/sessionService';
import {getFormationStage} from '@/services/stageService';
import {resolveSessionLocation} from '@/utils/stageAddress';

import 'leaflet/dist/leaflet.css';

export default async function Page(props: {
  params: Promise<{locale: string; fssId: string}>;
}) {
  const {locale, fssId} = await props.params;
  const {messages} = await initTranslations({locale});

  if (!messages) {
    return (
      <ErrorCustomComponent
        message="Messages undefined in session details page"
        statusCode={500}
      />
    );
  }

  try {
    const session = await getFormationSession(fssId);
    const stage = await getFormationStage(String(session.fssFst.fstId));
    const location = resolveSessionLocation(session, stage);

    const formatDate = (date: string) =>
      new Intl.DateTimeFormat(locale, {dateStyle: 'full'}).format(new Date(date));

    const formatHour = (iso: string) => {
      const d = new Date(iso);
      return `${d.getUTCHours()}H${String(d.getUTCMinutes()).padStart(2, '0')}`;
    };

    return (
      <NextIntlClientProvider locale={locale} messages={messages}>
        <section className="tk-detail-hero">
          <div className="tk-detail-hero-bg"></div>
          <Container className="tk-detail-hero-content">
            <Row className="g-4">
              <Col lg={8}>
                <Link
                  href={stageHref(locale, stage.fstId, stage.fstEve?.eveLibelle)}
                  className="tk-badge tk-badge-outline-green mb-3 d-inline-flex align-items-center"
                >
                  <FaArrowLeft className="me-2" />
                  {stage.fstEve.eveLibelle || 'Retour au stage'}
                </Link>

                <span className="tk-badge tk-badge-success mb-3 ms-2">
                  <FaGraduationCap className="me-2" />
                  Session
                </span>

                <h1 className="tk-detail-hero-title">
                  {session.fssFod.fodNom}
                  {session.fssSoustitre && (
                    <span className="tk-detail-hero-subtitle d-block fs-5 mt-2">
                      {session.fssSoustitre}
                    </span>
                  )}
                </h1>

                <div className="tk-hero-meta">
                  <div className="tk-hero-meta-item">
                    <FaCalendarAlt className="tk-hero-meta-icon" />
                    <span>
                      {formatDate(session.fssDateDebut)}
                      {session.fssDateFin && session.fssDateFin !== session.fssDateDebut
                        ? ` → ${formatDate(session.fssDateFin)}`
                        : ''}
                    </span>
                  </div>
                  {session.fssHeureDebut && (
                    <div className="tk-hero-meta-item">
                      <FaClock className="tk-hero-meta-icon" />
                      <span>
                        {formatHour(session.fssHeureDebut)}
                        {session.fssHeureFin
                          ? ` - ${formatHour(session.fssHeureFin)}`
                          : ''}
                      </span>
                    </div>
                  )}
                  <div className="tk-hero-meta-item">
                    <FaMapMarkerAlt className="tk-hero-meta-icon" />
                    <span>{location.libelle || location.placeName}</span>
                  </div>
                  {session.fssTarifs && (
                    <div className="tk-hero-meta-item">
                      <FaEuroSign className="tk-hero-meta-icon" />
                      <span>{session.fssTarifs}</span>
                    </div>
                  )}
                </div>

                {session.fssDescription && (
                  <p className="tk-hero-description mt-4">
                    {session.fssDescription}
                  </p>
                )}
              </Col>

              <Col lg={4}>
                <div className="tk-side-info">
                  <PartageSocialDiv />
                </div>
              </Col>
            </Row>
          </Container>
        </section>

        <section className="tk-section">
          <Container>
            {session.animateurs.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">
                      <FaUsers />
                    </span>
                    Animateurs
                  </h2>
                </div>
                <div className="tk-section-card-body">
                  <div className="tk-animateurs-list">
                    {session.animateurs.map((animateur, idx) => (
                      <div key={idx} className="tk-animateur-item">
                        <span className="tk-animateur-name">
                          {animateur.aenLibelle}
                        </span>
                        {animateur.aenBio && (
                          <p className="tk-animateur-bio">{animateur.aenBio}</p>
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            )}

            <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">
                    <FaMapMarkerAlt />
                  </span>
                  Lieu
                </h2>
              </div>
              <div className="tk-section-card-body">
                <Lieu
                  adresse={location.libelle}
                  capacity={location.capacity}
                  fst
                  geoX={location.geoX}
                  geoY={location.geoY}
                  geoZ={location.geoZ}
                  parking
                  parquet
                  placeName={location.placeName}
                />
              </div>
            </div>
          </Container>
        </section>
      </NextIntlClientProvider>
    );
  } catch (error) {
    const errorMessage =
      error instanceof Error ? error.message : 'An error occurred';
    return (
      <ErrorCustomComponent
        message={`Error loading session: ${errorMessage}`}
        statusCode={404}
      />
    );
  }
}
