import { createFileRoute, Link } from "@tanstack/react-router";
import { ArrowLeft } from "lucide-react";
import { z } from "zod";

import { DepartureDatesManager } from "@/components/app/DepartureDatesManager";
import { ItineraryManager } from "@/components/app/ItineraryManager";
import { Page } from "@/components/app/Page";
import { DetailRow, EmptyState, SectionHeading, formatDate } from "@/components/app/Primitives";
import { StatusPill } from "@/components/app/StatusPill";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useDropdownOptions } from "@/features/master-types/api";
import { useTour, type Tour } from "@/features/tours/api";
import { destinationImage } from "@/lib/images";

const tourDetailSearchSchema = z.object({
  tab: z.enum(["overview", "itinerary", "availability", "content", "publishing"]).optional(),
});

export const Route = createFileRoute("/tours/$id")({
  validateSearch: tourDetailSearchSchema,
  head: () => ({
    meta: [{ title: "Tour | KareVoyage Operations" }],
  }),
  component: TourDetail,
});

const money = (currency: string, amount: string | null) =>
  amount == null
    ? "—"
    : `${currency} ${Number(amount).toLocaleString("en-IN", { maximumFractionDigits: 0 })}`;

/** `publishingState` is stored lowercase ("draft"/"review"/"published") — capitalized here for
 * display only, in both places it's shown (hero banner + Publishing tab card), without touching
 * the shared StatusPill's own casing behavior (other modules pass their own casing on purpose). */
const titleCase = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);

/** Every dropdown-backed tour field stores the Master Type option's `value` slug (e.g.
 * "room_only_ro"), not its display label — this resolves it back to the friendly label
 * ("Room Only (RO)") for read-only display, falling back to the raw value if it's not found
 * (e.g. the option was later renamed/deactivated) rather than showing nothing. */
function DropdownValue({ groupKey, value }: { groupKey: string; value: string | null }) {
  const { data: options } = useDropdownOptions(groupKey);
  if (!value) return null;
  return <>{options?.find((o) => o.value === value)?.label ?? value}</>;
}

/** Same resolution as `DropdownValue`, for a multi-select field — renders each value's label as
 * a chip. */
function MultiDropdownValue({ groupKey, values }: { groupKey: string; values: string[] }) {
  const { data: options } = useDropdownOptions(groupKey);
  if (values.length === 0) return null;
  return (
    <span className="flex flex-wrap justify-end gap-1">
      {values.map((v) => (
        <span key={v} className="rounded-md bg-surface-muted px-1.5 py-0.5 text-xs text-foreground">
          {options?.find((o) => o.value === v)?.label ?? v}
        </span>
      ))}
    </span>
  );
}

function TourDetail() {
  const { id } = Route.useParams();
  const { tab } = Route.useSearch();
  const { data: tour, isLoading, isError } = useTour(id);

  if (isLoading) {
    return (
      <Page>
        <p className="text-sm text-muted-foreground">Loading tour…</p>
      </Page>
    );
  }

  if (isError || !tour) {
    return (
      <Page>
        <EmptyState
          title="Tour not found"
          message="This tour doesn't exist or may have been removed."
          action={
            <Button asChild>
              <Link to="/tours">Back to tours</Link>
            </Button>
          }
        />
      </Page>
    );
  }

  return <TourDetailView tour={tour} initialTab={tab} />;
}

function TourDetailView({
  tour,
  initialTab,
}: {
  tour: Tour;
  initialTab?: "overview" | "itinerary" | "availability" | "content" | "publishing" | undefined;
}) {
  return (
    <div className="min-h-0 flex-1 overflow-y-auto kv-scroll">
      <div className="relative h-52 w-full overflow-hidden md:h-60">
        <img
          src={tour.primaryImageUrl || destinationImage(tour.destination)}
          alt={`${tour.destination} landscape`}
          width={1024}
          height={640}
          className="h-full w-full object-cover"
        />
        <div className="absolute inset-0 bg-gradient-to-t from-foreground/80 via-foreground/35 to-transparent" />
        <div className="absolute inset-x-0 bottom-0 mx-auto w-full max-w-[1440px] px-5 pb-6 md:px-8">
          <Link
            to="/tours"
            className="mb-3 inline-flex items-center gap-1.5 text-xs text-background/80 hover:text-background"
          >
            <ArrowLeft className="h-3.5 w-3.5" /> All tours
          </Link>
          <div className="flex flex-wrap items-end justify-between gap-4">
            <div>
              <p className="text-[11px] font-semibold uppercase tracking-[0.16em] text-background/70">
                {tour.destination}, {tour.country}
              </p>
              <h1 className="mt-1 text-[32px] leading-tight text-background">{tour.title}</h1>
              <p className="mt-2 text-xs text-background/85">
                {tour.durationNights}N / {tour.durationDays}D · from{" "}
                {money(tour.currency, tour.price)}
              </p>
            </div>
            <div className="flex items-center gap-2">
              <StatusPill value={titleCase(tour.publishingState)} className="bg-background/90" />
              <Button size="sm" variant="secondary" asChild>
                <Link to="/tours/edit/$id" params={{ id: tour.id }}>
                  Edit tour
                </Link>
              </Button>
            </div>
          </div>
        </div>
      </div>

      <Page className="space-y-8">
        <Tabs defaultValue={initialTab ?? "overview"}>
          <TabsList className="flex h-auto w-full flex-wrap justify-start gap-1 bg-transparent p-0">
            {[
              { value: "overview", label: "Overview" },
              { value: "itinerary", label: "Itinerary" },
              { value: "availability", label: "Availability" },
              { value: "content", label: "Content" },
              { value: "publishing", label: "Publishing" },
            ].map((t) => (
              <TabsTrigger
                key={t.value}
                value={t.value}
                className="rounded-lg px-3 py-1.5 text-sm data-[state=active]:bg-primary-soft data-[state=active]:text-accent-foreground data-[state=active]:shadow-none"
              >
                {t.label}
              </TabsTrigger>
            ))}
          </TabsList>

          <TabsContent value="overview" className="mt-6 grid gap-6 lg:grid-cols-3">
            <div className="rounded-xl border border-border bg-surface p-5">
              <SectionHeading title="Product" />
              <dl className="divide-y divide-border">
                <DetailRow label="Slug" value={tour.slug} />
                <DetailRow label="Tour type" value={tour.tourType.replace("_", " ")} />
                <DetailRow
                  label="Category"
                  value={<DropdownValue groupKey="tour_category" value={tour.category} />}
                />
                <DetailRow label="Badge" value={tour.badgeLabel} />
                <DetailRow
                  label="Document requirements"
                  value={<MultiDropdownValue groupKey="document_type" values={tour.requiredDocuments} />}
                />
                <DetailRow
                  label="Status"
                  value={<StatusPill value={tour.isActive ? "Active" : "Inactive"} />}
                />
              </dl>
            </div>
            <div className="rounded-xl border border-border bg-surface p-5">
              <SectionHeading title="Destination & Details" />
              <dl className="divide-y divide-border">
                <DetailRow
                  label="Country"
                  value={<DropdownValue groupKey="country" value={tour.country} />}
                />
                <DetailRow label="State / Region" value={tour.stateRegion} />
                <DetailRow label="City" value={tour.destination} />
                <DetailRow
                  label="Duration"
                  value={`${tour.durationNights}N / ${tour.durationDays}D`}
                />
                <DetailRow label="Group size" value={`${tour.groupSizeMin}–${tour.groupSizeMax}`} />
                <DetailRow label="Departure city" value={tour.departureCity} />
              </dl>
            </div>
            <div className="rounded-xl border border-border bg-surface p-5">
              <SectionHeading title="Pricing" />
              <dl className="divide-y divide-border">
                <DetailRow label="Base price" value={money(tour.currency, tour.price)} />
                <DetailRow label="Child price" value={money(tour.currency, tour.childPrice)} />
                <DetailRow
                  label="Single supplement"
                  value={money(tour.currency, tour.singleSupplement)}
                />
                <DetailRow label="Start date" value={formatDate(tour.startDate)} />
                <DetailRow label="End date" value={formatDate(tour.endDate)} />
              </dl>
            </div>
          </TabsContent>

          <TabsContent value="itinerary" className="mt-6">
            <ItineraryManager tour={tour} />
          </TabsContent>

          <TabsContent value="availability" className="mt-6">
            <DepartureDatesManager tour={tour} />
          </TabsContent>

          <TabsContent value="content" className="mt-6 space-y-6">
            <div className="grid gap-6 md:grid-cols-3">
              <BulletCard
                title="Inclusions"
                items={tour.inclusions}
                empty="No inclusions listed."
              />
              <BulletCard
                title="Exclusions"
                items={tour.exclusions}
                empty="No exclusions listed."
              />
              <BulletCard
                title="Highlights"
                items={tour.highlights}
                empty="No highlights listed."
              />
            </div>
            {tour.galleryImageUrls.length > 0 ? (
              <div className="rounded-xl border border-border bg-surface p-5">
                <SectionHeading title="Gallery" />
                <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
                  {tour.galleryImageUrls.map((url) => (
                    <img
                      key={url}
                      src={url}
                      alt="Gallery"
                      loading="lazy"
                      className="h-24 w-full rounded-lg border border-border object-cover"
                    />
                  ))}
                </div>
              </div>
            ) : null}
          </TabsContent>

          <TabsContent value="publishing" className="mt-6 grid gap-6 lg:grid-cols-2">
            <div className="rounded-xl border border-border bg-surface p-5">
              <SectionHeading title="Publishing" />
              <dl className="divide-y divide-border">
                <DetailRow
                  label="Status"
                  value={<StatusPill value={titleCase(tour.publishingState)} />}
                />
                <DetailRow label="Featured" value={tour.featured ? "Yes" : "No"} />
                <DetailRow label="Active" value={tour.isActive ? "Yes" : "No"} />
                <DetailRow label="Allow booking" value={tour.allowBooking ? "Yes" : "No"} />
                <DetailRow label="Created" value={formatDate(tour.createdAt)} />
                <DetailRow label="Last updated" value={formatDate(tour.updatedAt)} />
              </dl>
            </div>
            <div className="rounded-xl border border-border bg-surface p-5">
              <SectionHeading title="Additional Info" />
              <dl className="divide-y divide-border">
                <DetailRow
                  label="Accommodation"
                  value={<DropdownValue groupKey="accommodation_type" value={tour.accommodationType} />}
                />
                <DetailRow
                  label="Meal plan"
                  value={<DropdownValue groupKey="meal_plan" value={tour.mealPlan} />}
                />
                <DetailRow
                  label="Transport"
                  value={<DropdownValue groupKey="transport_type" value={tour.transportType} />}
                />
                <DetailRow
                  label="Physical rating"
                  value={tour.physicalRating ? `${tour.physicalRating}/5` : null}
                />
                <DetailRow
                  label="Recommended for"
                  value={<DropdownValue groupKey="recommended_for" value={tour.recommendedFor} />}
                />
                <DetailRow label="Tags" value={tour.tags.length ? tour.tags.join(", ") : null} />
              </dl>
            </div>
          </TabsContent>
        </Tabs>
      </Page>
    </div>
  );
}

function BulletCard({ title, items, empty }: { title: string; items: string[]; empty: string }) {
  return (
    <div className="rounded-xl border border-border bg-surface p-5">
      <SectionHeading title={title} />
      {items.length === 0 ? (
        <p className="text-sm text-muted-foreground">{empty}</p>
      ) : (
        <ul className="space-y-2 text-sm text-muted-foreground">
          {items.map((i) => (
            <li key={i}>· {i}</li>
          ))}
        </ul>
      )}
    </div>
  );
}
