import React, { useMemo } from 'react';
import styled from 'styled-components';
import { PrintMenu } from '../../fakedata';
import { useOrderDetails, useOrderStaticData } from '../../store';
import { Dropdown, Space } from 'antd';
import ArrowDownIcon from '../../../../assets/icons/ArrowDownIcon';
import { getBaseEndpoint } from '@bjsdistribution/dms-component-library';

function Print() {
  const [orderDetails] = useOrderDetails();
  const gsitId = orderDetails?.gsit_order_id;

  const orderId = useMemo(() => {
    return orderDetails?.id;
  }, [orderDetails]);
  //new
  const [orderStaticData] = useOrderStaticData();
  const orderTypeID = useMemo(() => {
    return orderDetails?.order_type_id;
  }, [orderDetails]);

  const getEnvironment = ():
    | 'development'
    | 'release_us'
    | 'release_uk'
    | 'staging' => {
    const projectEnv = process.env.REACT_APP_PROJECT_ENV;
    const apiPath = process.env.REACT_APP_API_PATH;

    if (apiPath === 'https://us.dms.api.bjshomedelivery.com') {
      return 'release_us';
    }
    if (apiPath === 'https://development.dms.api.bjshomedelivery.com') {
      return 'development';
    }
    if (apiPath === 'https://staging.dms.api.bjshomedelivery.com') {
      return 'staging';
    }

    if (projectEnv === 'release_uk') {
      return 'release_uk';
    }
    if (projectEnv === 'release_us') {
      return 'release_us';
    }
    if (projectEnv === 'staging') {
      return 'staging';
    }
    return 'development';
  };

  const getBaseUrl = (): string => {
    const environment = getEnvironment();
    switch (environment) {
      case 'release_uk':
      case 'release_us':
        return 'https://us.toolbox.bjshomedelivery.com/api/v1/gsit';
      case 'staging':
        return 'https://staging.toolbox.bjshomedelivery.com/api/v1/gsit';
      default:
        return 'https://development.toolbox.bjshomedelivery.com/api/v1/gsit';
    }
  };

  const getUrl = (option: string) => {
    const val = option?.toLowerCase()?.replaceAll(' ', '');
    const baseUrl = getBaseUrl();

    if (!gsitId) {
      console.error('Missing orderId. Cannot generate Return Labels URL.');
      return '';
    }
    if (val === 'returnlabels') {
      return `${baseUrl}/generate_labels?pdf=true&product_type=Return&order_id=${gsitId}`;
    } else {
      return '';
    }
  };

  const handleSelectChange = (selectedOption: any) => {
    const selectedValue = selectedOption?.value;
    const baseEndpoint = getBaseEndpoint();
    if (selectedValue) {
      //return
      if (selectedValue === 'returncovernote') {
        window.open(
          `${baseEndpoint}/orders/return_cover_notes/?order_id=${orderId}`,
          '_blank'
        );
        //proof
      } else if (selectedValue === 'proofofdelivery') {
        window.open(
          `${baseEndpoint}/orders/generate_note/?order_id=${orderId}&output_format=pdf`,
          '_blank'
        );
      } else {
        const url = getUrl(selectedValue);
        window.open(url, '_blank');
      }
    }
  };

  const isOptionDisabled = (optionValue: any) => {
    const orderType = orderStaticData?.order_type?.find(
      (type: any) => type?.id === orderTypeID
    );
    if (optionValue === 'ordercovernote') {
      if (orderType?.type === 'return') {
        return false;
      }
      return true;
    }
    return false;
  };

  const filteredOptions = PrintMenu?.map((option: any) => ({
    key: option.value,
    label: option.label,
    value: option.value,
  }));

  const menuItems = {
    items: filteredOptions?.map((option: any) => {
      const disabled = isOptionDisabled(option.value);

      return {
        key: option.value,
        label: (
          <div
            onClick={e => {
              e.stopPropagation();
              if (!disabled) {
                handleSelectChange(option);
              }
            }}
            style={{
              color: disabled ? '#bfbfbf' : undefined,
              cursor: disabled ? 'not-allowed' : 'pointer',
            }}
          >
            {option.label}
          </div>
        ),
        disabled,
      };
    }),
  };

  return (
    <Container>
      <Dropdown menu={menuItems} trigger={['hover']}>
        <a onClick={e => e.preventDefault()} style={{ cursor: 'pointer' }}>
          <StyledSpace>
            PRINT
            <ArrowDownIcon fill={'#f0f2f2'} />
          </StyledSpace>
        </a>
      </Dropdown>
    </Container>
  );
}

const Container = styled.div``;

const StyledSpace = styled(Space)`
  .ant-space-item {
    color: #6a7378;
    text-align: center;
    font-family: Lato;
    font-size: 14px;
    font-style: normal;
    font-weight: 500;
  }
`;

export default Print;
