import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { Button, Modal, Text, type ButtonProps } from "@mantine/core";
import { AlertCircle, Upload, type LucideIcon } from "lucide-react";

import { api } from "@/services/api";
import { ContractClearancePanel } from "@/pages/contracts/ContractClearancePanel";
import { ModalSafeWrapper } from "./ModalSafeWrapper";
import { useDisclosure } from "@mantine/hooks";

interface ContractClearanceActionProps {
  contractId: string;
  label?: string;
  size?: ButtonProps["size"];
  urgent?: boolean;
  /** GL's turn — render as a calm status button, not a call to action. */
  waiting?: boolean;
  /** Icon override from the phase-aware action derivation. */
  icon?: LucideIcon;
}

export function ContractClearanceAction({
  contractId,
  label: labelProp,
  size = "xs",
  urgent = false,
  waiting = false,
  icon: iconProp,
}: ContractClearanceActionProps) {
  const [opened, { open, close }] = useDisclosure(false);

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

  const label = useMemo(() => {
    if (labelProp) return labelProp;
    const docs = clearance?.documents ?? [];
    const queried = docs.filter(
      (d) => d.uploadedBy === "customer" && d.reviewStatus === "QUERIED",
    ).length;
    if (queried > 0) return "Update clearance";
    return urgent ? "Upload clearance" : "Manage clearance";
  }, [labelProp, clearance, urgent]);

  const Icon =
    iconProp ?? (urgent || label.includes("Update") ? AlertCircle : Upload);

  // Urgent (customer's turn) = filled orange so it stands out among the green
  // actions; waiting (GL's turn) = calm subtle gray; default = brand green.
  const color = urgent ? "orange" : waiting ? "gray" : "edr-green";
  const variant = waiting ? "light" : "filled";

  return (
    <ModalSafeWrapper>
      <Button
        size={size}
        radius="md"
        fw={700}
        fz={13}
        color={color}
        variant={variant}
        leftSection={<Icon size={14} />}
        onClick={(e) => {
          e.stopPropagation();
          open();
        }}
      >
        {label}
      </Button>

      <Modal
        opened={opened}
        onClose={close}
        title={
          <Text fw={700} fz={16}>
            Clearance documents
          </Text>
        }
        size="xl"
        radius="md"
        centered
        overlayProps={{ blur: 2, backgroundOpacity: 0.55 }}
      >
        <ContractClearancePanel contractId={contractId} bare onSubmitted={close} />
      </Modal>
    </ModalSafeWrapper>
  );
}
