import { useNavigate } from "react-router-dom";
import { Paper, Stack, Table, Text } from "@mantine/core";

import { BookingPriorityBadge } from "@/components/bookings/BookingPriorityBadge";
import { BookingStatusBadge } from "@/components/bookings/BookingStatusBadge";
import type { IOverviewRecentBooking } from "@/types/overview";

function formatAmount(amount: number | null, currency: string | null) {
  if (amount == null) return "—";
  const code = currency === "USD" ? "USD" : "ETB";
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: code,
    maximumFractionDigits: 0,
  }).format(amount);
}

export function OverviewRecentBookingsTable({
  bookings,
}: {
  bookings: IOverviewRecentBooking[];
}) {
  const navigate = useNavigate();

  return (
    <Paper p="lg" radius="lg" withBorder>
      <Stack gap="md">
        <Text fw={600}>Recent bookings</Text>
        {bookings.length === 0 ? (
          <Text size="sm" c="dimmed" ta="center" py="lg">
            No recent bookings
          </Text>
        ) : (
          <Table highlightOnHover verticalSpacing="sm">
            <Table.Thead>
              <Table.Tr>
                <Table.Th>Reference</Table.Th>
                <Table.Th>Customer</Table.Th>
                <Table.Th>Status</Table.Th>
                <Table.Th>Priority</Table.Th>
                <Table.Th>Amount</Table.Th>
                <Table.Th>Created</Table.Th>
              </Table.Tr>
            </Table.Thead>
            <Table.Tbody>
              {bookings.map((booking) => (
                <Table.Tr
                  key={booking.id}
                  style={{ cursor: "pointer" }}
                  onClick={() => navigate(`/dashboard/booking-requests/${booking.id}`)}
                >
                  <Table.Td>
                    <Text fw={600} size="sm">
                      {booking.reference}
                    </Text>
                  </Table.Td>
                  <Table.Td>{booking.customerLabel}</Table.Td>
                  <Table.Td>
                    <BookingStatusBadge status={booking.status} />
                  </Table.Td>
                  <Table.Td>
                    <BookingPriorityBadge score={booking.priorityScore} />
                  </Table.Td>
                  <Table.Td>
                    {formatAmount(booking.totalAmount, booking.paymentCurrency)}
                  </Table.Td>
                  <Table.Td>
                    {new Date(booking.createdAt).toLocaleDateString()}
                  </Table.Td>
                </Table.Tr>
              ))}
            </Table.Tbody>
          </Table>
        )}
      </Stack>
    </Paper>
  );
}
