import { ViewIcon } from '@bjsdistribution/dms-component-library';
import Tippy from '@tippyjs/react';
import React, { useState } from 'react';
import styled from 'styled-components';
import { atom } from 'jotai';
import { useOrderProductsResources } from '../../../store';
import { notification } from 'antd';
import DownloadIcon from '../../../../../assets/icons/DownloadIcon';

export const selectedOrderIdAtom = atom<number[]>([]);

interface ActionProps {
  row: {
    original: {
      id: number;
    };
  };
}

function Action({ row }: ActionProps) {
  const [orderResources] = useOrderProductsResources();
  const [isDownloading, setIsDownloading] = useState(false);
  const urlID = row?.original?.id;

  const matchingResource = orderResources?.data?.find(
    (resource: any) => resource.id === urlID
  );

  const resourceUrl = matchingResource?.url;

  const handleView = () => {
    if (resourceUrl) {
      window.open(resourceUrl, '_blank');
    }
  };

  const handleDownload = async () => {
    if (!resourceUrl) {
      notification.error({
        message: 'Error',
        description: 'Resource URL is not available',
      });
      return;
    }

    setIsDownloading(true); // disable button
    notification.info({
      message: 'Info',
      description: `Download is in progress. Please wait`,
    });
    //to change
    fetch(resourceUrl, {
      method: 'GET',
      headers: {},
    })
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.blob();
      })
      .then(blob => {
        // Create a temporary URL for the blob
        const urlObject = window.URL.createObjectURL(blob);

        // Create a temporary anchor element
        const link = document.createElement('a');
        link.href = urlObject;

        // Generate a filename (you can customize this)
        const filename = `Downloads`;
        link.download = filename;

        // Append to body, click, and remove
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        // Revoke the blob URL
        window.URL.revokeObjectURL(urlObject);

        notification.success({
          message: 'Success',
          description: 'Document downloaded successfully.',
        });

        setIsDownloading(false); // enable button
      })
      .catch(error => {
        console.error('Error downloading the document:', error);
        notification.error({
          message: 'Error',
          description: 'Failed to download the document.',
        });
      })
      .finally(() => {
        setIsDownloading(false);
      });
  };

  return (
    <Actions>
      <Row>
        <Tippy content="View" placement="top" trigger="mouseenter">
          <TippyContainer onClick={handleView}>
            <ViewIcon style={{ cursor: 'pointer' }} />
          </TippyContainer>
        </Tippy>
        <Tippy content="Download" placement="top" trigger="mouseenter">
          <TippyContainer
            onClick={isDownloading ? undefined : handleDownload}
            style={{
              cursor: isDownloading ? 'not-allowed' : 'pointer',
              opacity: isDownloading ? 0.6 : 1,
            }}
          >
            <DownloadIcon />
          </TippyContainer>
        </Tippy>
      </Row>
    </Actions>
  );
}

// Styled components for styling
const Actions = styled.div``;

const TippyContainer = styled.div`
  display: inline-block;
  margin: 7px;
`;

const Row = styled.div`
  gap: 10px;
  cursor: pointer;
  display: flex;
  align-items: center;
`;

export default Action;
