'use client';

import { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import { useTranslations, useLocale } from 'next-intl';
import { Container, Row, Col, Card, Badge, Image, Tab, Nav, Button } from 'react-bootstrap';
import Link from 'next/link';
import { useAuth } from '@/contexts/AuthContext';
import { getPublicProfile, sendProfileContactMessage } from '@/services/userService';
import ContactModal from '@/components/community/ContactModal';
import ProfilActivite from '@/components/community/ProfilActivite';
import {evenementHref} from '@/utils/evenementHref';
import {ensembleEvenementHref} from '@/utils/ensembleEvenementHref';
import {disciplineHref} from '@/utils/disciplineHref';

export default function PublicProfilePage() {
  const t = useTranslations('ProfilePage');
  const locale = useLocale();
  const params = useParams();
  const userId = Number(params.userId);
  const { isAuthenticated, loading: authLoading } = useAuth();

  const [profile, setProfile] = useState<Awaited<ReturnType<typeof getPublicProfile>> | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [showContactModal, setShowContactModal] = useState(false);

  useEffect(() => {
    if (!isAuthenticated || authLoading) return;

    const load = async () => {
      try {
        const data = await getPublicProfile(userId);
        setProfile(data);
      } catch {
        setError(t('profile_not_found'));
      } finally {
        setLoading(false);
      }
    };
    load();
  }, [userId, isAuthenticated, authLoading, t]);

  if (authLoading || loading) {
    return (
      <Container className="my-5 text-center">
        <p>...</p>
      </Container>
    );
  }

  if (!isAuthenticated) {
    return (
      <Container className="my-5 text-center">
        <p>{t('login_required')}</p>
        <Link href={`/${locale}/connexion`}>{t('go_to_login')}</Link>
      </Container>
    );
  }

  if (error || !profile) {
    return (
      <Container className="my-5 text-center">
        <p>{error || t('profile_not_found')}</p>
      </Container>
    );
  }

  const labelMap: Record<string, string> = {
    annuaire_entree: 'Groupe / Artiste',
    geolocale_ville: 'Ville',
    formation_discipline: 'Discipline',
    evenement: 'Evenement',
    evenement_ensemble: 'Festival',
  };

  const hrefMap: Record<string, string> = {
    annuaire_entree: `/${locale}/groupes/`,
    geolocale_ville: `/${locale}/ville/`,
    formation_discipline: `/${locale}/discipline/`,
    evenement: `/${locale}/evenements/`,
    evenement_ensemble: `/${locale}/festivite/`,
  };

  return (
    <div className="profile-page">
      <Container className="my-5">
        <Row>
          <Col xs={12} lg={3} className="text-center mb-4">
            <Image
              src={profile.avatarUrl || '/images/tk-default-avatar.svg'}
              alt={profile.pseudo}
              roundedCircle
              width={150}
              height={150}
              style={{ objectFit: 'cover' }}
            />
            <h3 className="mt-3">{profile.pseudo}</h3>
            {(profile.prenom || profile.patronyme) && (
              <p className="tk-text-muted">{profile.prenom} {profile.patronyme}</p>
            )}
            <Button
              variant="outline-primary"
              className="mt-2"
              onClick={() => setShowContactModal(true)}
            >
              {t('contact_send_message')}
            </Button>
          </Col>

          <Col xs={12} lg={9}>
            <Tab.Container defaultActiveKey="favoris">
              <Nav variant="pills" className="mb-3">
                <Nav.Item>
                  <Nav.Link eventKey="favoris">{t('tab_favorites')} ({profile.favoris.length})</Nav.Link>
                </Nav.Item>
                <Nav.Item>
                  <Nav.Link eventKey="events">{t('tab_events')} ({profile.participations.length})</Nav.Link>
                </Nav.Item>
                <Nav.Item>
                  <Nav.Link eventKey="activity">{t('tab_activity')}</Nav.Link>
                </Nav.Item>
              </Nav>

              <Tab.Content>
                <Tab.Pane eventKey="favoris">
                  {profile.favoris.length === 0 ? (
                    <p className="tk-text-muted">{t('no_favorites')}</p>
                  ) : (
                    <div className="d-flex flex-wrap gap-2">
                      {profile.favoris.map((fav) => {
                        const typeLabel = labelMap[fav.tableCible] || fav.tableCible;
                        const href = hrefMap[fav.tableCible];
                        const displayName = fav.libelle || `#${fav.cibleId}`;
                        return (
                          <Card key={fav.id} className="px-3 py-2">
                            <Badge bg="light" text="dark" className="mb-1">{typeLabel}</Badge>
                            {href ? (
                              <Link href={`${href}${fav.cibleId}`}>{displayName}</Link>
                            ) : (
                              <span>{displayName}</span>
                            )}
                          </Card>
                        );
                      })}
                    </div>
                  )}
                </Tab.Pane>

                <Tab.Pane eventKey="events">
                  {profile.participations.length === 0 ? (
                    <p className="tk-text-muted">{t('no_events')}</p>
                  ) : (
                    <div className="d-flex flex-wrap gap-2">
                      {profile.participations.map((p) => (
                        <Card key={p.id} className="px-3 py-2">
                          <Link href={evenementHref(locale, p.evenementId)}>
                            {p.libelle || `${t('event')} #${p.evenementId}`}
                          </Link>
                          {(p.date || p.lieu) && (
                            <small className="tk-text-muted">
                              {p.date && new Date(p.date).toLocaleDateString(locale)}
                              {p.date && p.lieu && ' · '}
                              {p.lieu}
                            </small>
                          )}
                        </Card>
                      ))}
                    </div>
                  )}
                </Tab.Pane>

                <Tab.Pane eventKey="activity">
                  <ProfilActivite
                    locale={locale}
                    commentaires={profile.commentaires ?? []}
                    annonces={profile.annonces ?? []}
                    covoiturages={profile.covoiturages ?? []}
                  />
                </Tab.Pane>
              </Tab.Content>
            </Tab.Container>
          </Col>
        </Row>
      </Container>

      <ContactModal
        show={showContactModal}
        onHide={() => setShowContactModal(false)}
        onSend={async (message) => {
          await sendProfileContactMessage(userId, message);
        }}
        recipientName={profile.pseudo}
      />
    </div>
  );
}
