import { useNavigate, useParams } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import {
  Box,
  Button,
  Group,
  Stack,
  Text,
  ThemeIcon,
  Title,
} from "@mantine/core";
import { ArrowLeft, Upload } from "lucide-react";

import { api } from "@/services/api";
import { ContractStatusBadge, INK } from "./contract-ui";
import { ContractClearancePanel } from "./ContractClearancePanel";

/**
 * Customer clearance upload page for a CONTRACT (doc §8.3). The document grid +
 * upload logic live in {@link ContractClearancePanel} so the same workspace can
 * render here (full page) or inside the contract action modal.
 */
export default function ContractClearanceFlow() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();

  const { data: contract } = useQuery(
    api.contracts.get.queryOptions({ input: { id: id! }, enabled: !!id }),
  );

  const { data: clearance } = useQuery(
    api.contracts.getClearance.queryOptions({
      input: { id: id! },
      enabled: !!id,
    }),
  );

  return (
    <Box style={{ padding: "28px 32px 40px" }}>
      <Stack gap="lg">
        <Group justify="space-between" align="flex-start" wrap="wrap" gap="md">
          <Group gap="md" align="center" wrap="nowrap">
            <Button
              variant="subtle"
              color="gray"
              radius="md"
              px={8}
              onClick={() => navigate(`/contracts/${id}`)}
            >
              <ArrowLeft size={18} />
            </Button>
            <Group gap={12} wrap="nowrap" align="center">
              <ThemeIcon size={48} radius="lg" variant="light" color="edr-green">
                <Upload size={23} />
              </ThemeIcon>
              <div>
                <Group gap={10} align="center">
                  <Title order={2} fw={800} fz={22} style={{ color: INK }}>
                    Clearance documents
                  </Title>
                  {contract && <ContractStatusBadge status={contract.status} />}
                </Group>
                <Text size="sm" c="dimmed" mt={2}>
                  {contract?.reference ?? ""} · Cycle{" "}
                  {clearance?.cycleNumber ?? 1}
                </Text>
              </div>
            </Group>
          </Group>
        </Group>

        {id && (
          <ContractClearancePanel
            contractId={id}
            tradeDirection={contract?.tradeDirection ?? "IMPORT"}
          />
        )}
      </Stack>
    </Box>
  );
}
