import React, { useCallback } from 'react';
import { Box, Button, Card, Flex, Heading, Typo } from '@/atoms';
import type { Attachment } from '@/molecules';
import { DownloadIcon } from '@/icon';

type File = Attachment & { buttonName: string };
export interface ReportCardProps {
  title?: string;
  file?: File;
  status?: React.ReactNode;
  subtitle?: string;
}

export function ReportCard(props: ReportCardProps): React.ReactNode {
  const { title, file, status, subtitle } = props;

  const onClickDownload = useCallback(() => {
    if (!file) return;
    const { url, fileName } = file;
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName;
    link.target = '_blank';

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }, [file]);

  if (status) {
    return (
      <Card>
        <Flex align="center" justify="between">
          <Heading variant="heading4">{title}</Heading>
          {status}
        </Flex>
      </Card>
    );
  }

  return (
    <Card>
      <Flex
        direction={{ initial: 'column', xs: 'row' }}
        gapY="2"
        justify="between"
      >
        <Box>
          <Heading variant="heading4">{title}</Heading>
          {subtitle ? <Typo color="gray">{subtitle}</Typo> : null}
        </Box>
        <Button key={file?.url} onClick={onClickDownload} variant="surface">
          <Flex gap="2" width="100%">
            <DownloadIcon />
            {file?.buttonName}
          </Flex>
        </Button>
      </Flex>
    </Card>
  );
}
