import { Center, Loader, Modal, Paper, Text } from "@mantine/core";

import { useContractTemplatePreview } from "@/hooks/contract-templates/useContractTemplates";

interface TemplatePreviewModalProps {
  code: string | null;
  title?: string;
  onClose: () => void;
}

/** Full-document HTML preview rendered by the API against mock contract data. */
export default function TemplatePreviewModal({
  code,
  title,
  onClose,
}: TemplatePreviewModalProps) {
  const { data, isLoading, isError } = useContractTemplatePreview(
    code ?? undefined,
    Boolean(code),
  );

  return (
    <Modal
      opened={Boolean(code)}
      onClose={onClose}
      title={title ?? "Contract preview"}
      size="90%"
      padding="sm"
    >
      {isLoading ? (
        <Center h={420}>
          <Loader color="edr-green" />
        </Center>
      ) : isError ? (
        <Center h={200}>
          <Text c="red">Failed to render the preview.</Text>
        </Center>
      ) : (
        <Paper withBorder radius="md" style={{ overflow: "hidden" }}>
          <iframe
            title="Contract template preview"
            srcDoc={data?.html}
            style={{ width: "100%", height: "72vh", border: 0, background: "#f3f8f5" }}
          />
        </Paper>
      )}
    </Modal>
  );
}
