"use client";

import { useSearchParams } from "next/navigation";
import DetailShell, { EventDetailBody, PlaceDetailBody, type SocialLink } from "./Detail";
import { useActivityDetail } from "@/store/entertainment";
import { useCafeDetail, useRestaurantDetail } from "@/store/dining";
import { useEventDetail, useVenueDetail as useVenueDetailStore } from "@/store/events";
import { venueTags } from "@/components/events/VenueDirectory";
import { useStayDetail } from "@/store/home";
import { useDealDetail } from "@/store/deals";
import { useAirportDetail, useEmbassyDetail, useMedicalCenterDetail, useMedicalDestinationDetail, useTransportDetail } from "@/store/services";
import { subtypeOf, type MedicalCenter, type ServicePlace } from "@/lib/api/services";
import DealBody from "@/components/deals/DealBody";
import { useDestinationDetail, useNeighborhoodDetail, useVenueDetail } from "@/store/explore";
import { useExperienceDetail, useGuideDetail } from "@/store/guides";
import { ExperienceDetailBody, GuideDetailBody } from "@/components/explore/GuideBodies";

const FOOD_LIST = "/life-and-fun/food-and-beverage";

function socialLinks(s: { instagram_url: string | null; facebook_url: string | null }): SocialLink[] {
  return [
    ...(s.instagram_url ? [{ kind: "instagram" as const, label: "Instagram", href: s.instagram_url }] : []),
    ...(s.facebook_url ? [{ kind: "facebook" as const, label: "Facebook", href: s.facebook_url }] : []),
  ];
}

// Each wrapper reads ?id= from the URL. Static export has no server to resolve /restaurants/:id, so details use the query string.

export function RestaurantDetailPage() {
  const id = useSearchParams().get("id");
  const detail = useRestaurantDetail();
  const flags = (item: NonNullable<typeof detail.item>) => [
    ...item.subtype.cuisines.map((c) => c.name),
    ...(item.subtype.has_delivery ? ["Delivery"] : []),
    ...(item.subtype.has_booking ? ["Booking"] : []),
  ];
  return (
    <DetailShell
      id={id}
      detail={detail}
      eyebrow="Restaurant"
      backHref={`${FOOD_LIST}?type=restaurants`}
      backLabel="Back to restaurants"
      render={(item) => (
        <PlaceDetailBody
          item={item}
          tags={flags(item)}
          links={socialLinks(item.subtype)}
        />
      )}
    />
  );
}

export function CafeDetailPage() {
  const id = useSearchParams().get("id");
  const detail = useCafeDetail();
  return (
    <DetailShell
      id={id}
      detail={detail}
      eyebrow="Café"
      backHref={`${FOOD_LIST}?type=cafes`}
      backLabel="Back to cafés"
      render={(item) => {
        const tags = [...(item.subtype.has_delivery ? ["Delivery"] : []), ...(item.subtype.has_booking ? ["Booking"] : [])];
        return <PlaceDetailBody item={item} tags={tags} links={socialLinks(item.subtype)} />;
      }}
    />
  );
}

export function EventDetailPage() {
  const id = useSearchParams().get("id");
  const detail = useEventDetail();
  return (
    <DetailShell
      id={id}
      detail={detail}
      eyebrow="Festival and event"
      backHref="/life-and-fun/festivals-and-events"
      backLabel="Back to festivals and events"
      render={(item) => <EventDetailBody item={item} />}
    />
  );
}

export function ActivityDetailPage() {
  const id = useSearchParams().get("id");
  const detail = useActivityDetail();
  return (
    <DetailShell
      id={id}
      detail={detail}
      eyebrow="Experience"
      backHref="/life-and-fun/experiences"
      backLabel="Back to experiences"
      render={(item) => <PlaceDetailBody item={item} tags={item.subtype.categories.map((c) => c.name)} />}
    />
  );
}

export function StayDetailPage() {
  const id = useSearchParams().get("id");
  const detail = useStayDetail();
  return (
    <DetailShell
      id={id}
      detail={detail}
      eyebrow="Place to stay"
      backHref="/#stays"
      backLabel="Back to places to stay"
      render={(item) => {
        const sub = item.subtype;
        const tags = [
          ...(sub.place_type ? [sub.place_type.name] : []),
          ...(sub.star_rating ? [`${sub.star_rating} stars`] : []),
          ...sub.features.map((f) => f.name),
        ];
        return <PlaceDetailBody item={item} tags={tags} />;
      }}
    />
  );
}

export function GuideDetailPage() {
  const id = useSearchParams().get("id");
  const detail = useGuideDetail();
  return <DetailShell id={id} detail={detail} eyebrow="Tour guide" backHref="/explore/tour-guides" backLabel="Back to tour guides" render={(item) => <GuideDetailBody item={item} />} />;
}

export function GuidedExperienceDetailPage() {
  const id = useSearchParams().get("id");
  const detail = useExperienceDetail();
  return <DetailShell id={id} detail={detail} eyebrow="Guided experience" backHref="/explore/tour-guides" backLabel="Back to tour guides" render={(item) => <ExperienceDetailBody item={item} />} />;
}

const EXPLORE = {
  destination: { eyebrow: "Destination", back: "/explore/history-and-heritage", label: "Back to history and heritage" },
  "cultural-venue": { eyebrow: "Cultural venue", back: "/explore/arts-and-culture", label: "Back to arts and culture" },
  neighborhood: { eyebrow: "Neighborhood", back: "/explore/neighborhoods", label: "Back to neighborhoods" },
} as const;

/** One page for all Explore places: ?kind=destination|cultural-venue|neighborhood&id=. All three stores exist; only the matching one loads. */
export function ExplorePlaceDetailPage() {
  const params = useSearchParams();
  const raw = params.get("kind") ?? "";
  const kind = raw in EXPLORE ? (raw as keyof typeof EXPLORE) : "destination";
  const detail = { destination: useDestinationDetail(), "cultural-venue": useVenueDetail(), neighborhood: useNeighborhoodDetail() }[kind];
  const m = EXPLORE[kind];
  const type = (item: { subtype: unknown }) => {
    const t = Array.isArray(item.subtype) ? null : (item.subtype as { destination_type?: string | null }).destination_type;
    return t ? [t.charAt(0).toUpperCase() + t.slice(1)] : [];
  };
  return <DetailShell id={params.get("id")} detail={detail} eyebrow={m.eyebrow} backHref={m.back} backLabel={m.label} render={(item) => <PlaceDetailBody item={item} tags={type(item)} />} />;
}

export function DealDetailPage() {
  const id = useSearchParams().get("id");
  const detail = useDealDetail();
  return <DetailShell id={id} detail={detail} eyebrow="Deal" backHref="/deals/accommodation-and-entertainment" backLabel="Back to deals" render={(item) => <DealBody item={item} />} />;
}

const SERVICE = {
  embassy: { eyebrow: "Embassy", back: "/services/embassies", label: "Back to embassies" },
  airport: { eyebrow: "Airport", back: "/services/transport", label: "Back to airports and transport" },
  transport: { eyebrow: "Transport company", back: "/services/transport", label: "Back to airports and transport" },
  "medical-center": { eyebrow: "Medical center", back: "/services/medical-tourism", label: "Back to medical tourism" },
  "medical-destination": { eyebrow: "Medical tourism destination", back: "/services/medical-tourism#destinations", label: "Back to medical tourism" },
} as const;
const CATEGORY: Record<string, string> = { airline: "Airline", travel_agency: "Travel agency" };

function medicalTags(sub: MedicalCenter["subtype"]) {
  return [
    ...sub.specialties.map((s) => s.name),
    ...(sub.doctor_in_charge ? [`Lead: ${sub.doctor_in_charge}`] : []),
    ...(sub.experience_years ? [`${sub.experience_years} years of experience`] : []),
  ];
}

/** One page for embassies, airports, transport companies and medical places: ?kind=embassy|airport|transport|medical-center|medical-destination&id=. */
export function ServicePlaceDetailPage() {
  const params = useSearchParams();
  const raw = params.get("kind") ?? "";
  const kind = (raw in SERVICE ? raw : "embassy") as keyof typeof SERVICE;
  const detail = {
    embassy: useEmbassyDetail(),
    airport: useAirportDetail(),
    transport: useTransportDetail(),
    "medical-center": useMedicalCenterDetail(),
    "medical-destination": useMedicalDestinationDetail(),
  }[kind];
  const m = SERVICE[kind];
  return (
    <DetailShell
      id={params.get("id")}
      detail={detail}
      eyebrow={m.eyebrow}
      backHref={m.back}
      backLabel={m.label}
      render={(item) => {
        if (kind === "medical-center") return <PlaceDetailBody item={item} tags={medicalTags((item as MedicalCenter).subtype)} />;
        if (kind === "medical-destination") return <PlaceDetailBody item={item} tags={[]} />;
        const sub = subtypeOf(item as ServicePlace);
        const tags = [sub.category && (CATEGORY[sub.category] ?? sub.category), sub.operational_status && sub.operational_status.charAt(0).toUpperCase() + sub.operational_status.slice(1)].filter((t): t is string => Boolean(t));
        return <PlaceDetailBody item={item} tags={tags} email={sub.email} />;
      }}
    />
  );
}

export function VenueDetailPage() {
  const id = useSearchParams().get("id");
  const detail = useVenueDetailStore();
  return (
    <DetailShell
      id={id}
      detail={detail}
      eyebrow="Celebration venue"
      backHref="/life-and-fun/festivals-and-events#venues"
      backLabel="Back to festivals and events"
      render={(item) => <PlaceDetailBody item={item} tags={venueTags(item)} />}
    />
  );
}
