import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { useApiHook } from '@bjsdistribution/dms-component-library';
import { ApiResponse } from '../../types';
import { useOrderDetails, useOrderId, useProductDetails } from '../../store';
import { Select } from 'antd';
import { useNewReturnOrderData, useSelectedProducts } from '../../../store';
import { atom, useAtom } from 'jotai';

export const payloadAtom = atom<any>(null);

const NewReturnDropdown = () => {
  const defaultSelectStyle = { width: '100%' };
  const defaultPopupClassName = 'dropDownStyle';
  const [returnOrderData, setReturnOrderData] = useNewReturnOrderData();
  const [selectedOrderId, setSelectedOrderId] = useState<string | null>(null);
  const [selectedProducts] = useSelectedProducts();
  const [orderData] = useOrderDetails();
  const [, setPayload] = useAtom(payloadAtom);
  const [productData] = useProductDetails();
  const [idProduct, setId] = useState<any>();
  const [orderId] = useOrderId();

  const id = orderData?.customer_id;
  useEffect(() => {
    const allProductIds =
      productData?.map((product: any) => product?.return_location) || [];
    setId(allProductIds);
  }, [productData]);

  const filters = [
    { field: 'customer_id', op: '=', value: id },
    { field: 'is_deleted', op: '=', value: 0 },
    { field: 'status', op: '!=', value: 'SD' },
    { field: 'id', op: '!=', value: orderId },
  ];

  if (idProduct?.length > 0 && idProduct[0]) {
    filters.push({
      field: 'return_order_products.return_location',
      op: '=',
      value: idProduct[0],
    });
  }

  const { data: fetchedReturnOrderData, setShouldPerformAction } = useApiHook<
    ApiResponse
  >({
    endpoint: '/v1/return/orders/',
    method: 'GET',
    filters: filters && filters?.length > 0 ? filters : undefined,
    //@ts-ignore
    pagination: { is_pagination: false },
    performAction: false,
  });

  useEffect(() => {
    if (id && idProduct?.length > 0 && idProduct[0]) {
      setShouldPerformAction(true);
    }
  }, [id, idProduct, setShouldPerformAction]);

  useEffect(() => {
    if (fetchedReturnOrderData && fetchedReturnOrderData?.data && id !== null) {
      setReturnOrderData(fetchedReturnOrderData?.data);
    }
  }, [fetchedReturnOrderData, id]);

  useEffect(() => {
    if (selectedOrderId && selectedProducts?.length > 0) {
      const newPayload = {
        new_return_order: selectedOrderId,
        products: selectedProducts,
      };
      setPayload(newPayload);
    }
  }, [selectedOrderId, selectedProducts, setPayload]);

  const handleDropdownChange = (value: string) => {
    setSelectedOrderId(value);
  };
  const dropdownOptions = returnOrderData?.map((order: any) => ({
    label: `${order?.recipient_name} - ${order?.postcode}`,
    value: order?.id,
  }));

  return (
    <Container>
      <Text>New Return Order:</Text>
      <StyledAntSelect
        options={dropdownOptions}
        value={selectedOrderId}
        placeholder="Select"
        // @ts-ignore
        onChange={handleDropdownChange}
        style={defaultSelectStyle}
        showSearch
        dropdownStyle={{ minWidth: '150px', width: 'auto' }}
        popupClassName={defaultPopupClassName}
        status={
          dropdownOptions.length === 0 ? '' : selectedOrderId ? '' : 'error'
        }
        notFoundContent="No orders found with a similar postcode"
      />
    </Container>
  );
};

const StyledAntSelect = styled(Select)`
  .ant-select-selector {
    /* width: 22vw; */
    border-radius: 22px;
  }
  .ant-select-clear {
    top: 40% !important;
    font-size: 18px !important;
  }
`;

const Container = styled.div`
  display: flex;
  align-items: center;
  gap: 10px;
  align-self: stretch;
  white-space: nowrap;
`;

const Text = styled.div`
  color: #000;
  font-family: 'Lato';
  font-size: 13px;
  font-weight: 400;
  line-height: 16px;
`;

export default NewReturnDropdown;
