import { useState } from "react";
import { Alert, Anchor, Button, FileInput, Group, Paper, Stack, Text } from "@mantine/core";
import { AlertTriangle, Download, Receipt, Upload } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import toast from "react-hot-toast";
import type { Freight } from "@edr/types";

import { bookingsService } from "@/services/bookings.service";
import { downloadStoredFile } from "@/services/files.service";
import { ClearancePhaseStepper } from "../contracts/ClearancePhaseStepper";
import { ClearanceUploadedDocumentsPanel } from "@/components/contracts/ClearanceUploadedDocumentsPanel";
import { useFileViewer } from "@/hooks/useFileViewer";

const BORDER = "#E6ECF2";

export function BookingClearanceWorkflowBanner({
  booking,
}: {
  booking: Freight.IBooking;
}) {
  // Drawdown bookings under a GENERAL contract keep bookingType = ONE_TIME —
  // the denormalized contractKind is what marks them as phased (Path B).
  const isPhased =
    booking.customsClearingEnabled &&
    (booking.bookingType === "GENERAL_CONTRACT" ||
      booking.contractKind === "GENERAL");

  const { view, viewer } = useFileViewer();

  const { data: clearance, refetch } = useQuery({
    queryKey: ["booking-clearance", booking.id],
    queryFn: () => bookingsService.getClearance(booking.id),
    enabled: isPhased,
  });

  if (!isPhased || !clearance) return null;

  const dutyPaid = clearance.milestones?.some(
    (m) => m.milestoneCode === "DUTY_TAX_PAID" && m.status === "COMPLETED",
  );
  const dutyPending =
    clearance.dutyRequired &&
    clearance.dutyAdvice &&
    !dutyPaid;

  return (
    <Paper withBorder radius="lg" p="lg" style={{ borderColor: BORDER }}>
      <Stack gap="md">
        <Text fw={700} size="sm">
          Clearance progress
        </Text>
        <ClearancePhaseStepper
          clearance={clearance as Freight.ContractClearanceView}
          tradeDirection={booking.tradeDirection}
          compact
        />

        {clearance.roHold && clearance.roHoldReason ? (
          <Alert color="orange" icon={<AlertTriangle size={16} />} title="Release Order on hold">
            {clearance.roHoldReason}
          </Alert>
        ) : null}

        {clearance.nextAction?.actor === "CUSTOMER" ? (
          <Alert color="blue" variant="light">
            {clearance.nextAction.action}
          </Alert>
        ) : null}

        {dutyPending && clearance.dutyAdvice ? (
          <DutyAdvicePanel
            dutyAdvice={clearance.dutyAdvice}
            bookingId={booking.id}
            onUploaded={() => void refetch()}
          />
        ) : null}

        {clearance.operationReady ? (
          <Alert color="green" variant="light">
            Clearance is complete. You may proceed to request your operation date.
          </Alert>
        ) : null}

        <ClearanceUploadedDocumentsPanel
          embedded
          files={clearance.workflowFiles ?? []}
          title="Customs documents"
          onView={(f) => view(f)}
          onDownload={({ id, name }) => void downloadStoredFile(id, name)}
        />
      </Stack>
      {viewer}
    </Paper>
  );
}

function DutyAdvicePanel({
  dutyAdvice,
  bookingId,
  onUploaded,
}: {
  dutyAdvice: NonNullable<Freight.ClearanceView["dutyAdvice"]>;
  bookingId: string;
  onUploaded: () => void;
}) {
  const [file, setFile] = useState<File | null>(null);
  const [loading, setLoading] = useState(false);
  const noticeFile = dutyAdvice.noticeFile;

  return (
    <Paper withBorder radius="md" p="md" bg="#FFFBF0">
      <Stack gap="sm">
        <GroupLabel icon={Receipt} text="Duty / tax payment" />
        <Text size="sm">
          Amount due:{" "}
          <strong>
            {dutyAdvice.amount.toLocaleString()} {dutyAdvice.currency}
          </strong>
          {dutyAdvice.declarationSerial
            ? ` · Payment code: ${dutyAdvice.declarationSerial}`
            : null}
        </Text>
        {noticeFile ? (
          <Anchor
            component="button"
            type="button"
            onClick={() => void downloadStoredFile(noticeFile.id, noticeFile.name)}
            size="sm"
          >
            <Group gap={6} wrap="nowrap">
              <Download size={14} />
              Download duty notice ({noticeFile.name})
            </Group>
          </Anchor>
        ) : null}
        <Text size="sm" c="dimmed">
          Pay the amount above, then upload your payment slip so clearance can continue.
        </Text>
        <FileInput label="Payment slip" value={file} onChange={setFile} size="sm" />
        <Button
          color="orange"
          loading={loading}
          disabled={!file}
          leftSection={<Upload size={16} />}
          onClick={async () => {
            if (!file) return;
            setLoading(true);
            try {
              await bookingsService.uploadBookingClearanceDutySlip(bookingId, file);
              toast.success("Payment slip uploaded");
              onUploaded();
            } catch (e) {
              toast.error(e instanceof Error ? e.message : "Upload failed");
            } finally {
              setLoading(false);
            }
          }}
        >
          Submit payment slip
        </Button>
      </Stack>
    </Paper>
  );
}

function GroupLabel({ icon: Icon, text }: { icon: typeof Receipt; text: string }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
      <Icon size={16} />
      <Text fw={600} size="sm">
        {text}
      </Text>
    </div>
  );
}
