import React, { useEffect } from 'react';
import ExpandedContent from './expanded-content';
import CollapsedContent from './collapsed-content';
import CollapsableForm from '../../../common/expand-collapse';
import { useOrderDetails, useProductDetails } from '../store';
import { useLoading } from '../../order-daily-overview/store/store';
import { useAxios } from '@bjsdistribution/dms-component-library';

interface ApiResponse {
  message: string;
  code: number;
  error: string | null;
  error_traceback: string | null;
  data: [];
  setShouldPerformAction: boolean;
}

function ProductsInfo() {
  const [data] = useOrderDetails();
  const returnOrder = data;

  // For API Call
  const [, setAPidata] = useProductDetails();
  const [, setLoading] = useLoading();
  const {
    data: returnOrdersData,
    loading,
    fetchData: callReturnProducts,
  } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `/v1/return/products/${returnOrder?.id}`,
    method: 'GET',
  });

  useEffect(() => {
    if (returnOrder?.id) {
      callReturnProducts();
    }
  }, [returnOrder.id]);

  useEffect(() => {
    setLoading(loading);
    if (returnOrdersData && returnOrdersData.data) {
      const requiredData = returnOrdersData.data;
      if (requiredData.length > 0) {
        setAPidata(requiredData);
      } else {
        setAPidata(null);
      }
    }
  }, [returnOrdersData, loading]);

  return (
    <CollapsableForm collapsedContent={<CollapsedContent />}>
      <ExpandedContent />
    </CollapsableForm>
  );
}

export default ProductsInfo;
