import { Box } from '@mui/material';
import React, { useEffect, useState } from 'react'
import { useGetOrdersByOwnerIdQuery } from '../store/api';
import Loader from '../components/Loader';
import Title from '../components/Title';
import OrderCard from '../components/OrderCard';
import { useParams } from 'react-router-dom';
import LinkButton from '../components/LinkButton';

export default function UserPage() {
  const { userId } = useParams();
  const { data, error, isFetching } = useGetOrdersByOwnerIdQuery(userId);
  const [sortedData, setSortedData] = useState();
  useEffect(() => {
    if (data) {
      const dataForSort = [...data?.OrderFind];
      setSortedData(dataForSort?.sort((a, b) => b.createdAt - a.createdAt));
    }
  }, [data]);

  return (
    <>
      <LinkButton to={`/user/${userId}/edit`}>Edit profile</LinkButton>
      <Title>My orders</Title>
      {isFetching ? <Loader /> :
        <Box>
          {sortedData?.map(order => <OrderCard key={order._id} order={order} />)}
        </Box>}
    </>
  )
}
