"use client";

import {
  useCallback,
  useEffect,
  useState,
  type ElementType,
} from "react";
import Link from "next/link";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import {
  cancelVehicleBookingAction,
  getUserVehicleBookingsAction,
  type UserVehicleBooking,
  type UserVehicleBookingRoute,
  type UserVehicleBookingSnapshot,
  type VehicleBookingRefundRequest,
} from "@/features/booking/actions/vehicle-bookings-actions";
import {
  createMyPaymentMethodAction,
  getMyPaymentMethodsAction,
} from "@/features/payment/actions/payment-methods-actions";
import type { PaymentMethodItem } from "@/core/api/services/payment-methods";
import { useToastEnhanced } from "@/hooks/use-toast-enhanced";
import { cn, getStorageUrl } from "@/lib/utils";
import {
  Calendar,
  Car,
  CreditCard,
  Eye,
  IndianRupee,
  Loader2,
  MapPin,
  Phone,
  Plus,
  ReceiptText,
  Search,
  User,
  X,
} from "lucide-react";
import Image from "next/image";

const statusTabs = [
  { id: "all", label: "All" },
  { id: "pending", label: "Pending" },
  { id: "confirm", label: "Confirmed" },
  { id: "cancel", label: "Cancelled" },
] as const;

const statusStyles: Record<string, string> = {
  pending: "border-amber-200 bg-amber-50 text-amber-700",
  confirm: "border-emerald-200 bg-emerald-50 text-emerald-700",
  completed: "border-emerald-200 bg-emerald-50 text-emerald-700",
  paid: "border-emerald-200 bg-emerald-50 text-emerald-700",
  cancel: "border-red-200 bg-red-50 text-red-700",
  cancelled: "border-red-200 bg-red-50 text-red-700",
  failed: "border-red-200 bg-red-50 text-red-700",
  default: "border-slate-200 bg-slate-50 text-slate-700",
};

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";

type AddMethodForm = {
  type: "bank" | "upi";
  accountHolder: string;
  bankName: string;
  accountNumber: string;
  ifscCode: string;
  upiId: string;
};

const INITIAL_METHOD_FORM: AddMethodForm = {
  type: "bank",
  accountHolder: "",
  bankName: "",
  accountNumber: "",
  ifscCode: "",
  upiId: "",
};

function toNumber(value: string | number | null | undefined) {
  if (value == null || value === "") return 0;
  const amount = Number(value);
  return Number.isFinite(amount) ? amount : 0;
}

function formatCurrency(value: string | number | null | undefined) {
  return new Intl.NumberFormat("en-IN", {
    style: "currency",
    currency: "INR",
    maximumFractionDigits: 0,
  }).format(toNumber(value));
}

function formatDate(value: string | null | undefined) {
  if (!value) return "Not set";
  return new Intl.DateTimeFormat("en-IN", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  }).format(new Date(value));
}

function formatLabel(value: string | null | undefined) {
  if (!value) return "NA";
  return value
    .replace(/_/g, " ")
    .replace(/\b\w/g, (char) => char.toUpperCase());
}

type RoutePoint = {
  id: string;
  name: string;
  meta: string;
  endpoint: boolean;
};

function parseSnapshotValue(
  raw: UserVehicleBooking["vehicle_booking_json"]
): UserVehicleBookingSnapshot | null {
  if (!raw) return null;
  if (typeof raw === "object") return raw;
  try {
    const parsed: unknown = JSON.parse(raw);
    if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
      return parsed as UserVehicleBookingSnapshot;
    }
  } catch {
    return null;
  }
  return null;
}

function parseBookingSnapshot(booking: UserVehicleBooking) {
  return (
    parseSnapshotValue(booking.vehicle_booking_json) ??
    parseSnapshotValue(booking.fix_package_json) ??
    null
  );
}

function readObjectValue<T>(source: unknown, ...keys: string[]): T | null {
  if (!source || typeof source !== "object") return null;
  const record = source as Record<string, unknown>;
  for (const key of keys) {
    const value = record[key];
    if (value && typeof value === "object") return value as T;
  }
  return null;
}

function getSnapshotRoute(snapshot: UserVehicleBookingSnapshot | null) {
  if (!snapshot) return null;
  const nestedRoute =
    snapshot.route ??
    snapshot.vehicleRoute ??
    snapshot.vehicle_route ??
    readObjectValue<UserVehicleBookingRoute>(
      snapshot,
      "route_detail",
      "vehicle_route_detail",
      "vehicleBookingRoute"
    );
  if (nestedRoute) return nestedRoute;

  if (
    "start_point_city" in snapshot ||
    "end_point_city" in snapshot ||
    "multi_cities" in snapshot
  ) {
    return snapshot as UserVehicleBookingRoute;
  }

  return null;
}

function getSnapshotVehicle(snapshot: UserVehicleBookingSnapshot | null) {
  if (!snapshot) return null;
  return (
    snapshot.vehicle ??
    readObjectValue<UserVehicleBooking["vehicle"]>(
      snapshot,
      "vehicle_detail",
      "vehicleDetails",
      "selected_vehicle"
    )
  );
}

function routeHasCityNames(route: UserVehicleBookingRoute | null | undefined) {
  return Boolean(
    getRouteCityName(route, "start") && getRouteCityName(route, "end")
  );
}

function getRoute(booking: UserVehicleBooking) {
  const snapshot = parseBookingSnapshot(booking);
  const snapshotRoute = getSnapshotRoute(snapshot);
  if (routeHasCityNames(snapshotRoute)) return snapshotRoute;
  if (routeHasCityNames(booking.vehicleRoute)) return booking.vehicleRoute;
  if (routeHasCityNames(booking.vehicle_route)) return booking.vehicle_route;
  return booking.vehicleRoute ?? booking.vehicle_route ?? snapshotRoute ?? null;
}

function getVehicle(booking: UserVehicleBooking) {
  return booking.vehicle ?? getSnapshotVehicle(parseBookingSnapshot(booking));
}

function getCancelledBy(booking: UserVehicleBooking) {
  return booking.cancelledBy ?? booking.cancelled_by ?? null;
}

function getRefundRequest(booking: UserVehicleBooking) {
  return booking.refund_request ?? booking.refundRequest ?? null;
}

function getStartCity(booking: UserVehicleBooking) {
  const route = getRoute(booking);
  return getRouteCityName(route, "start") ?? "Pickup";
}

function getEndCity(booking: UserVehicleBooking) {
  const route = getRoute(booking);
  return getRouteCityName(route, "end") ?? "Drop";
}

function getRouteCityName(
  route: UserVehicleBookingRoute | null | undefined,
  position: "start" | "end"
) {
  if (!route) return null;
  const routeRecord = route as Record<string, unknown>;
  const direct =
    position === "start" ? route.start_point_city : route.end_point_city;
  if (direct?.name) return direct.name;

  const possibleKeys =
    position === "start"
      ? ["start_city", "pickup_city", "from_city", "startPointCity"]
      : ["end_city", "drop_city", "to_city", "endPointCity"];

  for (const key of possibleKeys) {
    const value = routeRecord[key];
    if (value && typeof value === "object" && "name" in value) {
      const name = (value as { name?: unknown }).name;
      if (typeof name === "string" && name.trim()) return name;
    }
    if (typeof value === "string" && value.trim()) return value;
  }

  return null;
}

function formatRouteType(value: string | null | undefined) {
  if (value === "multi_city") return "Multi City Trip";
  if (value === "round_trip") return "Round Trip";
  if (value === "one_way") return "One Way Trip";
  return formatLabel(value ?? "Route");
}

function formatStopDistance(value: string | number | null | undefined) {
  if (value == null || value === "") return "Stoppage";
  const distance = String(value);
  return distance.toLowerCase().includes("km") ? distance : `${distance} km`;
}

function getRoutePoints(booking: UserVehicleBooking): RoutePoint[] {
  const route = getRoute(booking);
  if (!route) return [];

  const stops = (route.multi_cities ?? [])
    .filter((stop) => stop.status !== "inactive")
    .slice()
    .sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0));

  return [
    {
      id: "pickup",
      name: getRouteCityName(route, "start") ?? "Pickup",
      meta: "Pickup point",
      endpoint: true,
    },
    ...stops.map((stop, index) => ({
      id: `stop-${stop.id ?? stop.stopage_city_id ?? index}`,
      name: stop.stopage_city?.name ?? "Stoppage",
      meta: formatStopDistance(stop.distance_from_previous_stopage),
      endpoint: false,
    })),
    {
      id: "drop",
      name: getRouteCityName(route, "end") ?? "Drop",
      meta: "Drop point",
      endpoint: true,
    },
  ];
}

function getMethodTitle(method: PaymentMethodItem) {
  const label = method.method_type.replace(/_/g, " ");
  if (method.method_type === "UPI" && method.details.upi_id) {
    return `${method.details.upi_id} (${label})`;
  }
  if (method.method_type === "NET_BANKING" && method.details.bank_name) {
    return `${method.details.bank_name} (${label})`;
  }
  return `${method.provider_name} (${label})`;
}

function RefundRequestDetails({
  refund,
}: {
  refund: VehicleBookingRefundRequest | null;
}) {
  if (!refund) return null;

  const status = refund.status ?? "pending";

  return (
    <div className="rounded-xl border border-border/60 bg-muted/30 p-4">
      <div className="mb-3 flex items-center justify-between gap-3">
        <h4 className="font-semibold">Refund Request</h4>
        <Badge
          variant="outline"
          className={cn(statusStyles[status] ?? statusStyles.default)}
        >
          {formatLabel(status)}
        </Badge>
      </div>
      <div className="grid gap-3 text-sm sm:grid-cols-2">
        <div>
          <p className="text-muted-foreground">Cancelled By</p>
          <p className="font-medium">{formatLabel(refund.cancelled_by)}</p>
        </div>
        {refund.reject_reason ? (
          <div>
            <p className="text-muted-foreground">Reject Reason</p>
            <p className="font-medium">{refund.reject_reason}</p>
          </div>
        ) : null}
        {refund.payment_reference_id ? (
          <div>
            <p className="text-muted-foreground">Payment Reference</p>
            <p className="font-medium">{refund.payment_reference_id}</p>
          </div>
        ) : null}
        {refund.payment_reference_document ? (
          <div>
            <p className="text-muted-foreground">Reference Document</p>
            <p className="break-all font-medium">
              {refund.payment_reference_document}
            </p>
          </div>
        ) : null}
      </div>
    </div>
  );
}

function BookingRouteTimeline({
  booking,
  compact = false,
}: {
  booking: UserVehicleBooking;
  compact?: boolean;
}) {
  const route = getRoute(booking);
  const points = getRoutePoints(booking);
  if (!route || points.length === 0) return null;

  return (
    <div
      className={cn(
        "mt-4 rounded-lg border border-teal-100 bg-teal-50/40 px-4 py-4",
        compact ? "overflow-hidden" : "overflow-x-auto"
      )}
    >
      <p className="mb-4 inline-flex rounded-full bg-gradient-to-r from-[#0c1934] to-[#022f47] px-2.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-white shadow-sm">
        {formatRouteType(route.route_type)}
      </p>
      <div
        className={cn("relative grid gap-0", compact ? "min-w-0" : "min-w-[480px]")}
        style={{
          gridTemplateColumns: compact
            ? `repeat(${points.length}, minmax(0, 1fr))`
            : `repeat(${points.length}, minmax(112px, 1fr))`,
        }}
      >
        <div className="absolute left-12 right-12 top-[8px] border-t-4 border-dotted border-teal-200" />
        {points.map((point) => (
          <div
            key={point.id}
            className="relative z-10 flex min-w-0 flex-col items-center px-1.5 text-center sm:px-2"
          >
            <span className="flex h-4 w-4 items-center justify-center rounded-full border border-[#0c1934] bg-white shadow-sm">
              <span
                className={cn(
                  "h-2 w-2 rounded-full",
                  point.endpoint ? "bg-[#f84200]" : "bg-teal-600"
                )}
              />
            </span>
            <p className="mt-2 w-full truncate text-[11px] font-bold text-[#0c1934] sm:text-xs">
              {point.name}, India
            </p>
            <p className="mt-0.5 w-full truncate text-[10px] font-semibold text-teal-700 sm:text-[11px]">
              {point.meta}
            </p>
          </div>
        ))}
      </div>
    </div>
  );
}

export function VehicleBookingsContent() {
  const toast = useToastEnhanced();
  const [bookings, setBookings] = useState<UserVehicleBooking[]>([]);
  const [activeStatus, setActiveStatus] = useState("all");
  const [searchQuery, setSearchQuery] = useState("");
  const [isLoading, setIsLoading] = useState(true);
  const [isCancelling, setIsCancelling] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedBooking, setSelectedBooking] =
    useState<UserVehicleBooking | null>(null);
  const [bookingToCancel, setBookingToCancel] =
    useState<UserVehicleBooking | null>(null);
  const [paymentMethods, setPaymentMethods] = useState<PaymentMethodItem[]>([]);
  const [selectedPaymentMethodId, setSelectedPaymentMethodId] = useState("");
  const [cancelReason, setCancelReason] = useState("");
  const [isAddingPaymentMethod, setIsAddingPaymentMethod] = useState(false);
  const [isSavingPaymentMethod, setIsSavingPaymentMethod] = useState(false);
  const [methodForm, setMethodForm] =
    useState<AddMethodForm>(INITIAL_METHOD_FORM);

  const loadBookings = useCallback(async () => {
    setIsLoading(true);
    setError(null);

    const result = await getUserVehicleBookingsAction({
      booking_status: activeStatus,
      search: searchQuery,
      per_page: 20,
    });

    setIsLoading(false);
    if (result.success && result.data) {
      setBookings(result.data.data);
    } else {
      setError(result.error ?? "Failed to load vehicle bookings.");
    }
  }, [activeStatus, searchQuery]);

  useEffect(() => {
    const timer = window.setTimeout(
      () => {
        void loadBookings();
      },
      searchQuery ? 300 : 0
    );

    return () => window.clearTimeout(timer);
  }, [loadBookings, searchQuery]);

  const openCancelDialog = async (booking: UserVehicleBooking) => {
    setBookingToCancel(booking);
    setCancelReason("");
    setSelectedPaymentMethodId("");
    setIsAddingPaymentMethod(false);
    setMethodForm(INITIAL_METHOD_FORM);

    const result = await getMyPaymentMethodsAction();
    if (result.success) {
      setPaymentMethods(result.data ?? []);
    } else {
      toast.error({
        title: "Payment methods unavailable",
        description:
          result.error ?? "Please add a payment method before cancelling.",
      });
    }
  };

  const updateMethodForm = <K extends keyof AddMethodForm>(
    key: K,
    value: AddMethodForm[K]
  ) => {
    setMethodForm((prev) => ({ ...prev, [key]: value }));
  };

  const submitPaymentMethod = async () => {
    const isBank = methodForm.type === "bank";
    const hasRequiredFields = isBank
      ? methodForm.accountHolder.trim() &&
      methodForm.bankName.trim() &&
      methodForm.accountNumber.trim() &&
      methodForm.ifscCode.trim()
      : methodForm.upiId.trim();

    if (!hasRequiredFields) {
      toast.error({
        title: "Payment details required",
        description: "Fill the refund payment details before saving.",
      });
      return;
    }

    setIsSavingPaymentMethod(true);
    const result = await createMyPaymentMethodAction(
      isBank
        ? {
          provider_name: methodForm.bankName.trim(),
          method_type: "NET_BANKING",
          details: {
            bank_name: methodForm.bankName.trim(),
            account_number: methodForm.accountNumber.trim(),
            ifsc_code: methodForm.ifscCode.trim(),
            account_holder_name: methodForm.accountHolder.trim(),
          },
          status: "inactive",
        }
        : {
          provider_name: methodForm.upiId.trim(),
          method_type: "UPI",
          details: {
            upi_id: methodForm.upiId.trim(),
          },
          status: "inactive",
        }
    );
    setIsSavingPaymentMethod(false);

    if (!result.success) {
      toast.error({
        title: "Payment method not saved",
        description: result.error ?? "Unable to save this refund method.",
      });
      return;
    }

    if (result.data) {
      setPaymentMethods((prev) => [result.data!, ...prev]);
      setSelectedPaymentMethodId(String(result.data.id));
    } else {
      const refreshed = await getMyPaymentMethodsAction();
      if (refreshed.success) {
        setPaymentMethods(refreshed.data ?? []);
      }
    }

    setIsAddingPaymentMethod(false);
    setMethodForm(INITIAL_METHOD_FORM);
    toast.success({
      title: "Payment method added",
      description: "It is selected for this refund request.",
    });
  };

  const submitCancel = async () => {
    if (!bookingToCancel) return;
    if (!selectedPaymentMethodId) {
      toast.error({
        title: "Payment method required",
        description: "Select the payment method for refund processing.",
      });
      return;
    }
    if (!cancelReason.trim()) {
      toast.error({
        title: "Cancel reason required",
        description: "Please enter a reason for cancellation.",
      });
      return;
    }

    setIsCancelling(true);
    const result = await cancelVehicleBookingAction({
      booking_id: bookingToCancel.id,
      user_payment_method_id: selectedPaymentMethodId,
      cancel_reason: cancelReason.trim(),
    });
    setIsCancelling(false);

    if (!result.success) {
      toast.error({
        title: "Cancellation failed",
        description: result.error ?? "Unable to cancel this booking.",
      });
      return;
    }

    toast.success({
      title: "Booking cancelled",
      description: result.message ?? "Refund request has been submitted.",
    });
    setBookingToCancel(null);
    void loadBookings();
  };

  return (
    <div className="space-y-6">
      <header>
        <h1 className="text-2xl md:text-3xl font-bold text-gray-900 flex items-center gap-3">
          <Car className="h-8 w-8 text-teal-700" />
          Vehicle Bookings
        </h1>
        <p className="mt-2 text-muted-foreground">
          View and manage your vehicle booking history.
        </p>
      </header>

      <div className="flex flex-col gap-4 justify-between md:flex-row">
        <Tabs
          value={activeStatus}
          onValueChange={setActiveStatus}
          className="w-full md:w-auto"
        >
          <TabsList className="grid w-full grid-cols-4 md:w-auto">
            {statusTabs.map((status) => (
              <TabsTrigger
                key={status.id}
                value={status.id}
                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"
              >
                {status.label}
              </TabsTrigger>
            ))}
          </TabsList>
        </Tabs>

        <div className="relative flex-1 md:max-w-md">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder="Search booking number, status, or amount..."
            value={searchQuery}
            onChange={(event) => setSearchQuery(event.target.value)}
            className="pl-9"
          />
        </div>
      </div>

      {error ? (
        <div className="rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">
          {error}
        </div>
      ) : null}

      {isLoading ? (
        <Card>
          <CardContent className="flex items-center justify-center gap-2 py-14 text-muted-foreground">
            <Loader2 className="h-5 w-5 animate-spin" />
            Loading vehicle bookings...
          </CardContent>
        </Card>
      ) : bookings.length === 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-16 text-center">
            <Car className="mb-4 h-14 w-14 text-muted-foreground/60" />
            <p className="text-lg font-semibold">No vehicle bookings found</p>
            <p className="mt-1 text-sm text-muted-foreground">
              Your completed vehicle bookings will appear here.
            </p>
            <Button asChild className={cn("mt-5", primaryButtonClassName)}>
              <Link href="/vehicle-booking">Book a Vehicle</Link>
            </Button>
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-4">
          {bookings.map((booking) => {
            const route = getRoute(booking);
            const vehicle = getVehicle(booking);
            const vehicleName = vehicle?.name ?? "Vehicle";
            const bookingStatus = booking.booking_status ?? "pending";
            const canCancel = !["cancel", "cancelled", "completed"].includes(
              bookingStatus.toLowerCase()
            );

            return (
              <Card
                key={booking.id}
                className="border-border/60 shadow-sm transition hover:shadow-md"
              >
                <CardHeader>
                  <div className="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
                    <div className="flex items-center gap-3">
                      <div className="relative h-14 w-14 overflow-hidden rounded-xl bg-muted">
                        {vehicle?.image ? (
                          <Image
                            src={
                              getStorageUrl(vehicle.image) || "/placeholder.png"
                            }
                            alt={vehicleName}
                            fill
                            className="object-cover"
                          />
                        ) : (
                          <Car className="m-4 h-6 w-6 text-muted-foreground" />
                        )}
                      </div>
                      <div>
                        <CardTitle className="text-lg">
                          {booking.booking_number ?? `VB-${booking.id}`}
                        </CardTitle>
                        <p className="mt-1 text-sm text-muted-foreground">
                          {vehicleName} - {route?.name ?? "Route"}
                        </p>
                      </div>
                    </div>
                    <Badge
                      variant="outline"
                      className={cn(
                        statusStyles[bookingStatus] ?? statusStyles.default
                      )}
                    >
                      {formatLabel(bookingStatus)}
                    </Badge>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
                    <div className="flex gap-2">
                      <MapPin className="mt-0.5 h-5 w-5 shrink-0 text-muted-foreground" />
                      <div>
                        <p className="text-sm font-medium">Route</p>
                        <p className="text-sm text-muted-foreground">
                          {getStartCity(booking)} to {getEndCity(booking)}
                        </p>
                      </div>
                    </div>
                    <div className="flex gap-2">
                      <Calendar className="mt-0.5 h-5 w-5 shrink-0 text-muted-foreground" />
                      <div>
                        <p className="text-sm font-medium">Start Date</p>
                        <p className="text-sm text-muted-foreground">
                          {formatDate(booking.start_date)}
                        </p>
                      </div>
                    </div>
                    <div className="flex gap-2">
                      <User className="mt-0.5 h-5 w-5 shrink-0 text-muted-foreground" />
                      <div>
                        <p className="text-sm font-medium">Passenger</p>
                        <p className="text-sm text-muted-foreground">
                          {booking.passenger?.passenger_name ?? "Not added"}
                        </p>
                      </div>
                    </div>
                    <div className="flex gap-2">
                      <IndianRupee className="mt-0.5 h-5 w-5 shrink-0 text-muted-foreground" />
                      <div>
                        <p className="text-sm font-medium">Total Amount</p>
                        <p className="text-sm font-bold text-foreground">
                          {formatCurrency(booking.total_price)}
                        </p>
                      </div>
                    </div>
                  </div>

                  <BookingRouteTimeline booking={booking} />

                  {bookingStatus === "cancel" ? (
                    <div className="mt-4 rounded-lg border border-red-100 bg-red-50 p-3 text-sm text-red-700">
                      Cancelled{" "}
                      {booking.cancelled_at
                        ? `on ${formatDate(booking.cancelled_at)}`
                        : ""}
                      {getCancelledBy(booking)?.name
                        ? ` by ${getCancelledBy(booking)?.name}`
                        : ""}
                      {booking.cancel_reason
                        ? `. Reason: ${booking.cancel_reason}`
                        : ""}
                    </div>
                  ) : null}

                  <div className="mt-4 flex flex-wrap items-center justify-between gap-3 border-t border-border/60 pt-4">
                    <div className="text-sm text-muted-foreground">
                      Route price {formatCurrency(booking.route_price)} |
                      Discount {formatCurrency(booking.discount_price)} | Tax{" "}
                      {formatCurrency(booking.tax)}
                    </div>
                    <div className="flex gap-2">
                      <Button
                        variant="outline"
                        size="sm"
                        className={cn("gap-2", outlineButtonClassName)}
                        onClick={() => setSelectedBooking(booking)}
                      >
                        <Eye className="h-4 w-4" />
                        Details
                      </Button>
                      {canCancel ? (
                        <Button
                          variant="outline"
                          size="sm"
                          className="gap-2 text-destructive hover:text-destructive"
                          onClick={() => void openCancelDialog(booking)}
                        >
                          <X className="h-4 w-4" />
                          Cancel
                        </Button>
                      ) : null}
                    </div>
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}

      <Dialog
        open={Boolean(selectedBooking)}
        onOpenChange={(open) => !open && setSelectedBooking(null)}
      >
        <DialogContent className="max-h-[92vh] w-[calc(100vw-2rem)] max-w-5xl overflow-y-auto overflow-x-hidden">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <ReceiptText className="h-5 w-5 text-teal-700" />
              {selectedBooking?.booking_number ?? "Vehicle Booking"}
            </DialogTitle>
            <DialogDescription>
              Complete vehicle booking and passenger details.
            </DialogDescription>
          </DialogHeader>

          {selectedBooking ? (
            <div className="space-y-5">
              <div className="grid gap-4 sm:grid-cols-2">
                <Detail
                  label="Vehicle"
                  value={getVehicle(selectedBooking)?.name}
                />
                <Detail label="Route" value={getRoute(selectedBooking)?.name} />
                <Detail label="From" value={getStartCity(selectedBooking)} />
                <Detail label="To" value={getEndCity(selectedBooking)} />
                <Detail
                  label="Start Date"
                  value={formatDate(selectedBooking.start_date)}
                />
                <Detail
                  label="Total Amount"
                  value={formatCurrency(selectedBooking.total_price)}
                />
              </div>

              <BookingRouteTimeline booking={selectedBooking} compact />

              <div className="rounded-xl border border-border/60 p-4">
                <h4 className="mb-3 font-semibold">Passenger Details</h4>
                <div className="grid gap-3 text-sm sm:grid-cols-2">
                  <Detail
                    label="Name"
                    value={selectedBooking.passenger?.passenger_name}
                  />
                  <Detail
                    label="Phone"
                    value={selectedBooking.passenger?.phone_number}
                    icon={Phone}
                  />
                  <Detail
                    label="Email"
                    value={selectedBooking.passenger?.email}
                  />
                  <Detail
                    label="Gender"
                    value={selectedBooking.passenger?.gender}
                  />
                  <Detail
                    label="Adults"
                    value={selectedBooking.passenger?.total_adult}
                  />
                  <Detail
                    label="Children"
                    value={selectedBooking.passenger?.total_child}
                  />
                </div>
              </div>

              <RefundRequestDetails
                refund={getRefundRequest(selectedBooking)}
              />
            </div>
          ) : null}
          <DialogFooter>
            <Button
              variant="outline"
              className={outlineButtonClassName}
              onClick={() => setSelectedBooking(null)}
            >
              Close
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog
        open={Boolean(bookingToCancel)}
        onOpenChange={(open) => !open && setBookingToCancel(null)}
      >
        <DialogContent className="max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Cancel Vehicle Booking</DialogTitle>
            <DialogDescription>
              Select a refund payment method and enter the cancellation reason.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="rounded-lg bg-muted/50 p-3 text-sm">
              <p className="font-medium">
                {bookingToCancel?.booking_number ?? "Vehicle booking"}
              </p>
              <p className="text-muted-foreground">
                {bookingToCancel
                  ? `${getStartCity(bookingToCancel)} to ${getEndCity(bookingToCancel)}`
                  : ""}
              </p>
            </div>

            <div className="space-y-2">
              <div className="flex items-center justify-between gap-3">
                <Label>Refund Payment Method</Label>
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  className="h-8 gap-2 text-teal-700 hover:bg-teal-50 hover:text-teal-800"
                  onClick={() => setIsAddingPaymentMethod((value) => !value)}
                >
                  <Plus className="h-4 w-4" />
                  Add Method
                </Button>
              </div>
              {paymentMethods.length > 0 ? (
                <Select
                  value={selectedPaymentMethodId}
                  onValueChange={setSelectedPaymentMethodId}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select payment method" />
                  </SelectTrigger>
                  <SelectContent>
                    {paymentMethods.map((method) => (
                      <SelectItem key={method.id} value={String(method.id)}>
                        {getMethodTitle(method)}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              ) : null}
              {paymentMethods.length === 0 ? (
                <p className="text-xs text-muted-foreground">
                  No saved payment methods found. Add one here to request a
                  refund.
                </p>
              ) : null}
            </div>

            {isAddingPaymentMethod ? (
              <div className="rounded-xl border border-border/70 bg-muted/30 p-4">
                <div className="mb-4 flex gap-2">
                  <Button
                    type="button"
                    variant={methodForm.type === "bank" ? "default" : "outline"}
                    size="sm"
                    className={cn(
                      "gap-2",
                      methodForm.type === "bank"
                        ? primaryButtonClassName
                        : outlineButtonClassName
                    )}
                    onClick={() => updateMethodForm("type", "bank")}
                  >
                    <CreditCard className="h-4 w-4" />
                    Bank
                  </Button>
                  <Button
                    type="button"
                    variant={methodForm.type === "upi" ? "default" : "outline"}
                    size="sm"
                    className={cn(
                      "gap-2",
                      methodForm.type === "upi"
                        ? primaryButtonClassName
                        : outlineButtonClassName
                    )}
                    onClick={() => updateMethodForm("type", "upi")}
                  >
                    <IndianRupee className="h-4 w-4" />
                    UPI
                  </Button>
                </div>

                {methodForm.type === "bank" ? (
                  <div className="grid gap-3 sm:grid-cols-2">
                    <div className="space-y-2 sm:col-span-2">
                      <Label htmlFor="vehicle-refund-account-holder">
                        Account Holder Name
                      </Label>
                      <Input
                        id="vehicle-refund-account-holder"
                        value={methodForm.accountHolder}
                        onChange={(event) =>
                          updateMethodForm("accountHolder", event.target.value)
                        }
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="vehicle-refund-bank-name">
                        Bank Name
                      </Label>
                      <Input
                        id="vehicle-refund-bank-name"
                        value={methodForm.bankName}
                        onChange={(event) =>
                          updateMethodForm("bankName", event.target.value)
                        }
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="vehicle-refund-ifsc">IFSC Code</Label>
                      <Input
                        id="vehicle-refund-ifsc"
                        value={methodForm.ifscCode}
                        onChange={(event) =>
                          updateMethodForm("ifscCode", event.target.value)
                        }
                      />
                    </div>
                    <div className="space-y-2 sm:col-span-2">
                      <Label htmlFor="vehicle-refund-account-number">
                        Account Number
                      </Label>
                      <Input
                        id="vehicle-refund-account-number"
                        value={methodForm.accountNumber}
                        onChange={(event) =>
                          updateMethodForm("accountNumber", event.target.value)
                        }
                      />
                    </div>
                  </div>
                ) : (
                  <div className="space-y-2">
                    <Label htmlFor="vehicle-refund-upi">UPI ID</Label>
                    <Input
                      id="vehicle-refund-upi"
                      placeholder="name@upi"
                      value={methodForm.upiId}
                      onChange={(event) =>
                        updateMethodForm("upiId", event.target.value)
                      }
                    />
                  </div>
                )}

                <div className="mt-4 flex justify-end gap-2">
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    className={outlineButtonClassName}
                    onClick={() => {
                      setIsAddingPaymentMethod(false);
                      setMethodForm(INITIAL_METHOD_FORM);
                    }}
                    disabled={isSavingPaymentMethod}
                  >
                    Cancel
                  </Button>
                  <Button
                    type="button"
                    size="sm"
                    className={primaryButtonClassName}
                    onClick={submitPaymentMethod}
                    disabled={isSavingPaymentMethod}
                  >
                    {isSavingPaymentMethod ? (
                      <>
                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                        Saving
                      </>
                    ) : (
                      "Save Method"
                    )}
                  </Button>
                </div>
              </div>
            ) : null}

            <div className="space-y-2">
              <Label htmlFor="vehicle-cancel-reason">Cancel Reason</Label>
              <Textarea
                id="vehicle-cancel-reason"
                value={cancelReason}
                onChange={(event) => setCancelReason(event.target.value)}
                placeholder="Tell us why you are cancelling this booking"
                rows={4}
              />
            </div>
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              className={outlineButtonClassName}
              onClick={() => setBookingToCancel(null)}
              disabled={isCancelling}
            >
              Keep Booking
            </Button>
            <Button
              variant="destructive"
              onClick={submitCancel}
              disabled={isCancelling}
            >
              {isCancelling ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Cancelling
                </>
              ) : (
                "Submit Cancellation"
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

function Detail({
  label,
  value,
  icon: Icon,
}: {
  label: string;
  value: string | number | null | undefined;
  icon?: ElementType;
}) {
  return (
    <div>
      <p className="flex items-center gap-1 text-sm text-muted-foreground">
        {Icon ? <Icon className="h-3.5 w-3.5" /> : null}
        {label}
      </p>
      <p className="font-medium">{value ?? "NA"}</p>
    </div>
  );
}
