import { useMemo, useRef, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  AlertCircle,
  Calendar,
  MapPin,
  Package,
  StickyNote,
  Train,
  Weight,
  Ship,
  Truck,
  Anchor,
  FileText,
  ShieldCheck,
  AlertTriangle,
  Info,
  Layers,
  CheckCircle2,
  History,
  ArrowRight,
  ClipboardCheck,
  CreditCard,
  FileSignature,
  PackageCheck,
  LoaderCircle,
  DollarSign,
  Upload,
  XCircle,
  Building2,
  FileUp,
} from "lucide-react";

import { format } from "date-fns";

import Breadcrumbs from "@/components/Breadcrumbs";
import { api } from "@/services/api";
import type { Freight } from "@edr/types";
import {
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
  Badge,
  Button,
  Separator,
  Dialog,
  DialogTrigger,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
  DialogClose,
} from "@edr/ui-common";
import { cn } from "@/lib/utils";
import useAuth from "@/hooks/useAuth";

const PROGRESS_STAGES = [
  { label: "Request", icon: FileText, statuses: ["DRAFT", "CHANGES_REQUESTED"] },
  { label: "Submitted", icon: ClipboardCheck, statuses: ["SUBMITTED", "PENDING_APPROVAL"] },
  { label: "Approved", icon: ShieldCheck, statuses: ["APPROVED_PENDING_SIGNATURE", "APPROVED", "CONTRACT_READY", "SIGNED_CUSTOMER", "FULLY_EXECUTED"] },
  { label: "In Transit", icon: Train, statuses: ["PNR_GENERATED", "PAYMENT_VERIFICATION_IN_PROGRESS", "PAID", "IN_TRANSIT", "PENDING_CONSOLIDATION", "CONSOLIDATED"] },
  { label: "Complete", icon: PackageCheck, statuses: ["COMPLETED", "DELIVERED"] },
];

const STATUS_MAP: Record<
  string,
  { title: string; description: string; color: string; stage: number }
> = {
  DRAFT: {
    title: "Drafting Request",
    description: "Booking is being prepared and has not been submitted.",
    color: "text-muted-foreground",
    stage: 0,
  },
  CHANGES_REQUESTED: {
    title: "Changes Requested",
    description: "Staff has requested changes. Please review and resubmit.",
    color: "text-amber-600",
    stage: 0,
  },
  SUBMITTED: {
    title: "Submitted",
    description: "Your booking has been submitted for review.",
    color: "text-primary",
    stage: 1,
  },
  PENDING_APPROVAL: {
    title: "Pending Approval",
    description: "Booking is in the approval process.",
    color: "text-primary",
    stage: 1,
  },
  APPROVED_PENDING_SIGNATURE: {
    title: "Awaiting Signature",
    description: "Approved — pending contract signature.",
    color: "text-primary",
    stage: 2,
  },
  APPROVED: {
    title: "Approved",
    description: "Booking has been fully approved.",
    color: "text-primary",
    stage: 2,
  },
  CONTRACT_READY: {
    title: "Contract Ready",
    description: "Contract is available for review and signature.",
    color: "text-primary",
    stage: 2,
  },
  SIGNED_CUSTOMER: {
    title: "Customer Signed",
    description: "Customer has signed. Awaiting staff signature.",
    color: "text-primary",
    stage: 2,
  },
  FULLY_EXECUTED: {
    title: "Fully Executed",
    description: "Contract has been fully signed and executed.",
    color: "text-primary",
    stage: 2,
  },
  PNR_GENERATED: {
    title: "PNR Generated",
    description: "Payment reference number generated.",
    color: "text-primary",
    stage: 3,
  },
  PAYMENT_VERIFICATION_IN_PROGRESS: {
    title: "Payment Verification",
    description: "Payment is being verified.",
    color: "text-primary",
    stage: 3,
  },
  PAID: {
    title: "Paid",
    description: "Payment has been confirmed.",
    color: "text-primary",
    stage: 3,
  },
  IN_TRANSIT: {
    title: "Cargo Moving",
    description: "Shipment is currently moving through the rail network.",
    color: "text-primary",
    stage: 3,
  },
  PENDING_CONSOLIDATION: {
    title: "Pending Consolidation",
    description: "Awaiting consolidation partner.",
    color: "text-primary",
    stage: 3,
  },
  CONSOLIDATED: {
    title: "Consolidated",
    description: "Cargo has been consolidated with partner shipment.",
    color: "text-primary",
    stage: 3,
  },
  COMPLETED: {
    title: "Service Complete",
    description: "Cargo delivered and service successfully terminated.",
    color: "text-primary",
    stage: 4,
  },
  DELIVERED: {
    title: "Service Complete",
    description: "Cargo delivered and service successfully terminated.",
    color: "text-primary",
    stage: 4,
  },
  REJECTED: {
    title: "Rejected",
    description: "This booking request has been rejected.",
    color: "text-destructive",
    stage: -1,
  },
  CANCELLED: {
    title: "Cancelled",
    description: "This booking process has been terminated.",
    color: "text-destructive",
    stage: -1,
  },
};

const REQUIRED_DOC_FIELDS = [
  { key: "commercial_invoice", label: "Commercial Invoice" },
  { key: "packing_list", label: "Packing List" },
  { key: "certificate_of_origin", label: "Certificate of Origin" },
  { key: "letter_of_credit", label: "Letter of Credit / LC" },
];

export default function BookingDetailPage() {
  const { id } = useParams<{ id: string }>();
  const queryClient = useQueryClient();

  const {
    data: booking,
    isLoading,
    isError,
    error,
  } = useQuery(
    api.bookings.get.queryOptions({
      input: { id: id! },
      enabled: !!id,
    }),
  );

  const refetchBooking = () => {
    queryClient.invalidateQueries({
      queryKey: api.bookings.get.queryKey({ id: id! }),
    });
  };

  if (isLoading) {
    return (
      <div className="container mx-auto flex items-center justify-center p-12">
        <div className="flex flex-col items-center gap-4">
          <LoaderCircle className="size-8 animate-spin text-primary" />
          <p className="text-sm text-muted-foreground">
            Loading booking details…
          </p>
        </div>
      </div>
    );
  }

  if (isError) {
    return (
      <div className="container mx-auto p-6">
        <Card className="flex flex-col items-center p-12 text-center">
          <div className="flex size-16 items-center justify-center rounded-full bg-destructive/10 text-destructive">
            <AlertTriangle className="size-8" />
          </div>
          <h1 className="mt-4 text-2xl font-bold text-foreground">
            Failed to load booking
          </h1>
          <p className="mt-2 text-sm text-muted-foreground">
            {error instanceof Error
              ? error.message
              : "An unexpected error occurred."}
          </p>
        </Card>
      </div>
    );
  }

  if (!booking) {
    return (
      <div className="container mx-auto p-6">
        <Card className="flex flex-col items-center p-12 text-center">
          <div className="flex size-16 items-center justify-center rounded-full bg-muted text-muted-foreground">
            <Package className="size-8" />
          </div>
          <h1 className="mt-4 text-2xl font-bold text-foreground">
            Booking not found
          </h1>
        </Card>
      </div>
    );
  }

  if (booking.status === "DRAFT" || booking.status === "CHANGES_REQUESTED") {
    return (
      <DraftBookingView booking={booking} onBookingUpdated={refetchBooking} />
    );
  }

  return <ReadonlyBookingView booking={booking} />;
}

function DraftBookingView({
  booking,
  onBookingUpdated,
}: {
  booking: Freight.IBooking;
  onBookingUpdated: () => void;
}) {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { customer } = useAuth();
  const fileInputRefs = useRef<Record<string, HTMLInputElement | null>>({});
  const documentsRef = useRef<HTMLDivElement>(null);

  const [selectedFiles, setSelectedFiles] = useState<
    Record<string, File | null>
  >({});
  const [cancelDialogOpen, setCancelDialogOpen] = useState(false);
  const [cancelReason, setCancelReason] = useState("");
  const [docError, setDocError] = useState("");

  const anyFileSelected = Object.values(selectedFiles).some(Boolean);

  const uploadedCodes = useMemo(
    () => new Set(booking.files?.map((f) => f.code) ?? []),
    [booking.files],
  );

  const { data: generatedPricing } = useQuery({
    ...api.bookings.generatePrice.queryOptions({ input: { id: booking.id } }),
    enabled: booking.status === "DRAFT" && !booking.pricingBreakdown,
  });

  const pricing = booking.pricingBreakdown ?? generatedPricing ?? null;

  const uploadMutation = useMutation({
    mutationFn: (files: Record<string, File | File[] | null>) =>
      api.bookings.uploadDocuments.call({ id: booking.id, files }),
    onSuccess: () => {
      setSelectedFiles({});
      setDocError("");
      onBookingUpdated();
    },
  });

  const submitMutation = useMutation({
    mutationFn: () => api.bookings.submit.call({ id: booking.id }),
    onSuccess: () => {
      onBookingUpdated();
      queryClient.invalidateQueries({ queryKey: api.bookings.list.queryKey() });
    },
  });

  const cancelMutation = useMutation({
    mutationFn: (reason: string) =>
      api.bookings.cancel.call({ id: booking.id, reason }),
    onSuccess: () => {
      setCancelDialogOpen(false);
      onBookingUpdated();
    },
  });

  function handleFileSelect(key: string, file: File | null) {
    setSelectedFiles((prev) => ({ ...prev, [key]: file }));
  }

  function handleUploadAll() {
    const filesToUpload: Record<string, File | null> = {};
    for (const doc of REQUIRED_DOC_FIELDS) {
      if (selectedFiles[doc.key]) {
        filesToUpload[doc.key] = selectedFiles[doc.key]!;
      }
    }
    if (Object.keys(filesToUpload).length === 0) return;
    uploadMutation.mutate(filesToUpload);
  }

  function handleCancel() {
    const reason = cancelReason.trim() || "Cancelled by customer";
    cancelMutation.mutate(reason);
  }

  function handleSubmitRequest() {
    const missing = REQUIRED_DOC_FIELDS.filter(
      (doc) => !uploadedCodes.has(doc.key),
    );
    if (missing.length > 0) {
      setDocError("Please upload all required documents before submitting.");
      documentsRef.current?.scrollIntoView({ behavior: "smooth" });
      return;
    }
    submitMutation.mutate();
  }

  const companyName = (customer as any)?.company?.name ?? "—";
  const companyTin = (customer as any)?.company?.tin ?? "—";
  const contactName = (customer as any)?.profile
    ? `${(customer as any).profile.firstName ?? ""} ${(customer as any).profile.lastName ?? ""}`.trim() ||
    "—"
    : "—";
  const contactEmail = (customer as any)?.profile?.email ?? "—";

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="flex flex-col gap-6">
        <Breadcrumbs
          items={[
            { label: "Bookings", href: "/bookings" },
            { label: booking.reference },
          ]}
        />

        <Card>
          <CardHeader>
            <div className="flex items-center gap-6">
              <div className="flex size-14 items-center justify-center rounded-2xl bg-muted text-muted-foreground">
                <Package className="size-6" />
              </div>
              <div className="flex flex-1 flex-col gap-1">
                <div className="flex items-center gap-3">
                  <h1 className="text-2xl font-black tracking-tight text-foreground">
                    {booking.reference}
                  </h1>
                  <StatusBadge status={booking.status} />
                </div>
                <p className="text-xs text-muted-foreground">
                  {booking.status === "CHANGES_REQUESTED"
                    ? "Staff has requested changes. Please review, update, and resubmit."
                    : "Complete the steps below to submit your booking request."}
                </p>
              </div>

              <div className="flex items-center gap-3">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => navigate(`/bookings/${booking.id}/edit`)}
                >
                  <FileText className="size-4" />
                  Edit
                </Button>
                <Button
                  type="button"
                  onClick={handleSubmitRequest}
                  disabled={submitMutation.isPending}
                >
                  {submitMutation.isPending ? (
                    <LoaderCircle className="animate-spin" />
                  ) : (
                    <CheckCircle2 />
                  )}
                  {submitMutation.isPending
                    ? "Submitting..."
                    : "Confirm Booking Request"}
                </Button>
              </div>
            </div>
          </CardHeader>
        </Card>

        {booking.status === "CHANGES_REQUESTED" && booking.latestChangeRequestNote && (
          <div className="flex items-start gap-3 rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800">
            <AlertCircle className="mt-0.5 h-4 w-4 shrink-0 text-amber-500" />
            <div>
              <p className="font-semibold">Changes Requested by Staff</p>
              <p className="mt-1 text-amber-700">{booking.latestChangeRequestNote}</p>
            </div>
          </div>
        )}

        {uploadMutation.isError && (
          <div className="flex items-start gap-3 rounded-xl border border-destructive/20 bg-destructive/10 p-4 text-sm text-destructive">
            <AlertCircle className="mt-0.5 h-4 w-4 shrink-0 text-destructive" />
            <div>
              <p className="font-semibold">Document upload failed</p>
              <p className="mt-1 text-destructive/80">
                {uploadMutation.error instanceof Error
                  ? uploadMutation.error.message
                  : "An unexpected error occurred."}
              </p>
            </div>
          </div>
        )}

        {submitMutation.isError && (
          <div className="flex items-start gap-3 rounded-xl border border-destructive/20 bg-destructive/10 p-4 text-sm text-destructive">
            <AlertCircle className="mt-0.5 h-4 w-4 shrink-0 text-destructive" />
            <div>
              <p className="font-semibold">Submission failed</p>
              <p className="mt-1 text-destructive/80">
                {submitMutation.error instanceof Error
                  ? submitMutation.error.message
                  : "An unexpected error occurred."}
              </p>
            </div>
          </div>
        )}

        {cancelMutation.isError && (
          <div className="flex items-start gap-3 rounded-xl border border-destructive/20 bg-destructive/10 p-4 text-sm text-destructive">
            <AlertCircle className="mt-0.5 h-4 w-4 shrink-0 text-destructive" />
            <div>
              <p className="font-semibold">Cancel failed</p>
              <p className="mt-1 text-destructive/80">
                {cancelMutation.error instanceof Error
                  ? cancelMutation.error.message
                  : "An unexpected error occurred."}
              </p>
            </div>
          </div>
        )}

        <Card
          className={cn(
            pricing ? "border-primary/20 bg-primary/5" : "",
          )}
        >
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-base">
              <DollarSign className="size-4 text-primary" />
              Pricing Estimation
            </CardTitle>
            <CardDescription>
              Price estimate based on your booking details.
            </CardDescription>
          </CardHeader>
          <CardContent>
            {pricing ? (
              <div className="flex flex-col gap-4">
                <div className="overflow-hidden rounded-lg border">
                  <table className="w-full text-left text-xs">
                    <thead className="bg-muted text-muted-foreground">
                      <tr>
                        <th className="px-4 py-2 font-semibold">Description</th>
                        <th className="px-4 py-2 font-semibold text-right">
                          Amount
                        </th>
                      </tr>
                    </thead>
                    <tbody className="divide-y">
                      {pricing.lineItems.map((item, i) => (
                        <tr key={i}>
                          <td className="px-4 py-2 text-foreground">
                            {item.description}
                          </td>
                          <td className="px-4 py-2 text-right font-medium text-foreground">
                            {item.amount.toLocaleString()} {item.currency}
                          </td>
                        </tr>
                      ))}
                      <tr className="bg-primary/5 font-bold">
                        <td className="px-4 py-2 text-foreground">
                          Total Estimated Cost
                        </td>
                        <td className="px-4 py-2 text-right text-foreground">
                          {pricing.totalAmount.toLocaleString()}{" "}
                          {pricing.currency}
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            ) : (
              <p className="text-xs text-muted-foreground">
                Pricing will be calculated after submission.
              </p>
            )}
          </CardContent>
        </Card>

        <Card ref={documentsRef}>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-base">
              <FileText className="size-4 text-primary" />
              Required Documents
            </CardTitle>
            <CardDescription>
              Provide the necessary documents for this booking. Some information
              is pre-filled from your company profile.
            </CardDescription>
          </CardHeader>
          <CardContent className="flex flex-col gap-6">
            {docError && (
              <div className="flex items-start gap-3 rounded-xl border border-destructive/20 bg-destructive/10 p-4 text-sm text-destructive">
                <AlertCircle className="mt-0.5 h-4 w-4 shrink-0 text-destructive" />
                <p className="font-semibold">{docError}</p>
              </div>
            )}
            <div className="rounded-lg border border-primary/10 bg-primary/[0.02] p-4">
              <h3 className="mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wide text-foreground">
                <Building2 className="size-3.5 text-primary" />
                Company Information (from profile)
              </h3>
              <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                <InfoItem label="Company Name" value={companyName} />
                <InfoItem label="TIN / VAT" value={companyTin} />
                <InfoItem label="Contact Person" value={contactName} />
                <InfoItem label="Contact Email" value={contactEmail} />
              </div>
              <p className="mt-3 text-xs text-muted-foreground">
                To update your company information, go to{" "}
                <button
                  type="button"
                  className="text-primary underline-offset-2 hover:underline"
                  onClick={() => navigate("/settings")}
                >
                  Settings
                </button>
                .
              </p>
            </div>

            <Separator />

            <div>
              <h3 className="mb-3 flex items-center gap-2 text-xs font-bold uppercase tracking-wide text-foreground">
                <FileUp className="size-3.5 text-primary" />
                Upload Booking Documents
              </h3>
              <div className="flex flex-col gap-4">
                {REQUIRED_DOC_FIELDS.map((doc) => {
                  const isUploaded = uploadedCodes.has(doc.key);
                  return (
                    <div
                      key={doc.key}
                      className="flex flex-col gap-1.5 sm:flex-row sm:items-center sm:justify-between"
                    >
                      <label className="flex items-center gap-2 text-xs font-medium text-foreground">
                        {isUploaded && (
                          <CheckCircle2 className="size-3.5 text-primary" />
                        )}
                        {doc.label}
                      </label>
                      <div className="flex items-center gap-2">
                        {isUploaded ? (
                          <span className="inline-flex items-center gap-1 rounded-lg border border-primary/20 bg-primary/10 px-3 py-1.5 text-xs font-medium text-primary">
                            <CheckCircle2 className="size-3" />
                            Uploaded
                          </span>
                        ) : (
                          <>
                            <input
                              ref={(el) => {
                                fileInputRefs.current[doc.key] = el;
                              }}
                              type="file"
                              accept=".pdf,.jpg,.jpeg,.png"
                              className="hidden"
                              onChange={(e) => {
                                handleFileSelect(
                                  doc.key,
                                  e.target.files?.[0] ?? null,
                                );
                              }}
                            />
                            <button
                              type="button"
                              className={cn(
                                "inline-flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors",
                                selectedFiles[doc.key]
                                  ? "border-primary/20 bg-primary/10 text-primary"
                                  : "border-border bg-background text-muted-foreground hover:border-foreground/20 hover:text-foreground",
                              )}
                              onClick={() =>
                                fileInputRefs.current[doc.key]?.click()
                              }
                            >
                              <Upload className="size-3" />
                              {selectedFiles[doc.key]
                                ? selectedFiles[doc.key]!.name
                                : "Choose file"}
                            </button>
                            {selectedFiles[doc.key] && (
                              <button
                                type="button"
                                className="text-muted-foreground hover:text-destructive"
                                onClick={() => handleFileSelect(doc.key, null)}
                              >
                                <XCircle className="size-4" />
                              </button>
                            )}
                          </>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>

              <div className="mt-6">
                <Button
                  type="button"
                  onClick={handleUploadAll}
                  disabled={!anyFileSelected || uploadMutation.isPending}
                >
                  {uploadMutation.isPending ? (
                    <LoaderCircle className="mr-1 h-4 w-4 animate-spin" />
                  ) : (
                    <Upload className="mr-1 h-4 w-4" />
                  )}
                  {uploadMutation.isPending
                    ? "Uploading..."
                    : anyFileSelected
                      ? "Upload Selected Documents"
                      : "Select files to upload"}
                </Button>
                {uploadMutation.isSuccess && (
                  <p className="mt-2 flex items-center gap-1.5 text-xs text-primary">
                    <CheckCircle2 className="size-3" />
                    Documents uploaded successfully
                  </p>
                )}
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="border-destructive/20">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-base text-destructive">
              <AlertTriangle className="size-4" />
              Cancel Booking
            </CardTitle>
            <CardDescription>
              If you no longer need this booking, you can cancel it.
            </CardDescription>
          </CardHeader>
          <CardContent className="flex flex-col gap-3">
            <p className="text-xs text-muted-foreground">
              Cancelling will terminate this booking request and cannot be
              undone.
            </p>
            <Dialog open={cancelDialogOpen} onOpenChange={setCancelDialogOpen}>
              <DialogTrigger asChild>
                <Button
                  type="button"
                  variant="destructive"
                  className="self-start"
                >
                  <XCircle className="mr-1 h-4 w-4" />
                  Cancel Booking
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>Cancel Booking</DialogTitle>
                  <DialogDescription>
                    Are you sure you want to cancel this booking? This action
                    cannot be undone.
                  </DialogDescription>
                </DialogHeader>
                <div className="flex flex-col gap-3 py-2">
                  <label className="text-xs font-medium text-foreground">
                    Reason for cancellation
                  </label>
                  <input
                    type="text"
                    placeholder="Optional — provide a reason"
                    className="rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground outline-none focus:border-destructive/50"
                    value={cancelReason}
                    onChange={(e) => setCancelReason(e.target.value)}
                    autoFocus
                  />
                </div>
                <DialogFooter>
                  <DialogClose asChild>
                    <Button type="button" variant="outline">
                      Keep Booking
                    </Button>
                  </DialogClose>
                  <Button
                    type="button"
                    variant="destructive"
                    onClick={handleCancel}
                    disabled={cancelMutation.isPending}
                  >
                    {cancelMutation.isPending ? (
                      <LoaderCircle className="mr-1 h-4 w-4 animate-spin" />
                    ) : (
                      <XCircle className="mr-1 h-4 w-4" />
                    )}
                    Yes, Cancel Booking
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

function ReadonlyBookingView({ booking }: { booking: Freight.IBooking }) {
  const navigate = useNavigate();
  const queryClient = useQueryClient();

  const payMutation = useMutation({
    mutationFn: () => api.bookings.pay.call({ id: booking.id }),
    onSuccess: (data) => {
      if (data.redirectUrl) {
        window.location.href = data.redirectUrl;
      }
    },
  });

  const normalizedStatus = booking.status as keyof typeof STATUS_MAP;
  const statusConfig = STATUS_MAP[normalizedStatus] || STATUS_MAP.DRAFT;
  const currentStageIndex = statusConfig.stage;

  const pricing = booking.pricingBreakdown;

  const uploadedCodes = useMemo(
    () => new Set(booking.files?.map((f) => f.code) ?? []),
    [booking.files],
  );

  return (
    <div className="container mx-auto max-w-7xl px-4 py-8">
      <div className="flex flex-col gap-8">
        <Breadcrumbs
          items={[
            { label: "Bookings", href: "/bookings" },
            { label: booking.reference },
          ]}
        />

        <Card>
          <CardHeader>
            <div className="flex items-center gap-6">
              <div className="flex size-14 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
                <Package className="size-6" />
              </div>
              <div className="flex flex-1 flex-col gap-1">
                <div className="flex items-center gap-3">
                  <h1 className="text-2xl font-black tracking-tight text-foreground">
                    {booking.reference}
                  </h1>
                  <StatusBadge status={normalizedStatus} />
                </div>
                <div className="flex items-center gap-3 text-xs text-muted-foreground">
                  <span className="flex items-center gap-1">
                    <Calendar className="size-3" />
                    {format(
                      new Date(booking.scheduledDate ?? booking.createdAt),
                      "MMM d, yyyy HH:mm",
                    )}
                  </span>
                </div>
              </div>
              {normalizedStatus === "FULLY_EXECUTED" && booking.paymentStatus !== "PAID" && (
                <Button
                  type="button"
                  onClick={() => payMutation.mutate()}
                  disabled={payMutation.isPending}
                >
                  {payMutation.isPending ? (
                    <LoaderCircle className="mr-1 h-4 w-4 animate-spin" />
                  ) : (
                    <CreditCard className="mr-1 h-4 w-4" />
                  )}
                  {payMutation.isPending ? "Processing..." : "Pay Now"}
                </Button>
              )}
            </div>
          </CardHeader>
        </Card>

        {renderContractCard(booking, navigate, payMutation)}

        {pricing && (
          <Card className="border-primary/20 bg-primary/5">
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-base">
                <DollarSign className="size-4 text-primary" />
                Pricing Breakdown
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="overflow-hidden rounded-lg border">
                <table className="w-full text-left text-xs">
                  <thead className="bg-muted text-muted-foreground">
                    <tr>
                      <th className="px-4 py-2 font-semibold">Description</th>
                      <th className="px-4 py-2 font-semibold text-right">Amount</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    {pricing.lineItems.map((item, i) => (
                      <tr key={i}>
                        <td className="px-4 py-2 text-foreground">{item.description}</td>
                        <td className="px-4 py-2 text-right font-medium text-foreground">
                          {item.amount.toLocaleString()} {item.currency}
                        </td>
                      </tr>
                    ))}
                    <tr className="bg-primary/5 font-bold">
                      <td className="px-4 py-2 text-foreground">Total Estimated Cost</td>
                      <td className="px-4 py-2 text-right text-foreground">
                        {pricing.totalAmount.toLocaleString()} {pricing.currency}
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        )}

        {booking.files && booking.files.length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-base">
                <FileText className="size-4 text-primary" />
                Uploaded Documents ({booking.files.length})
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                {booking.files.map((file) => (
                  <a
                    key={file.id}
                    href={file.signedUrl ?? file.url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center gap-3 rounded-lg border border-border p-3 transition hover:border-primary/40"
                  >
                    <div className="flex size-8 items-center justify-center rounded-lg bg-primary/10">
                      <FileText className="size-4 text-primary" />
                    </div>
                    <div className="min-w-0 flex-1">
                      <p className="truncate text-sm font-medium text-foreground">
                        {file.name}
                      </p>
                      <p className="text-xs text-muted-foreground">
                        {file.code.replace(/_/g, " ")}
                      </p>
                    </div>
                  </a>
                ))}
              </div>
            </CardContent>
          </Card>
        )}

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-base">
              <History className="size-4 text-primary" />
              Booking Status Lifecycle
            </CardTitle>
            <CardDescription>
              Track the journey from request to completion
            </CardDescription>
          </CardHeader>
          <CardContent className="flex flex-col gap-8">
            <div className="relative flex w-full justify-between px-2">
              <div className="absolute top-4 left-0 h-0.5 w-full bg-muted">
                <div
                  className="h-full bg-primary transition-all duration-500"
                  style={{
                    width:
                      currentStageIndex >= 0
                        ? `${(currentStageIndex / (PROGRESS_STAGES.length - 1)) * 100}%`
                        : "0%",
                  }}
                />
              </div>

              {PROGRESS_STAGES.map((stage, idx) => {
                const isCompleted = idx < currentStageIndex;
                const isActive = idx === currentStageIndex;

                return (
                  <div
                    key={stage.label}
                    className="relative z-10 flex flex-col items-center gap-2"
                  >
                    <div
                      className={cn(
                        "flex size-8 items-center justify-center rounded-full border-2 transition-all duration-300 bg-background",
                        isCompleted
                          ? "border-primary text-primary"
                          : isActive
                            ? "border-primary text-primary shadow-[0_0_10px_rgba(16,185,129,0.3)] scale-110"
                            : "border-muted text-muted-foreground",
                      )}
                    >
                      {isCompleted ? (
                        <CheckCircle2 className="size-4" />
                      ) : (
                        <stage.icon className="size-4" />
                      )}
                    </div>
                    <span
                      className={cn(
                        "text-xs font-bold uppercase tracking-widest",
                        isActive ? "text-primary" : "text-muted-foreground",
                      )}
                    >
                      {stage.label}
                    </span>
                  </div>
                );
              })}
            </div>

            <div className="flex flex-col gap-4 rounded-xl border border-border/50 bg-muted/20 p-5 md:flex-row md:items-center">
              <div className="flex size-10 shrink-0 items-center justify-center rounded-full bg-background shadow-sm">
                {normalizedStatus === "CANCELLED" ? (
                  <AlertTriangle className="size-5 text-destructive" />
                ) : (
                  <Info className="size-5 text-primary" />
                )}
              </div>
              <div className="flex flex-col gap-0.5">
                <h4
                  className={cn(
                    "text-sm font-black uppercase tracking-tight",
                    statusConfig.color,
                  )}
                >
                  {statusConfig.title}
                </h4>
                <p className="text-xs font-medium text-muted-foreground">
                  {statusConfig.description}
                </p>
              </div>
              {normalizedStatus !== "CANCELLED" &&
                normalizedStatus !== "DELIVERED" && (
                  <div className="ml-auto flex items-center gap-4 border-l border-border pl-6">
                    <div className="flex flex-col">
                      <p className="text-xs font-bold uppercase text-muted-foreground">
                        Est. Waiting
                      </p>
                      <p className="text-xs font-black text-foreground">
                        1-2 Working Days
                      </p>
                    </div>
                    <CreditCard className="size-5 text-muted-foreground" />
                  </div>
                )}
            </div>
          </CardContent>
        </Card>

        <div className="grid grid-cols-1 gap-8 lg:grid-cols-3">
          <div className="flex flex-col gap-8 lg:col-span-2">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2 text-base">
                  <Anchor className="size-4 text-primary" />
                  Route & Service
                </CardTitle>
              </CardHeader>
              <CardContent className="flex flex-col gap-6">
                <div className="flex flex-col items-center justify-between gap-4 rounded-xl border bg-muted/30 p-4 md:flex-row">
                  <RouteEndpoint
                    label="Origin Yard"
                    station={
                      booking.originYard?.label ??
                      booking.originYard?.code ??
                      "—"
                    }
                    icon={<MapPin />}
                  />
                  <div className="flex flex-col items-center gap-1 text-primary">
                    <div className="flex items-center gap-2">
                      <Train className="size-5" />
                      <ArrowRight className="size-4" />
                    </div>
                    <Badge
                      variant="outline"
                      className="border-primary/20 bg-primary/5 text-xs font-bold uppercase"
                    >
                      Rail
                    </Badge>
                  </div>
                  <RouteEndpoint
                    label="Destination Yard"
                    station={
                      booking.destinationYard?.label ??
                      booking.destinationYard?.code ??
                      "—"
                    }
                    icon={<MapPin />}
                  />
                </div>

                <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
                  <InfoItem
                    icon={<Layers />}
                    label="Service"
                    value={
                      booking.serviceType === "RAIL_AND_FORWARDING"
                        ? "Rail & Forwarding"
                        : "Rail Only"
                    }
                  />
                  <InfoItem
                    icon={<ShieldCheck />}
                    label="Return"
                    value={
                      booking.equipmentReturn === "WITH_RETURN"
                        ? "With Return"
                        : "Without Return"
                    }
                  />
                  <InfoItem
                    icon={<FileText />}
                    label="Trade"
                    value={
                      booking.tradeDirection === "IMPORT" ? "Import" : "Export"
                    }
                  />
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2 text-base">
                  <Truck className="size-4 text-primary" />
                  Mile Services
                </CardTitle>
              </CardHeader>
              <CardContent className="grid grid-cols-1 gap-6 md:grid-cols-2">
                <div className="flex flex-col gap-3">
                  <h3 className="border-l-4 border-primary pl-3 text-xs font-bold uppercase tracking-wide text-foreground">
                    First Mile
                  </h3>
                  <InfoItem
                    label="Address"
                    value={
                      booking.firstMileEnabled && booking.firstMilePickupAddress
                        ? booking.firstMilePickupAddress
                        : "Not requested"
                    }
                  />
                </div>
                <div className="flex flex-col gap-3">
                  <h3 className="border-l-4 border-primary pl-3 text-xs font-bold uppercase tracking-wide text-foreground">
                    Last Mile
                  </h3>
                  <p className="pl-4 text-xs text-muted-foreground italic">
                    {booking.lastMileEnabled && booking.lastMileDeliveryAddress
                      ? booking.lastMileDeliveryAddress
                      : "Not requested"}
                  </p>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2 text-base">
                  <Package className="size-4 text-primary" />
                  Cargo Specifications
                </CardTitle>
              </CardHeader>
              <CardContent className="flex flex-col gap-6">
                <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
                  <InfoItem
                    icon={<Package />}
                    label="Freight Type"
                    value={
                      booking.freightType === "BULK" ? "Bulk" : "Break Bulk"
                    }
                  />
                  <InfoItem
                    icon={<Weight />}
                    label="Weight (VGM)"
                    value={`${booking.cargoTotalWeightVgm} Tons`}
                  />
                  <InfoItem
                    icon={<Ship />}
                    label="Currency"
                    value={booking.paymentCurrency}
                  />
                </div>

                {booking.containers && booking.containers.length > 0 && (
                  <>
                    <Separator />
                    <div className="flex flex-col gap-3">
                      <h3 className="text-xs font-bold uppercase tracking-wide text-foreground">
                        Load Details
                      </h3>
                      <div className="rounded-lg border overflow-hidden">
                        <table className="w-full text-left text-xs">
                          <thead className="bg-muted text-muted-foreground">
                            <tr>
                              <th className="px-3 py-2 font-semibold">Type</th>
                              <th className="px-3 py-2 font-semibold text-center">
                                Quantity
                              </th>
                              <th className="px-3 py-2 font-semibold text-right">
                                VGM (Tons)
                              </th>
                            </tr>
                          </thead>
                          <tbody className="divide-y">
                            {booking.containers.map((c, i) => (
                              <tr key={i}>
                                <td className="px-3 py-2 font-medium">
                                  {c.type}
                                </td>
                                <td className="px-3 py-2 text-center">
                                  {c.qty} Units
                                </td>
                                <td className="px-3 py-2 text-right">
                                  {c.vgm}t
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    </div>
                  </>
                )}
              </CardContent>
            </Card>
          </div>

          <div className="flex flex-col gap-8">
            <Card className="border-primary/20 bg-primary/[0.02]">
              <CardHeader>
                <CardTitle className="flex items-center gap-2 text-base">
                  <FileText className="size-4 text-primary" />
                  Contract Info
                </CardTitle>
              </CardHeader>
              <CardContent className="flex flex-col gap-4">
                <InfoItem
                  label="Type"
                  value={booking.contractType === "RENEWAL" ? "Renewal" : "New"}
                />
                <InfoItem label="Customer ID" value={booking.customerId} />
                <Separator />
                <div className="flex flex-wrap gap-2">
                  <Badge variant="outline" className="bg-background text-xs">
                    Hazardous: {booking.isHazardous ? "Yes" : "No"}
                  </Badge>
                  <Badge variant="outline" className="bg-background text-xs">
                    Refrigerated: {booking.isRefrigerated ? "Yes" : "No"}
                  </Badge>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-base">Additional Info</CardTitle>
              </CardHeader>
              <CardContent className="flex flex-col gap-4">
                {booking.freightSubtype && (
                  <div className="flex flex-col gap-1">
                    <p className="text-xs font-bold uppercase tracking-tight text-muted-foreground">
                      Cargo Description
                    </p>
                    <p className="text-xs text-foreground leading-relaxed italic">
                      "{booking.freightSubtype}"
                    </p>
                  </div>
                )}
                {booking.financialTerms && (
                  <>
                    <Separator />
                    <div className="flex flex-col gap-1">
                      <p className="text-xs font-bold uppercase tracking-tight text-muted-foreground">
                        Financial Terms
                      </p>
                      <div className="rounded-lg bg-amber-50/50 border border-amber-100 p-2">
                        <p className="text-xs text-amber-900 flex gap-2">
                          <StickyNote className="size-3 shrink-0 mt-0.5 text-amber-500" />
                          {booking.financialTerms}
                        </p>
                      </div>
                    </div>
                  </>
                )}
                {!booking.freightSubtype && !booking.financialTerms && (
                  <p className="text-xs text-muted-foreground italic">
                    No additional information provided.
                  </p>
                )}
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    </div>
  );
}

function renderContractCard(
  booking: Freight.IBooking,
  navigate: ReturnType<typeof useNavigate>,
  payMutation: { mutate: () => void; isPending: boolean },
) {
  const s = booking.status;
  if (
    s !== "APPROVED_PENDING_SIGNATURE" &&
    s !== "CONTRACT_READY" &&
    s !== "SIGNED_CUSTOMER" &&
    s !== "FULLY_EXECUTED"
  ) {
    return null;
  }

  const config: Record<
    string,
    { title: string; description: string; buttonLabel?: string }
  > = {
    APPROVED_PENDING_SIGNATURE: {
      title: "Contract being prepared",
      description:
        "Your booking has been approved. The contract is being generated and will be available shortly.",
    },
    CONTRACT_READY: {
      title: "Contract ready for signature",
      description:
        "Review the agreement and apply your digital signature.",
      buttonLabel: "View & sign contract",
    },
    SIGNED_CUSTOMER: {
      title: "You have signed the contract",
      description:
        "Your signature has been submitted. Awaiting staff signature to finalize.",
      buttonLabel: "View contract",
    },
    FULLY_EXECUTED: {
      title: "Contract fully executed",
      description:
        "The contract has been fully signed and executed by all parties.",
      buttonLabel: "View contract",
    },
  };

  const c = config[s];

  return (
    <Card
      className={cn(
        "border-primary/30 bg-primary/5",
        s === "FULLY_EXECUTED" && "border-emerald-300 bg-emerald-50",
      )}
    >
      <CardContent className="flex flex-col gap-4 p-6 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <p className="font-semibold text-foreground">{c.title}</p>
          <p className="text-sm text-muted-foreground">{c.description}</p>
        </div>
        {c.buttonLabel && (
          <button
            type="button"
            className="inline-flex items-center justify-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground"
            onClick={() => navigate(`/bookings/${booking.id}/contract`)}
          >
            <FileSignature className="size-4" />
            {c.buttonLabel}
          </button>
        )}
      </CardContent>
    </Card>
  );
}

function RouteEndpoint({
  label,
  station,
  icon,
}: {
  label: string;
  station: string;
  icon: React.ReactNode;
}) {
  return (
    <div className="flex items-center gap-3">
      <div className="flex size-10 items-center justify-center rounded-xl bg-primary text-primary-foreground shadow-sm">
        {icon && <div className="[&_svg]:size-5">{icon}</div>}
      </div>
      <div className="flex flex-col">
        <p className="text-xs font-bold uppercase tracking-wide text-muted-foreground">
          {label}
        </p>
        <p className="text-sm font-black text-foreground">{station}</p>
      </div>
    </div>
  );
}

function InfoItem({
  icon,
  label,
  value,
}: {
  icon?: React.ReactNode;
  label: string;
  value?: string | number | null;
}) {
  return (
    <div className="flex items-start gap-2">
      {icon && (
        <div className="mt-0.5 text-muted-foreground [&_svg]:size-3.5">
          {icon}
        </div>
      )}
      <div className="flex flex-col">
        <p className="text-xs font-bold uppercase tracking-tight text-muted-foreground">
          {label}
        </p>
        <p className="text-xs font-bold text-foreground">{value ?? "—"}</p>
      </div>
    </div>
  );
}

function StatusBadge({ status }: { status: string }) {
  const statusColors: Record<string, string> = {
    DRAFT: "bg-muted text-muted-foreground border-border",
    CHANGES_REQUESTED: "bg-amber-50 text-amber-700 border-amber-200",
    SUBMITTED: "bg-primary/10 text-primary border-primary/20",
    PENDING_APPROVAL: "bg-primary/10 text-primary border-primary/20",
    APPROVED_PENDING_SIGNATURE: "bg-primary/10 text-primary border-primary/20",
    APPROVED: "bg-primary/10 text-primary border-primary/20",
    CONTRACT_READY: "bg-primary/10 text-primary border-primary/20",
    SIGNED_CUSTOMER: "bg-primary/10 text-primary border-primary/20",
    FULLY_EXECUTED: "bg-primary/10 text-primary border-primary/20",
    PNR_GENERATED: "bg-primary/10 text-primary border-primary/20",
    PAYMENT_VERIFICATION_IN_PROGRESS: "bg-primary/10 text-primary border-primary/20",
    PAID: "bg-primary/10 text-primary border-primary/20",
    CONFIRMED: "bg-primary/10 text-primary border-primary/20",
    IN_TRANSIT: "bg-primary/10 text-primary border-primary/20",
    PENDING_CONSOLIDATION: "bg-primary/10 text-primary border-primary/20",
    CONSOLIDATED: "bg-primary/10 text-primary border-primary/20",
    COMPLETED: "bg-muted text-foreground border-border",
    DELIVERED: "bg-muted text-foreground border-border",
    REJECTED: "bg-destructive/10 text-destructive border-destructive/20",
    CANCELLED: "bg-destructive/10 text-destructive border-destructive/20",
  };

  return (
    <Badge
      variant="outline"
      className={cn(
        "px-2 py-0.5 font-bold uppercase tracking-wider text-xs",
        statusColors[status] || "bg-muted",
      )}
    >
      {status.replace(/_/g, " ")}
    </Badge>
  );
}
