import { useEffect, useState } from 'react';
import { useRouteMatch } from 'react-router-dom';
import { connect } from 'react-redux';

import s from './DetailOrder.module.css';
import { actionLoading } from '../../../redux/loading/action';
import { orderById } from '../../../api-data';
import { IOrderDetail } from '../../../typescript/orders/interfaces';
import {
  TRouteMatchId,
  TDispatchLoading,
} from '../../../typescript/orders/types';

function DetailOrder({ dispatchLoading }: TDispatchLoading) {
  const {
    params: { id },
  }: TRouteMatchId = useRouteMatch();

  const [order, setOrder] = useState<IOrderDetail | null>(null);

  useEffect(() => {
    async function getGood() {
      try {
        dispatchLoading(true);
        const data = await orderById<IOrderDetail>(id);
        setOrder(data);
      } catch (e) {
        console.error(e);
      } finally {
        dispatchLoading(false);
      }
    }
    getGood();
  }, [dispatchLoading, id]);

  return order ? (
    <div className={s.detailOrder_wrapper}>
      <p>_id : {order._id ? order._id : 'missed'}</p>
      <p>createdAt : {order.createdAt ? order.createdAt : 'missed'}</p>
    </div>
  ) : null;
}
const mapDispatchToProps = (dispatch: any) => ({
  dispatchLoading: (value: boolean) => dispatch(actionLoading(value)),
});

export default connect(null, mapDispatchToProps)(DetailOrder);
