import { useAuth } from "@/_core/hooks/useAuth";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { trpc } from "@/lib/trpc";
import { AssociationPublicMap } from "@/components/AssociationPublicMap";
import { getAssociationThematicDescription, getAssociationThematicLabel } from "@shared/associationThematics";
import { getFacebookEmbedUrl, getSocialHandle } from "@shared/socialLinks";
import { ArrowLeft, Building2, Facebook, Globe, Instagram, MapPinned } from "lucide-react";
import { Link, useParams } from "wouter";

function getPublicGeoStatus(entry: {
  latitude?: number | null;
  longitude?: number | null;
  geoSource?: string | null;
  geoPrecision?: string | null;
}) {
  const hasCoordinates = typeof entry.latitude === "number" && typeof entry.longitude === "number";

  if (!hasCoordinates || !entry.geoSource) {
    return "Non localisée";
  }

  if (entry.geoSource === "manual") {
    return "Position manuelle";
  }

  if (entry.geoPrecision === "commune_center" || entry.geoSource === "commune_center") {
    return "Centre de commune";
  }

  return "Adresse exacte";
}

export default function AssociationPublicProfile() {
  const { isAuthenticated } = useAuth();
  const params = useParams();
  const associationId = Number(params.id);
  const { data, isLoading, error } = trpc.associationDirectory.getMapEntry.useQuery(
    { id: associationId },
    { enabled: Number.isFinite(associationId) }
  );
  const { data: associationMapSettings } = trpc.settings.getAssociationMap.useQuery();
  const facebookEmbedUrl = data?.facebookUrl ? getFacebookEmbedUrl(data.facebookUrl) : null;
  const instagramHandle = data?.instagramUrl ? getSocialHandle(data.instagramUrl) : null;
  const backToDirectoryHref = isAuthenticated ? "/dashboard/associations" : "/associations";
  const backToMapHref = isAuthenticated ? "/dashboard/associations" : "/associations/carte";
  const backToDashboardHref = isAuthenticated ? "/dashboard" : "/";
  const geoStatus = data ? getPublicGeoStatus(data) : null;

  return (
    <div className="min-h-screen bg-muted/30">
      <header className="border-b border-border bg-white">
        <div className="container py-4">
          <div className="flex items-center gap-4">
            <Link href={backToDirectoryHref}>
              <Button variant="ghost" size="icon">
                <ArrowLeft className="h-5 w-5" />
              </Button>
            </Link>
            <div>
              <h1 className="text-xl font-bold">Fiche association</h1>
              <p className="text-sm text-muted-foreground">Présentation légère publique de l'association.</p>
            </div>
          </div>
        </div>
      </header>

      <main className="container py-8">
        {isLoading ? (
          <Card>
            <CardContent className="py-10 text-sm text-muted-foreground">Chargement de la fiche...</CardContent>
          </Card>
        ) : error || !data ? (
          <Card>
            <CardContent className="py-10 text-sm text-muted-foreground">
              Cette fiche n'est pas disponible publiquement.
            </CardContent>
          </Card>
        ) : (
          <Card className="max-w-3xl">
            <CardHeader>
              <div className="flex items-start justify-between gap-4">
                <div>
                  <CardTitle className="text-2xl">{data.nomAssociation}</CardTitle>
                  <CardDescription className="mt-2 flex items-center gap-2">
                    <MapPinned className="h-4 w-4" />
                    {data.ville || "Commune non renseignée"}
                  </CardDescription>
                </div>
                <Badge variant="outline">{data.registered ? "Inscrite sur le portail" : "Référencée dans l'annuaire"}</Badge>
              </div>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="rounded-lg border bg-primary/5 p-5">
                <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
                  <div>
                    <p className="text-sm font-medium text-primary">Carte des associations</p>
                    <p className="mt-1 text-sm text-muted-foreground">
                      Decouvre les associations des Savanes et leur implantation territoriale.
                    </p>
                  </div>
                  <Link href={backToMapHref}>
                    <Button variant="outline">
                      <MapPinned className="mr-2 h-4 w-4" />
                      Ouvrir la carte
                    </Button>
                  </Link>
                </div>
              </div>

              <div className="grid gap-4 md:grid-cols-2">
                <div className="rounded-lg border bg-muted/20 p-4">
                  <p className="text-xs uppercase tracking-wide text-muted-foreground">Type de localisation</p>
                  <p className="mt-2 font-medium">{geoStatus}</p>
                </div>
                <div className="rounded-lg border bg-muted/20 p-4">
                  <p className="text-xs uppercase tracking-wide text-muted-foreground">Source de la position</p>
                  <p className="mt-2 font-medium">{data.sourceLabel || data.geoSource || "Aucune source active"}</p>
                </div>
              </div>

              {typeof data.latitude === "number" && typeof data.longitude === "number" ? (
                <div className="space-y-3">
                  <div>
                    <p className="text-sm font-medium text-muted-foreground">Localisation interactive</p>
                    <p className="mt-1 text-sm text-muted-foreground">
                      Carte vectorielle MapLibre basée sur les coordonnées enregistrées dans l’annuaire.
                    </p>
                  </div>
                  <AssociationPublicMap
                    associations={[{
                      id: data.id,
                      nomAssociation: data.nomAssociation,
                      ville: data.ville ?? null,
                      thematiques: data.thematiques,
                      objetAssociation: data.objetAssociation ?? null,
                      siteWeb: data.siteWeb ?? null,
                      latitude: data.latitude,
                      longitude: data.longitude,
                      registered: data.registered,
                      publicUrl: `/associations/${data.id}`,
                    }]}
                    mode="annuaire"
                    selectedAssociationId={data.id}
                    styleUrl={associationMapSettings?.styleUrl}
                    heightClassName="h-[360px]"
                  />
                </div>
              ) : null}

              {data.thematiques?.length ? (
                <div className="rounded-lg border bg-muted/20 p-4">
                  <p className="text-xs uppercase tracking-wide text-muted-foreground">Thématique</p>
                  <div className="mt-2 flex flex-wrap gap-2">
                    {data.thematiques.map((value: string) => (
                      <span key={value} className="rounded-full bg-primary/10 px-3 py-1 text-sm text-primary">
                        {getAssociationThematicLabel(value)}
                      </span>
                    ))}
                  </div>
                  <div className="mt-2 space-y-1 text-sm text-muted-foreground">
                    {data.thematiques.map((value: string) => (
                      <p key={`${value}-description`}>{getAssociationThematicDescription(value)}</p>
                    ))}
                  </div>
                </div>
              ) : null}

              {(data.siret || data.rna) ? (
                <div className="grid gap-4 md:grid-cols-2">
                  <div className="rounded-lg border bg-muted/20 p-4">
                    <p className="text-xs uppercase tracking-wide text-muted-foreground">Numéro SIRET</p>
                    <p className="mt-2 font-medium">{data.siret || "-"}</p>
                  </div>
                  <div className="rounded-lg border bg-muted/20 p-4">
                    <p className="text-xs uppercase tracking-wide text-muted-foreground">Numéro RNA</p>
                    <p className="mt-2 font-medium">{data.rna || "-"}</p>
                  </div>
                </div>
              ) : null}

              <div>
                <p className="text-sm font-medium text-muted-foreground">Objet / activité</p>
                <p className="mt-2 leading-7">{data.objetAssociation || "Cette association n'a pas encore publié de description."}</p>
              </div>

              {data.siteWeb ? (
                <div>
                  <p className="text-sm font-medium text-muted-foreground">Site web</p>
                  <a href={data.siteWeb} target="_blank" rel="noreferrer" className="mt-2 inline-flex items-center text-primary hover:underline">
                    <Globe className="mr-2 h-4 w-4" />
                    Visiter le site
                  </a>
                </div>
              ) : null}

              {(data.facebookUrl || data.instagramUrl) ? (
                <div>
                  <p className="text-sm font-medium text-muted-foreground">Réseaux sociaux</p>
                  <div className="mt-2 flex flex-wrap gap-3">
                    {data.facebookUrl ? (
                      <a
                        href={data.facebookUrl}
                        target="_blank"
                        rel="noreferrer"
                        className="inline-flex items-center gap-2 rounded-full border px-3 py-2 text-sm hover:bg-muted/50"
                      >
                        <Facebook className="h-4 w-4 text-primary" />
                        Facebook
                      </a>
                    ) : null}
                    {data.instagramUrl ? (
                      <a
                        href={data.instagramUrl}
                        target="_blank"
                        rel="noreferrer"
                        className="inline-flex items-center gap-2 rounded-full border px-3 py-2 text-sm hover:bg-muted/50"
                      >
                        <Instagram className="h-4 w-4 text-primary" />
                        Instagram
                      </a>
                    ) : null}
                  </div>
                  <div className="mt-4 grid gap-4 lg:grid-cols-2">
                    {data.facebookUrl ? (
                      <div className="overflow-hidden rounded-lg border bg-white">
                        {facebookEmbedUrl ? (
                          <iframe
                            title={`Flux Facebook de ${data.nomAssociation}`}
                            src={facebookEmbedUrl}
                            width="100%"
                            height="380"
                            style={{ border: "none", overflow: "hidden" }}
                            scrolling="no"
                            allow="autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share"
                          />
                        ) : (
                          <div className="flex h-[380px] flex-col justify-between bg-[#1877f2] p-6 text-white">
                            <div>
                              <Facebook className="h-8 w-8" />
                              <p className="mt-4 text-lg font-semibold">Suivre l’association sur Facebook</p>
                              <p className="mt-2 text-sm text-white/85">
                                Ouvre la page officielle pour consulter les actualités et publications.
                              </p>
                            </div>
                            <a
                              href={data.facebookUrl}
                              target="_blank"
                              rel="noreferrer"
                              className="inline-flex w-fit items-center rounded-full bg-white px-4 py-2 text-sm font-medium text-[#1877f2]"
                            >
                              Ouvrir Facebook
                            </a>
                          </div>
                        )}
                      </div>
                    ) : null}

                    {data.instagramUrl ? (
                      <div className="rounded-lg border bg-[linear-gradient(135deg,#833ab4_0%,#fd1d1d_55%,#fcb045_100%)] p-[1px]">
                        <div className="flex h-full min-h-[220px] flex-col justify-between rounded-[calc(0.5rem-1px)] bg-background p-6">
                          <div>
                            <div className="inline-flex h-11 w-11 items-center justify-center rounded-full bg-[linear-gradient(135deg,#833ab4_0%,#fd1d1d_55%,#fcb045_100%)] text-white">
                              <Instagram className="h-5 w-5" />
                            </div>
                            <p className="mt-4 text-lg font-semibold">Instagram</p>
                            <p className="mt-2 text-sm text-muted-foreground">
                              {instagramHandle
                                ? `Retrouve l’association sur ${instagramHandle} pour suivre ses publications et moments forts.`
                                : "Retrouve l’association sur Instagram pour suivre ses publications et moments forts."}
                            </p>
                          </div>
                          <a
                            href={data.instagramUrl}
                            target="_blank"
                            rel="noreferrer"
                            className="inline-flex w-fit items-center rounded-full border px-4 py-2 text-sm font-medium hover:bg-muted/50"
                          >
                            Ouvrir Instagram
                          </a>
                        </div>
                      </div>
                    ) : null}
                  </div>
                </div>
              ) : null}

              <div className="flex flex-wrap gap-3">
                <Link href={backToMapHref}>
                  <Button variant="outline">
                    <MapPinned className="mr-2 h-4 w-4" />
                    {isAuthenticated ? "Retour à l'annuaire" : "Retour à la carte"}
                  </Button>
                </Link>
                <Link href={backToDashboardHref}>
                  <Button>
                    <Building2 className="mr-2 h-4 w-4" />
                    {isAuthenticated ? "Retour au tableau de bord" : "Revenir au portail"}
                  </Button>
                </Link>
              </div>
            </CardContent>
          </Card>
        )}
      </main>
    </div>
  );
}
