import React from 'react';
import styled from 'styled-components';
import {
  useAtom,
  useReturnAfterOrderData,
  useReturnData,
} from '../order-view/store';
import { filtersReducerAtom } from '../order-daily-overview/header-filters/filterStore';
import { ExportButton, useAxios } from '@bjsdistribution/dms-component-library';
import { useParams } from 'react-router-dom';
import { filtersReducerReturnAtom } from '../order-daily-overview/return-after-table/table-filters/ReturnFilterStore';
import { notification } from 'antd';
import {
  useSelectedClientAfterOrders,
  useSelectedClientPortOrders,
  // useSelectedClientPortOrders,
} from '../store';

const ReturnRTFilters = () => {
  const [returnData] = useReturnData();
  const [pendingState] = useAtom(filtersReducerAtom);
  const [state] = useAtom(filtersReducerReturnAtom);
  const [returnAfterOrder] = useReturnAfterOrderData();
  // const [selectedReturnOrder] = useSelectedClientPortOrders();
  const [
    selectedOrderIds,
    setSelectedOrderIds,
  ] = useSelectedClientAfterOrders();
  const [
    selectedPendingOrderIds,
    setSelectedPendingOrderIds,
  ] = useSelectedClientPortOrders();
  const { status } = useParams<{ status: any }>();
  const { 'x-filters': pendingFilters } = pendingState;

  let moduleInfo: any | null = null;
  if (status === 'outstanding_return') {
    moduleInfo = {
      isExportedData: returnData?.length > 0,
      moduleName: 'return',
      filter: pendingFilters,
      file_type: 'csv',
      apiUrlEndPoint: `v1/return/product/pending/`,
      reference: 'return_export',
      feature_name: 'return',
    };
  } else if (['scheduled_for_return', 'return_completed'].includes(status)) {
    const { 'x-filters': orderFilters } = state;

    moduleInfo = {
      isExportedData: returnAfterOrder?.length > 0,
      moduleName: 'return',
      filter: orderFilters,
      file_type: 'csv',
      apiUrlEndPoint: `v1/return/orders/`,
      reference: 'return_overview_export',
      feature_name: 'return',
    };
  }
  //Export Manifest
  const isExportEnabled =
    status === 'outstanding_return'
      ? selectedPendingOrderIds?.length > 0
      : status === 'scheduled_for_return' || status === 'return_completed'
      ? selectedOrderIds?.length > 0
      : false;
  const { fetchData: callExportApi } = useAxios<{
    data: any[];
    message: string;
  }>({
    endpoint: `/v1/orders/import/manifest/csv/`,
    method: 'POST',
  });

  const handleExportManifest = async () => {
    if (!isExportEnabled) return;

    const exportOrderIds =
      status === 'outstanding_return'
        ? selectedPendingOrderIds
        : status === 'scheduled_for_return' || status === 'return_completed'
        ? selectedOrderIds
        : [];

    try {
      const response = (await callExportApi({
        payload: { order_ids: exportOrderIds },
      })) as {
        code: number | null;
        error?: string | null;
        data?: {
          url?: string;
        };
        message?: string;
      };

      if (response?.data?.url) {
        notification.success({
          message: 'Success',
          description: response?.message || 'Export completed.',
        });
        window.open(response?.data?.url, '_blank');

        if (status === 'outstanding_return') {
          setSelectedPendingOrderIds([]);
        } else if (
          status === 'scheduled_for_return' ||
          status === 'return_completed'
        ) {
          setSelectedOrderIds([]);
        }
      } else {
        notification.error({
          message: 'No File URL',
          description: 'Export succeeded but no download URL was returned.',
        });
      }
    } catch (error) {
      console.error('Error during export or download:', error);
      notification.error({
        message: 'Export Failed',
        description: 'Something went wrong during export.',
      });

      if (status === 'outstanding_return') {
        setSelectedPendingOrderIds([]);
      } else if (
        status === 'scheduled_for_return' ||
        status === 'return_completed'
      ) {
        setSelectedOrderIds([]);
      }
    }
  };

  return (
    <StyledBulkFilterCover className="dmsBulkFilter">
      <ExportButton moduleInfoModule={moduleInfo} />
      <StyledBulkItem
        onClick={handleExportManifest}
        style={{
          pointerEvents: isExportEnabled ? 'auto' : 'none',
          opacity: isExportEnabled ? 1 : 0.5,
        }}
      >
        <Text>Export Manifest</Text>
      </StyledBulkItem>
    </StyledBulkFilterCover>
  );
};

const Text = styled.div`
  color: #6a7378;
  text-align: center;
  font-size: 14px;
  font-style: normal;
  font-weight: 500;
  line-height: 18px;
`;
export const StyledBulkFilterCover = styled.div`
  border-radius: 100px;
  border: 1px solid rgba(208, 213, 221, 0.5);
  background: #fff;
  display: flex;
  min-height: 40px;
  // gap: 8px;
`;

export const StyledBulkItem = styled.div`
  padding: 6px 12px;
  display: flex;
  align-items: center;
  border-right: 1px solid #d0d5dd;
  gap: 8px;
  position: relative;
  a {
    text-decoration: none;
  }
  &.disabled {
    /* opacity: 0.5; */
    width: 150px;
    cursor: default;
    a {
      cursor: default;

      label {
        cursor: default;
      }
    }
  }
  &:hover:not(:disabled) {
    background: #f0f0f0;
    cursor: pointer;
  }

  @media screen and (max-width: 1030px) {
    padding: 6px 4px;
  }

  ul {
    margin: 0;
    padding: 0;
    list-style: none;
    box-sizing: border-box;
    top: 54px;
  }
  &:last-child {
    border-right: none;
  }
  &.active svg.arrowDown {
    transform: rotate(180deg);
  }
  label {
    color: #3a3630;
    text-align: center;
    font-family: 'Open Sans';
    font-size: 14px;
    font-style: normal;
    font-weight: 400;
    line-height: 18px;
    cursor: pointer;
  }

  &.noPadding {
    padding: 0;
  }
`;
export default ReturnRTFilters;
