import { Box, Center, Loader, Stack, Text } from "@mantine/core";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { AlertTriangle } from "lucide-react";
import { useParams } from "react-router-dom";

import { api } from "@/services/api";

import { DraftBookingView } from "./DraftBookingView";
import { PageShell, SectionCard } from "./components/layout";
import { ReadonlyBookingView } from "./ReadonlyBookingView";
import { isDraftLike } from "./utils";

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 (
      <Center mih={400} p="xl">
        <Stack align="center" gap="md">
          <Loader color="edr-green" />
          <Text size="sm" c="dimmed">
            Loading booking details…
          </Text>
        </Stack>
      </Center>
    );
  }

  if (isError || !booking) {
    return (
      <PageShell>
        <SectionCard>
          <Stack align="center" gap={8} py={48} ta="center">
            <Box
              style={{
                width: 64,
                height: 64,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                borderRadius: 16,
                backgroundColor: "#FBEAE7",
                color: "#C0392B",
              }}
            >
              <AlertTriangle size={30} />
            </Box>
            <Text mt={4} fz="20px" fw={800} c="#10202F">
              {isError ? "Failed to load booking" : "Booking not found"}
            </Text>
            {isError && (
              <Text size="sm" c="dimmed">
                {error instanceof Error
                  ? error.message
                  : "An unexpected error occurred."}
              </Text>
            )}
          </Stack>
        </SectionCard>
      </PageShell>
    );
  }

  if (isDraftLike(booking.status)) {
    return (
      <DraftBookingView booking={booking} onBookingUpdated={refetchBooking} />
    );
  }
  return <ReadonlyBookingView booking={booking} />;
}
