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

import { ContractStatusBadge } from "@/components/contracts/ContractStatusBadge";
import type { IOverviewRecentContract } from "@/types/overview";

function kindLabel(kind: string) {
  return kind === "GENERAL" ? "General" : "One-time";
}

export function OverviewRecentContractsTable({
  contracts,
}: {
  contracts: IOverviewRecentContract[];
}) {
  const navigate = useNavigate();

  return (
    <Paper p="lg" radius="lg" withBorder>
      <Stack gap="md">
        <Text fw={600}>Recent contracts</Text>
        {contracts.length === 0 ? (
          <Text size="sm" c="dimmed" ta="center" py="lg">
            No recent contracts
          </Text>
        ) : (
          <Table highlightOnHover verticalSpacing="sm">
            <Table.Thead>
              <Table.Tr>
                <Table.Th>Reference</Table.Th>
                <Table.Th>Customer</Table.Th>
                <Table.Th>Kind</Table.Th>
                <Table.Th>Cargo</Table.Th>
                <Table.Th>Status</Table.Th>
                <Table.Th>Valid until</Table.Th>
                <Table.Th>Created</Table.Th>
              </Table.Tr>
            </Table.Thead>
            <Table.Tbody>
              {contracts.map((contract) => (
                <Table.Tr
                  key={contract.id}
                  style={{ cursor: "pointer" }}
                  onClick={() =>
                    navigate(`/dashboard/contract-requests/${contract.id}`)
                  }
                >
                  <Table.Td>
                    <Text fw={600} size="sm">
                      {contract.reference}
                    </Text>
                  </Table.Td>
                  <Table.Td>{contract.customerLabel}</Table.Td>
                  <Table.Td>
                    <Badge variant="light" color="gray" radius="sm">
                      {kindLabel(contract.contractKind)}
                    </Badge>
                  </Table.Td>
                  <Table.Td>
                    {contract.freightType === "CONTAINER" ? "Container" : "Bulk"}
                  </Table.Td>
                  <Table.Td>
                    <ContractStatusBadge status={contract.status} />
                  </Table.Td>
                  <Table.Td>
                    {contract.validUntil
                      ? new Date(contract.validUntil).toLocaleDateString()
                      : "—"}
                  </Table.Td>
                  <Table.Td>
                    {new Date(contract.createdAt).toLocaleDateString()}
                  </Table.Td>
                </Table.Tr>
              ))}
            </Table.Tbody>
          </Table>
        )}
      </Stack>
    </Paper>
  );
}
