import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import ProductTable from '../../return-client-products/ProductTable';
import NewReturnDropdown, {
  payloadAtom,
} from '../../notes/order-dropdown/NewReturnDropdown';
import { Button, useApiHook } from '@bjsdistribution/dms-component-library';
import { useAtom } from 'jotai';
import { ApiResponse } from '../../types';
import { usePostLoading, useSelectedProducts } from '../../../store';
// import { useOrderId } from '../../store';
import { useNavigate } from 'react-router-dom';
import { notification } from 'antd';
import { useOrderId } from '../../store';

function ExpandedContent() {
  const [payload] = useAtom(payloadAtom);
  const [, setPostLoading] = usePostLoading();
  const [orderId] = useOrderId();
  const [isButtonDisabled, setIsButtonDisabled] = useState(true);
  const navigate = useNavigate();
  const [, setSelectedProducts] = useSelectedProducts();

  const {
    data: response,
    setShouldPerformAction,
    loading: confirmLoading,
  } = useApiHook<{
    data: ApiResponse[];
  }>({
    endpoint: `/v1/return/product/move/?return_order_id=${orderId}`,
    method: 'POST',
    body: payload,
    performAction: false,
  });

  useEffect(() => {
    setPostLoading(confirmLoading);
  }, [confirmLoading, setPostLoading]);

  useEffect(() => {
    if (payload?.new_return_order && payload?.products?.length > 0) {
      setIsButtonDisabled(false);
    } else {
      setIsButtonDisabled(true);
    }
  }, [payload]);

  const handleConfirmReturn = () => {
    if (!isButtonDisabled) {
      setShouldPerformAction(true);
      setPostLoading(confirmLoading);
    } else {
      console.error('Payload is incomplete:', payload);
    }
  };

  const newId = Array.isArray(response?.data)
    ? //@ts-ignore
      response?.data?.[0]?.id
    : //@ts-ignore
      response?.data?.id;

  useEffect(() => {
    //@ts-ignore
    if (response?.code === 200) {
      notification.success({
        message: 'Success',
        //@ts-ignore

        description: response?.message || 'Products moved successfully',
      });
      setSelectedProducts([]);
    } else if (response) {
      notification.error({
        message: 'Error',
        //@ts-ignore

        description: response?.message || 'Error while moving products',
      });
    }

    //@ts-ignore
    if (response?.code === 200 && newId) {
      // suggested by rahul
      navigate(`${newId}`);
      setSelectedProducts([]);
    }
  }, [response, newId, navigate, setSelectedProducts]);

  return (
    <Container>
      <ProductTable />
      <MidContainer>
        <SaveNoteContainer>
          <Button
            style={{ borderRadius: '20px' }}
            onClick={handleConfirmReturn}
            disabled={isButtonDisabled}
          >
            Move Products
          </Button>
          <NewReturnDropdown />
        </SaveNoteContainer>
      </MidContainer>
    </Container>
  );
}

const MidContainer = styled.div`
  display: flex;
  justify-content: space-between;
  padding: 10px 15px;
  align-items: flex-start;
  border-top: 1px solid #edebe8;
  background: #f8fafc;
  margin: 0px -15px -15px -15px;
  border-radius: 0px 0px 8px 8px;
  margin-bottom: 22px;
`;

const SaveNoteContainer = styled.div`
  display: inline-flex;
  gap: 10px;
`;

const Container = styled.div``;

export default ExpandedContent;
