import { useQuery } from "@tanstack/react-query";
import { Alert, Group, Loader, Modal, Text } from "@mantine/core";
import { Info } from "lucide-react";

import { contractsService } from "@/services/contracts.service";

interface ContractPreviewModalProps {
  opened: boolean;
  onClose: () => void;
  contractId: string;
}

/**
 * Live preview of the contract document. Renders server-side HTML, not the
 * stored PDF — the PDF is only produced once the final approver approves, so
 * before that this is the document. Served in an iframe so the contract's own
 * styles stay sandboxed away from the app.
 */
export function ContractPreviewModal({
  opened,
  onClose,
  contractId,
}: ContractPreviewModalProps) {
  const { data, isLoading, isError } = useQuery({
    queryKey: ["contracts", contractId, "contract-view"],
    queryFn: () => contractsService.getContractView(contractId),
    enabled: opened,
    // The document changes as approvers edit it, so never serve a stale render.
    staleTime: 0,
  });

  return (
    <Modal
      opened={opened}
      onClose={onClose}
      size="xl"
      title="Contract document preview"
    >
      <Alert
        icon={<Info size={16} />}
        color="blue"
        variant="light"
        mb="sm"
        p="xs"
      >
        <Text size="xs">
          Draft preview. The PDF is generated automatically once the final
          approver approves.
        </Text>
      </Alert>

      {isLoading ? (
        <Group gap="xs" py="xl" justify="center">
          <Loader size="sm" />
          <Text size="sm" c="dimmed">
            Rendering document…
          </Text>
        </Group>
      ) : isError || !data?.html ? (
        <Text size="sm" c="red">
          The document could not be rendered. Check that the contract has a
          template and try again.
        </Text>
      ) : (
        <iframe
          srcDoc={data.html}
          title="Contract document preview"
          style={{
            width: "100%",
            minHeight: "70vh",
            border: "none",
            background: "white",
          }}
        />
      )}
    </Modal>
  );
}
