"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Input } from "@/components/ui/input";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
  DialogFooter,
} from "@/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import {
  Box,
  MapPin,
  Calendar,
  Clock,
  Users,
  Search,
  FileText,
  Eye,
  XCircle,
  UserCheck,
  Loader2,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { useToastEnhanced } from "@/hooks/use-toast-enhanced";
import { getFixPackageBookingsAction } from "@/features/fixed-packages/actions/booking-actions";
import type {
  FixPackageBooking,
  FixPackagePassengerDetail,
  UserFixPackageBookingsListResult,
  UserFixPackageBookingsPagination,
} from "@/core/api/services/fix-packages/fix-packages.types";
import {
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination";
import {
  USER_FIXED_BOOKINGS,
  formatUserFixedBookingsPaginationRange,
  formatUserFixedBookingsPaginationPage,
  formatDurationDays,
  travelersSectionTitle,
  childListLabel,
} from "@/lib/strings/user-fixed-bookings";

type BookingStatus = "pending" | "booked" | "cancelled" | "completed";

const PAGE_SIZE = 10;

const primaryButtonClassName =
  "bg-gradient-to-r from-teal-600 to-cyan-600 text-white shadow-md hover:from-teal-700 hover:to-cyan-700 hover:text-white";

const outlineButtonClassName =
  "border-teal-200 bg-white text-teal-700 hover:bg-teal-50 hover:text-teal-800";

const emptyPagination = (): UserFixPackageBookingsPagination => ({
  current_page: 1,
  last_page: 1,
  per_page: PAGE_SIZE,
  total: 0,
  from: null,
  to: null,
});

/** Coalesces concurrent identical requests (e.g. React Strict Mode dev double effects). */
const inflightUserFixBookings = new Map<
  string,
  Promise<UserFixPackageBookingsListResult>
>();

/** e.g. ISO string → "Dec 15, 2024" */
function formatBookingStartDate(value: string | undefined | null): string {
  if (value == null || value === "")
    return USER_FIXED_BOOKINGS.DATE_NOT_AVAILABLE;
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return value;
  return d.toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
  });
}

/** Avoid "0–3 years yrs" when API already sends a range label. */
function formatChildAgeForPill(age: string): string {
  const t = String(age ?? "").trim();
  if (!t) return USER_FIXED_BOOKINGS.EMPTY_DASH;
  if (/year|yr\b|month/i.test(t)) return t;
  return `${t}${USER_FIXED_BOOKINGS.CHILD_AGE_YEARS_SUFFIX}`;
}

/** Snapshot stored at booking time (avoids showing admin-edited live package). */
type BookingPackageDisplay = {
  name: string;
  locationDetail: string;
  totalDays: number | null;
  itineraryHtml: string | null;
};

function parseFixPackageJsonObject(
  booking: FixPackageBooking
): Record<string, unknown> | null {
  const raw = booking.fix_package_json;
  if (typeof raw !== "string" || !raw.trim()) return null;
  try {
    const parsed: unknown = JSON.parse(raw);
    if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
      return null;
    }
    return parsed as Record<string, unknown>;
  } catch {
    return null;
  }
}

function readSnapshotString(
  snap: Record<string, unknown>,
  ...keys: string[]
): string {
  for (const k of keys) {
    const v = snap[k];
    if (typeof v === "string") return v;
    if (v != null && typeof v !== "object" && typeof v !== "undefined") {
      return String(v);
    }
  }
  return "";
}

function readSnapshotTotalDays(snap: Record<string, unknown>): number | null {
  const v = snap.total_days ?? snap.totalDays;
  if (typeof v === "number" && !Number.isNaN(v)) return v;
  if (typeof v === "string") {
    const n = Number(v);
    return Number.isFinite(n) ? n : null;
  }
  return null;
}

function readSnapshotItineraryHtml(
  snap: Record<string, unknown>
): string | null {
  const v =
    snap.Itinerary_detail ?? snap.itinerary_detail ?? snap.Itinerary_Detail;
  if (typeof v === "string" && v.trim()) return v;
  return null;
}

/**
 * Prefer `fix_package_json` for all package copy shown to the user.
 * Falls back to `fix_package` only when JSON is missing or invalid.
 */
function getBookingPackageDisplay(
  booking: FixPackageBooking
): BookingPackageDisplay {
  const snap = parseFixPackageJsonObject(booking);
  if (snap) {
    const name = readSnapshotString(snap, "name").trim();
    const locationDetail = readSnapshotString(
      snap,
      "location_detail",
      "locationDetail"
    ).trim();
    return {
      name: name || USER_FIXED_BOOKINGS.UNKNOWN_PACKAGE,
      locationDetail: locationDetail || USER_FIXED_BOOKINGS.DATE_NOT_AVAILABLE,
      totalDays: readSnapshotTotalDays(snap),
      itineraryHtml: readSnapshotItineraryHtml(snap),
    };
  }

  const fb = booking.fix_package;
  return {
    name: fb?.name || USER_FIXED_BOOKINGS.UNKNOWN_PACKAGE,
    locationDetail:
      (fb?.location_detail ?? "").trim() ||
      USER_FIXED_BOOKINGS.DATE_NOT_AVAILABLE,
    totalDays: fb?.total_days ?? null,
    itineraryHtml:
      typeof fb?.Itinerary_detail === "string" && fb.Itinerary_detail.trim()
        ? fb.Itinerary_detail
        : null,
  };
}

function extractPassengerDetail(
  booking: FixPackageBooking
): FixPackagePassengerDetail | null {
  const pdRaw = booking.passenger_detail as unknown;
  if (typeof pdRaw === "string" && pdRaw.trim()) {
    try {
      const parsed: unknown = JSON.parse(pdRaw);
      if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
        return parsed as FixPackagePassengerDetail;
      }
    } catch {
      /* ignore */
    }
  }
  if (pdRaw && typeof pdRaw === "object") {
    return pdRaw as FixPackagePassengerDetail;
  }
  const p = booking.passenger;
  if (p && typeof p === "object") return p;
  const pAlt = (booking as { Passenger?: FixPackagePassengerDetail }).Passenger;
  if (pAlt && typeof pAlt === "object") return pAlt;
  if (
    typeof booking.passenger_json === "string" &&
    booking.passenger_json.trim()
  ) {
    try {
      const parsed: unknown = JSON.parse(booking.passenger_json);
      if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
        return parsed as FixPackagePassengerDetail;
      }
    } catch {
      /* ignore */
    }
  }
  return null;
}

type TravelersModalRow =
  | {
      kind: "list";
      passenger_name: string;
      gender?: string;
      age?: number;
      phone_number?: string | null;
      document_id_no?: string | null;
    }
  | {
      kind: "primary";
      passenger_name: string;
      total_child: number;
      total_adult: number;
      phone_number?: string;
      email?: string;
      children_json?: { age: string }[];
    };

function getTravelersForModal(booking: FixPackageBooking): {
  rows: TravelersModalRow[];
  travelerCount: number;
} {
  const list = booking.passengers;
  if (list && list.length > 0) {
    return {
      rows: list.map((p) => ({
        kind: "list" as const,
        passenger_name: p.passenger_name,
        gender: p.gender,
        age: p.age,
        phone_number: p.phone_number,
        document_id_no: p.document_id_no,
      })),
      travelerCount: list.length,
    };
  }

  const detail = extractPassengerDetail(booking);
  if (detail) {
    const totalChild = Number(detail.total_child) || 0;
    let totalAdult = Number(detail.total_adult);
    if (!Number.isFinite(totalAdult)) totalAdult = 0;
    if (
      totalAdult === 0 &&
      (detail.passenger_name?.trim() || detail.phone_number?.trim())
    ) {
      totalAdult = 1;
    }
    const travelerCount = totalAdult + totalChild;

    return {
      rows: [
        {
          kind: "primary" as const,
          passenger_name:
            detail.passenger_name?.trim() ||
            USER_FIXED_BOOKINGS.PRIMARY_TRAVELER_FALLBACK,
          total_child: totalChild,
          total_adult: totalAdult,
          phone_number: detail.phone_number,
          email: detail.email,
          children_json: detail.children_json,
        },
      ],
      travelerCount,
    };
  }

  return { rows: [], travelerCount: 0 };
}

function bookingMatchesSearchQuery(
  booking: FixPackageBooking,
  queryLower: string
): boolean {
  const snap = parseFixPackageJsonObject(booking);
  if (snap) {
    const name = readSnapshotString(snap, "name").toLowerCase();
    const loc = readSnapshotString(
      snap,
      "location_detail",
      "locationDetail"
    ).toLowerCase();
    return name.includes(queryLower) || loc.includes(queryLower);
  }
  const fb = booking.fix_package;
  return (
    (fb?.name ?? "").toLowerCase().includes(queryLower) ||
    (fb?.location_detail ?? "").toLowerCase().includes(queryLower)
  );
}

function dedupedUserFixPackageBookings(
  page: number,
  perPage: number
): Promise<UserFixPackageBookingsListResult> {
  const key = `${page}:${perPage}`;
  const existing = inflightUserFixBookings.get(key);
  if (existing) return existing;
  const pending = getFixPackageBookingsAction({
    page,
    per_page: perPage,
  }).finally(() => {
    inflightUserFixBookings.delete(key);
  });
  inflightUserFixBookings.set(key, pending);
  return pending;
}

export default function FixedBookingsContent() {
  const router = useRouter();
  const [activeTab, setActiveTab] = useState<"all" | BookingStatus>("all");
  const [searchQuery, setSearchQuery] = useState("");
  const [bookings, setBookings] = useState<FixPackageBooking[]>([]);
  const [pagination, setPagination] =
    useState<UserFixPackageBookingsPagination>(emptyPagination);
  const [currentPage, setCurrentPage] = useState(1);
  const [loading, setLoading] = useState(true);
  const [isFetchingPage, setIsFetchingPage] = useState(false);
  const { error } = useToastEnhanced();

  const applyBookingsResponse = (
    list: FixPackageBooking[],
    meta: UserFixPackageBookingsPagination,
    requestedPage: number
  ) => {
    setBookings(list ?? []);
    setPagination(meta);
    if (meta.last_page >= 1 && requestedPage > meta.last_page) {
      setCurrentPage(meta.last_page);
    }
  };

  useEffect(() => {
    let active = true;
    const page = currentPage;

    (async () => {
      try {
        if (pagination.total > 0 || bookings.length > 0) {
          setIsFetchingPage(true);
        } else {
          setLoading(true);
        }
        const { bookings: list, pagination: meta } =
          await dedupedUserFixPackageBookings(page, PAGE_SIZE);
        if (!active) return;
        applyBookingsResponse(list, meta, page);
      } catch {
        if (!active) return;
        error({
          title: USER_FIXED_BOOKINGS.TOAST_ERROR_TITLE,
          description: USER_FIXED_BOOKINGS.TOAST_FETCH_FAILED,
        });
        setBookings([]);
        setPagination(emptyPagination());
      } finally {
        if (active) {
          setLoading(false);
          setIsFetchingPage(false);
        }
      }
    })();

    return () => {
      active = false;
    };
  }, [currentPage]);

  // Helper to map DB booking_status to our UI status categories
  const getUiStatus = (dbStatus?: string): BookingStatus => {
    switch (dbStatus?.toLowerCase()) {
      case "confirm":
        return "booked";
      case "complete":
        return "completed";
      case "cancel":
        return "cancelled";
      default:
        return "pending";
    }
  };

  const getFilteredBookings = () => {
    let filtered = bookings;

    if (activeTab !== "all") {
      filtered = filtered.filter(
        (booking) => getUiStatus(booking.booking_status) === activeTab
      );
    }

    if (searchQuery) {
      const q = searchQuery.toLowerCase();
      filtered = filtered.filter(
        (booking) =>
          booking.id.toString().includes(searchQuery) ||
          bookingMatchesSearchQuery(booking, q)
      );
    }

    return filtered;
  };

  const filteredBookings = getFilteredBookings();

  const getStatusConfig = (dbStatus?: string) => {
    const uiStatus = getUiStatus(dbStatus);
    const configs: Record<
      BookingStatus,
      { label: string; badgeClass: string }
    > = {
      pending: {
        label: USER_FIXED_BOOKINGS.STATUS_PENDING,
        badgeClass: "bg-yellow-100 text-yellow-700 border-yellow-300",
      },
      booked: {
        label: USER_FIXED_BOOKINGS.STATUS_CONFIRMED,
        badgeClass: "bg-teal-50 text-teal-700 border-teal-200",
      },
      completed: {
        label: USER_FIXED_BOOKINGS.STATUS_COMPLETED,
        badgeClass: "bg-green-100 text-green-700 border-green-300",
      },
      cancelled: {
        label: USER_FIXED_BOOKINGS.STATUS_CANCELLED,
        badgeClass: "bg-red-100 text-red-700 border-red-300",
      },
    };
    return configs[uiStatus];
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center py-12">
        <Loader2 className="h-8 w-8 animate-spin text-teal-700" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="space-y-2">
        <h1 className="text-2xl md:text-3xl font-bold text-gray-900 flex items-center gap-3">
          <Box className="h-8 w-8 text-teal-700" />
          {USER_FIXED_BOOKINGS.PAGE_TITLE}
        </h1>
        <p className="text-gray-600">{USER_FIXED_BOOKINGS.PAGE_SUBTITLE}</p>
      </div>

      {/* Tabs and Search */}
      <div className="flex flex-col md:flex-row gap-4 justify-between">
        <Tabs
          value={activeTab}
          onValueChange={(v) => {
            setActiveTab(v as any);
            setCurrentPage(1);
          }}
          className="w-full md:w-auto"
        >
          <TabsList className="grid grid-cols-5 w-full md:w-auto">
            <TabsTrigger
              value="all"
              className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-teal-600 data-[state=active]:to-cyan-600 data-[state=active]:text-white"
            >
              {USER_FIXED_BOOKINGS.TAB_ALL}
            </TabsTrigger>
            <TabsTrigger
              value="ongoing"
              className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-teal-600 data-[state=active]:to-cyan-600 data-[state=active]:text-white"
            >
              {USER_FIXED_BOOKINGS.TAB_ONGOING}
            </TabsTrigger>
            <TabsTrigger
              value="booked"
              className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-teal-600 data-[state=active]:to-cyan-600 data-[state=active]:text-white"
            >
              {USER_FIXED_BOOKINGS.TAB_CONFIRMED}
            </TabsTrigger>
            <TabsTrigger
              value="completed"
              className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-teal-600 data-[state=active]:to-cyan-600 data-[state=active]:text-white"
            >
              {USER_FIXED_BOOKINGS.TAB_COMPLETED}
            </TabsTrigger>
            <TabsTrigger
              value="cancelled"
              className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-teal-600 data-[state=active]:to-cyan-600 data-[state=active]:text-white"
            >
              {USER_FIXED_BOOKINGS.TAB_CANCELLED}
            </TabsTrigger>
          </TabsList>
        </Tabs>

        <div className="relative flex-1 md:max-w-md">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
          <Input
            placeholder={USER_FIXED_BOOKINGS.SEARCH_PLACEHOLDER}
            value={searchQuery}
            onChange={(e) => {
              setSearchQuery(e.target.value);
              setCurrentPage(1);
            }}
            className="pl-9"
          />
        </div>
      </div>

      {/* Bookings List */}
      <div className="space-y-4 relative min-h-[120px]">
        {isFetchingPage && (
          <div
            className="absolute inset-0 z-10 flex items-center justify-center rounded-lg bg-background/60 backdrop-blur-[1px]"
            aria-busy="true"
            aria-label={USER_FIXED_BOOKINGS.LOADING_BOOKINGS_ARIA}
          >
            <Loader2 className="h-8 w-8 animate-spin text-teal-700" />
          </div>
        )}
        {filteredBookings.length === 0 ? (
          <Card>
            <CardContent className="flex flex-col items-center justify-center py-16 text-center">
              <Box className="mb-4 h-14 w-14 text-muted-foreground/60" />
              <h3 className="text-lg font-semibold">
              {USER_FIXED_BOOKINGS.EMPTY_TITLE}
              </h3>
              <p className="mt-1 text-sm text-muted-foreground">
                {USER_FIXED_BOOKINGS.EMPTY_DESCRIPTION}
              </p>
              <Button asChild className={cn("mt-5", primaryButtonClassName)}>
                <Link href="/fixed-packages">
                  {USER_FIXED_BOOKINGS.BROWSE_FIXED_PACKAGES}
                </Link>
              </Button>
            </CardContent>
          </Card>
        ) : (
          filteredBookings.map((booking) => {
            const config = getStatusConfig(booking.booking_status);
            const pkgDisplay = getBookingPackageDisplay(booking);
            const travelersModal = getTravelersForModal(booking);

            return (
              <Card
                key={booking.id}
                className="shadow-md hover:shadow-lg transition-all border-border/50"
              >
                <CardHeader>
                  <div className="flex items-start justify-between">
                    <div className="flex items-center gap-3">
                      <div className="rounded-lg bg-gradient-to-br from-[#0c1934] to-[#022f47] p-3 shadow-sm">
                        <Box
                          className="h-6 w-6 text-white"
                          aria-hidden="true"
                        />
                      </div>
                      <div>
                        <CardTitle className="text-lg">
                          {USER_FIXED_BOOKINGS.BOOKING_NO_PREFIX}
                          {booking.booking_number}
                        </CardTitle>
                        <p className="text-sm text-muted-foreground mt-1">
                          {pkgDisplay.name}
                        </p>
                      </div>
                    </div>
                    <Badge
                      variant="outline"
                      className={cn("shadow-sm", config.badgeClass)}
                    >
                      {config.label}
                    </Badge>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-4">
                    <div className="flex items-start gap-2">
                      <MapPin
                        className="h-5 w-5 text-muted-foreground mt-0.5 shrink-0"
                        aria-hidden="true"
                      />
                      <div>
                        <p className="text-sm font-medium">
                          {USER_FIXED_BOOKINGS.LABEL_DESTINATION}
                        </p>
                        <p className="text-sm text-muted-foreground">
                          {pkgDisplay.locationDetail}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-start gap-2">
                      <Calendar
                        className="h-5 w-5 text-muted-foreground mt-0.5 shrink-0"
                        aria-hidden="true"
                      />
                      <div>
                        <p className="text-sm font-medium">
                          {USER_FIXED_BOOKINGS.LABEL_START_DATE}
                        </p>
                        <p className="text-sm text-muted-foreground">
                          {formatBookingStartDate(booking.start_date)}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-start gap-2">
                      <Clock
                        className="h-5 w-5 text-muted-foreground mt-0.5 shrink-0"
                        aria-hidden="true"
                      />
                      <div>
                        <p className="text-sm font-medium">
                          {USER_FIXED_BOOKINGS.LABEL_DURATION}
                        </p>
                        <p className="text-sm text-muted-foreground">
                          {pkgDisplay.totalDays != null
                            ? formatDurationDays(pkgDisplay.totalDays)
                            : USER_FIXED_BOOKINGS.DATE_NOT_AVAILABLE}
                        </p>
                      </div>
                    </div>
                    {/* Note: Travelers count computation depends on API response structure if it includes passengers list */}
                    <div className="flex items-start gap-2">
                      <Users
                        className="h-5 w-5 text-muted-foreground mt-0.5 shrink-0"
                        aria-hidden="true"
                      />
                      <div>
                        <p className="text-sm font-medium">
                          {USER_FIXED_BOOKINGS.LABEL_PRICE}
                        </p>
                        <p className="text-sm text-muted-foreground">
                          ₹
                          {Number(booking.package_price).toLocaleString(
                            "en-IN"
                          )}
                        </p>
                      </div>
                    </div>
                  </div>
                  <div className="mt-4 pt-4 border-t border-border/50 flex flex-wrap justify-between items-center gap-3">
                    <div className="flex items-center gap-2">
                      <p className="text-lg font-bold">
                        ₹
                        {Number(
                          booking.total_price || booking.package_price
                        ).toLocaleString("en-IN")}
                      </p>
                    </div>
                    <div className="flex flex-wrap gap-2">
                      <Button
                        variant="outline"
                        size="sm"
                        asChild
                        className={cn("gap-2 hidden", outlineButtonClassName)}
                      >
                        <Link href={`/user/invoices/${booking.id}`}>
                          <FileText className="h-4 w-4" />
                          {USER_FIXED_BOOKINGS.BTN_INVOICE}
                        </Link>
                      </Button>
                      <Dialog>
                        <DialogTrigger asChild>
                          <Button
                            variant="outline"
                            size="sm"
                            className={cn("gap-2", outlineButtonClassName)}
                          >
                            <Eye className="h-4 w-4" />
                            {USER_FIXED_BOOKINGS.BTN_VIEW_DETAILS}
                          </Button>
                        </DialogTrigger>
                        <DialogContent className="max-h-[90vh] w-full max-w-[calc(80vw-1rem)] overflow-y-auto sm:max-w-5xl">
                          <DialogHeader>
                            <DialogTitle className="flex items-center gap-2">
                              <Eye className="h-5 w-5" />
                              {USER_FIXED_BOOKINGS.DIALOG_DETAILS_TITLE}
                              {booking && (
                                <Badge
                                  variant="outline"
                                  className="ml-2 font-mono"
                                >
                                  #{booking.booking_number}
                                </Badge>
                              )}
                            </DialogTitle>
                            <DialogDescription>
                              {USER_FIXED_BOOKINGS.DIALOG_DETAILS_DESCRIPTION}
                            </DialogDescription>
                          </DialogHeader>
                          <div className="py-2 space-y-6">
                            {/* General Info */}
                            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 bg-muted/30 p-4 rounded-lg">
                              <div>
                                <p className="text-sm text-muted-foreground">
                                  {USER_FIXED_BOOKINGS.LABEL_BOOKING_STATUS}
                                </p>
                                <Badge
                                  variant="outline"
                                  className={cn("mt-1", config.badgeClass)}
                                >
                                  {config.label}
                                </Badge>
                              </div>
                              <div>
                                <p className="text-sm text-muted-foreground">
                                  {USER_FIXED_BOOKINGS.LABEL_PAYMENT_STATUS}
                                </p>
                                <p className="font-medium mt-1 uppercase text-sm">
                                  {booking.payment_status ||
                                    USER_FIXED_BOOKINGS.PAYMENT_STATUS_UNKNOWN}
                                </p>
                              </div>
                              <div>
                                <p className="text-sm text-muted-foreground">
                                  {USER_FIXED_BOOKINGS.LABEL_BOOKING_DATE}
                                </p>
                                <p className="font-medium mt-1 text-sm">
                                  {formatBookingStartDate(booking.created_at)}
                                </p>
                              </div>
                              <div>
                                <p className="text-sm text-muted-foreground">
                                  {USER_FIXED_BOOKINGS.LABEL_TOTAL_PAID}
                                </p>
                                <p className="mt-1 text-sm font-medium text-teal-700">
                                  ₹
                                  {Number(
                                    booking.total_price || booking.package_price
                                  ).toLocaleString("en-IN")}
                                </p>
                              </div>
                            </div>

                            {/* Package Profile */}
                            <div>
                              <h3 className="text-lg font-semibold flex items-center gap-2 border-b pb-2 mb-3">
                                <Box className="h-5 w-5 text-teal-700" />
                                {USER_FIXED_BOOKINGS.SECTION_PACKAGE_INFO}
                              </h3>
                              <div className="grid md:grid-cols-3 gap-4">
                                <div>
                                  <p className="text-sm text-muted-foreground">
                                    {USER_FIXED_BOOKINGS.LABEL_PACKAGE_NAME}
                                  </p>
                                  <p className="font-medium">
                                    {pkgDisplay.name}
                                  </p>
                                </div>
                                <div className="md:col-span-2">
                                  <p className="text-sm text-muted-foreground">
                                    {
                                      USER_FIXED_BOOKINGS.LABEL_DESTINATION_LOCATION
                                    }
                                  </p>
                                  <p className="font-medium">
                                    {pkgDisplay.locationDetail}
                                  </p>
                                </div>
                                <div>
                                  <p className="text-sm text-muted-foreground">
                                    {USER_FIXED_BOOKINGS.LABEL_JOURNEY_START}
                                  </p>
                                  <p className="font-medium">
                                    {formatBookingStartDate(booking.start_date)}
                                  </p>
                                </div>
                                <div>
                                  <p className="text-sm text-muted-foreground">
                                    {USER_FIXED_BOOKINGS.LABEL_DURATION}
                                  </p>
                                  <p className="font-medium">
                                    {pkgDisplay.totalDays != null
                                      ? formatDurationDays(pkgDisplay.totalDays)
                                      : USER_FIXED_BOOKINGS.DATE_NOT_AVAILABLE}
                                  </p>
                                </div>
                              </div>
                            </div>

                            {/* Passengers / Travelers */}
                            <div>
                              <h3 className="text-lg font-semibold flex items-center gap-2 border-b pb-2 mb-3">
                                <Users className="h-5 w-5 text-teal-700" />
                                {travelersSectionTitle(
                                  travelersModal.travelerCount
                                )}
                              </h3>
                              {travelersModal.rows.length > 0 ? (
                                <div className="grid gap-3">
                                  {travelersModal.rows.map((row, idx) =>
                                    row.kind === "list" ? (
                                      <div
                                        key={idx}
                                        className="flex flex-col md:flex-row md:items-center justify-between p-3 border rounded-lg bg-card"
                                      >
                                        <div className="flex items-center gap-3 mb-2 md:mb-0">
                                          <div className="rounded-full bg-teal-50 p-2 text-teal-700">
                                            <UserCheck className="h-4 w-4" />
                                          </div>
                                          <div>
                                            <p className="font-medium">
                                              {row.passenger_name}
                                            </p>
                                            {(row.gender ||
                                              row.age != null) && (
                                              <p className="text-xs text-muted-foreground">
                                                {[
                                                  row.gender,
                                                  row.age != null
                                                    ? `${row.age}${USER_FIXED_BOOKINGS.CHILD_AGE_YEARS_SUFFIX}`
                                                    : null,
                                                ]
                                                  .filter(Boolean)
                                                  .join(" • ")}
                                              </p>
                                            )}
                                          </div>
                                        </div>
                                        <div className="text-sm text-gray-600 pl-11 md:pl-0 flex flex-col md:items-end">
                                          {row.phone_number && (
                                            <p>
                                              {
                                                USER_FIXED_BOOKINGS.LABEL_PHONE_COLON
                                              }
                                              {row.phone_number}
                                            </p>
                                          )}
                                          {row.document_id_no && (
                                            <p>
                                              {
                                                USER_FIXED_BOOKINGS.LABEL_ID_COLON
                                              }
                                              {row.document_id_no}
                                            </p>
                                          )}
                                        </div>
                                      </div>
                                    ) : (
                                      <div
                                        key={idx}
                                        className="flex gap-3 p-3 border rounded-lg bg-card"
                                      >
                                        <div
                                          className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-teal-50 text-teal-700"
                                          aria-hidden
                                        >
                                          <UserCheck className="h-5 w-5" />
                                        </div>
                                        <div className="min-w-0 flex-1 space-y-3">
                                          <div>
                                            <p className="text-sm text-muted-foreground">
                                              {
                                                USER_FIXED_BOOKINGS.LABEL_PRIMARY_CONTACT
                                              }
                                            </p>
                                            <p className="font-medium text-base text-foreground">
                                              {row.passenger_name}
                                            </p>
                                          </div>
                                          {(row.phone_number || row.email) && (
                                            <div className="flex flex-row flex-wrap items-baseline gap-x-8 gap-y-1 text-sm">
                                              {row.phone_number && (
                                                <p className="text-muted-foreground whitespace-nowrap">
                                                  <span className="font-medium text-foreground">
                                                    {
                                                      USER_FIXED_BOOKINGS.LABEL_PHONE
                                                    }
                                                  </span>
                                                  <span className="mx-1.5 text-border">
                                                    ·
                                                  </span>
                                                  {row.phone_number}
                                                </p>
                                              )}
                                              {row.email && (
                                                <p className="min-w-0 flex-1 text-muted-foreground break-all">
                                                  <span className="font-medium text-foreground">
                                                    {
                                                      USER_FIXED_BOOKINGS.LABEL_EMAIL
                                                    }
                                                  </span>
                                                  <span className="mx-1.5 text-border">
                                                    ·
                                                  </span>
                                                  {row.email}
                                                </p>
                                              )}
                                            </div>
                                          )}
                                          <div className="space-y-1 text-sm text-muted-foreground border-t border-border/60 pt-3">
                                            <p>
                                              <span className="font-medium text-foreground">
                                                {
                                                  USER_FIXED_BOOKINGS.LABEL_CHILDREN_TRAVELLING
                                                }
                                              </span>
                                              {row.total_child}
                                            </p>
                                            {row.total_adult > 1 && (
                                              <p>
                                                <span className="font-medium text-foreground">
                                                  {
                                                    USER_FIXED_BOOKINGS.LABEL_ADULTS
                                                  }
                                                </span>
                                                {row.total_adult}
                                              </p>
                                            )}
                                          </div>
                                          {row.children_json &&
                                            row.children_json.length > 0 && (
                                              <div className="space-y-2">
                                                <p className="text-xs font-medium text-muted-foreground">
                                                  {
                                                    USER_FIXED_BOOKINGS.CHILD_AGE_DETAILS
                                                  }
                                                </p>
                                                <ul
                                                  className="grid grid-cols-2 sm:grid-cols-3 gap-2"
                                                  aria-label={
                                                    USER_FIXED_BOOKINGS.CHILDREN_AGES_ARIA
                                                  }
                                                >
                                                  {row.children_json.map(
                                                    (c, childIdx) => (
                                                      <li key={childIdx}>
                                                        <div
                                                          className={cn(
                                                            "flex h-full flex-col gap-1 rounded-lg border border-border/80 bg-muted/35 px-2.5 py-2 text-left",
                                                            "shadow-sm"
                                                          )}
                                                        >
                                                          <span className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
                                                            {childListLabel(
                                                              childIdx + 1
                                                            )}
                                                          </span>
                                                          <span className="text-sm font-semibold leading-snug text-foreground">
                                                            {formatChildAgeForPill(
                                                              c.age
                                                            )}
                                                          </span>
                                                        </div>
                                                      </li>
                                                    )
                                                  )}
                                                </ul>
                                              </div>
                                            )}
                                        </div>
                                      </div>
                                    )
                                  )}
                                </div>
                              ) : (
                                <p className="text-sm text-muted-foreground bg-muted p-4 rounded-lg text-center">
                                  {USER_FIXED_BOOKINGS.NO_TRAVELER_INFO}
                                </p>
                              )}
                            </div>

                            {/* If there's itinerary detail in the package */}
                            {pkgDisplay.itineraryHtml && (
                              <div>
                                <h3 className="text-lg font-semibold border-b pb-2 mb-3">
                                  {USER_FIXED_BOOKINGS.SECTION_ITINERARY}
                                </h3>
                                <div
                                  className="text-sm prose max-w-none prose-sm text-muted-foreground dark:prose-invert"
                                  dangerouslySetInnerHTML={{
                                    __html: pkgDisplay.itineraryHtml,
                                  }}
                                />
                              </div>
                            )}
                          </div>
                          <DialogFooter>
                            <DialogTrigger asChild>
                              <Button
                                variant="outline"
                                className={outlineButtonClassName}
                              >
                                {USER_FIXED_BOOKINGS.BTN_CLOSE}
                              </Button>
                            </DialogTrigger>
                          </DialogFooter>
                        </DialogContent>
                      </Dialog>

                      <AlertDialog>
                        <AlertDialogTrigger asChild>
                          <Button
                            variant="outline"
                            size="sm"
                            className="gap-2 text-red-600 hover:text-red-700 hover:bg-red-50 bg-transparent"
                          >
                            <XCircle className="h-4 w-4" />
                            {USER_FIXED_BOOKINGS.BTN_CANCEL_BOOKING}
                          </Button>
                        </AlertDialogTrigger>
                        <AlertDialogContent>
                          <AlertDialogHeader>
                            <AlertDialogTitle>
                              {USER_FIXED_BOOKINGS.ALERT_CANCEL_TITLE}
                            </AlertDialogTitle>
                            <AlertDialogDescription>
                              {USER_FIXED_BOOKINGS.ALERT_CANCEL_DESCRIPTION}
                            </AlertDialogDescription>
                          </AlertDialogHeader>
                          <AlertDialogFooter>
                            <AlertDialogCancel>
                              {USER_FIXED_BOOKINGS.ALERT_KEEP_BOOKING}
                            </AlertDialogCancel>
                            <AlertDialogAction
                              onClick={(e) => {
                                e.preventDefault();
                                router.push(
                                  `/user/fixed-bookings/${booking.id}/refund?bookingNumber=${encodeURIComponent(String(booking.booking_number))}`
                                );
                              }}
                              className="bg-red-600 hover:bg-red-700"
                            >
                              {USER_FIXED_BOOKINGS.ALERT_CONFIRM_CANCEL}
                            </AlertDialogAction>
                          </AlertDialogFooter>
                        </AlertDialogContent>
                      </AlertDialog>
                    </div>
                  </div>
                </CardContent>
              </Card>
            );
          })
        )}
      </div>

      {pagination.total > 0 && (
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 pt-2 border-t border-border/50">
          <p className="text-sm text-muted-foreground">
            {pagination.from != null && pagination.to != null
              ? formatUserFixedBookingsPaginationRange(
                  pagination.from,
                  pagination.to,
                  pagination.total
                )
              : formatUserFixedBookingsPaginationPage(
                  pagination.current_page,
                  pagination.last_page,
                  pagination.total
                )}
          </p>
          {pagination.last_page > 1 && (
            <Pagination>
              <PaginationContent>
                <PaginationItem>
                  <PaginationPrevious
                    href="#"
                    onClick={(e) => {
                      e.preventDefault();
                      if (pagination.current_page > 1) {
                        setCurrentPage((p) => p - 1);
                      }
                    }}
                    className={
                      pagination.current_page <= 1
                        ? "pointer-events-none opacity-50"
                        : undefined
                    }
                  />
                </PaginationItem>
                <PaginationItem>
                  <span className="flex h-9 min-w-[2.5rem] items-center justify-center px-3 text-sm font-medium">
                    {pagination.current_page} / {pagination.last_page}
                  </span>
                </PaginationItem>
                <PaginationItem>
                  <PaginationNext
                    href="#"
                    onClick={(e) => {
                      e.preventDefault();
                      if (pagination.current_page < pagination.last_page) {
                        setCurrentPage((p) => p + 1);
                      }
                    }}
                    className={
                      pagination.current_page >= pagination.last_page
                        ? "pointer-events-none opacity-50"
                        : undefined
                    }
                  />
                </PaginationItem>
              </PaginationContent>
            </Pagination>
          )}
        </div>
      )}
    </div>
  );
}
