import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Box, Button, FileButton, Group, Text } from "@mantine/core";
import { Receipt, Upload } from "lucide-react";

import { contractsService } from "@/services/contracts.service";
import { SectionCard, CardTitle } from "./layout";

/**
 * Customs (Path B) duty/tax panel: when GL has advised duty/tax but the slip is
 * not yet paid, surfaces the payment-slip upload — the customer's only action
 * in this phase. The milestone progression itself is rendered by the unified
 * journey wizard at the top of the page.
 */
export function ShipmentTrackingCard({ bookingId }: { bookingId: string }) {
  const qc = useQueryClient();
  const { data: milestones = [] } = useQuery({
    queryKey: ["booking-milestones", bookingId],
    queryFn: () => contractsService.getBookingMilestones(bookingId),
    enabled: !!bookingId,
  });

  const [slip, setSlip] = useState<File | null>(null);
  const uploadSlip = useMutation({
    mutationFn: (file: File) => contractsService.uploadDutySlip(bookingId, file),
    onSuccess: () => {
      setSlip(null);
      void qc.invalidateQueries({ queryKey: ["booking-milestones", bookingId] });
    },
  });

  const dutyAdvised = milestones.find(
    (m) => m.milestoneCode === "DUTY_TAXES_ADVISED",
  );
  const dutyPaid = milestones.find((m) => m.milestoneCode === "DUTY_TAX_PAID");
  const needsDutySlip =
    dutyAdvised?.status === "COMPLETED" && dutyPaid?.status !== "COMPLETED";

  // The milestone progression itself lives in the unified journey wizard at
  // the top of the page — this card only surfaces the customer's one action
  // in the customs phase: uploading the duty/tax payment slip.
  if (!needsDutySlip) return null;

  return (
    <SectionCard>
      <CardTitle>Duty &amp; tax payment</CardTitle>

      {needsDutySlip ? (
        <Box
          mt="sm"
          p="md"
          style={{
            borderRadius: 12,
            border: "1px solid var(--mantine-color-yellow-3)",
            background: "var(--mantine-color-yellow-0)",
          }}
        >
          <Group gap={8} mb={6}>
            <Receipt size={16} />
            <Text fw={600} fz="sm">
              Duty &amp; tax due
            </Text>
          </Group>
          <Text fz="xs" c="dimmed" mb="sm">
            Global Logistics advised
            {dutyAdvised?.metadata?.dutyAmount != null
              ? ` ${dutyAdvised.metadata.dutyAmount.toLocaleString()} ${dutyAdvised.metadata.dutyCurrency ?? ""}`
              : ""}
            {dutyAdvised?.metadata?.declarationSerial
              ? ` · serial ${dutyAdvised.metadata.declarationSerial}`
              : ""}
            . Upload your payment slip to proceed.
          </Text>
          <Group justify="space-between" wrap="nowrap">
            <FileButton onChange={setSlip} accept="application/pdf,image/*">
              {(props) => (
                <Button
                  {...props}
                  variant="light"
                  color="gray"
                  size="compact-sm"
                  leftSection={<Upload size={14} />}
                >
                  {slip ? slip.name : "Choose slip"}
                </Button>
              )}
            </FileButton>
            <Button
              size="compact-sm"
              color="edr-green"
              loading={uploadSlip.isPending}
              disabled={!slip}
              onClick={() => slip && uploadSlip.mutate(slip)}
            >
              Upload slip
            </Button>
          </Group>
        </Box>
      ) : null}
    </SectionCard>
  );
}
