import { useEffect, useState } from 'react';

import { LandingService } from '../../api/landing';
import { Order } from '../../models/landing';
import { FetchOrderQueryResponse } from '../../models/api';

export const useFetchOrderDetails = ({
  orderId,
}: {
  orderId: Order.View['id'];
}) => {
  const { fetchOrder } = LandingService();

  const [data, setData] = useState<FetchOrderQueryResponse>();
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);

      try {
        const data = await fetchOrder(orderId);
        setData(data.body);
      } catch (error) {
        setError(error.message);
      } finally {
        setIsLoading(false);
      }
    };

    fetchData();
  }, []);

  return {
    isLoading,
    data,
    error,
  };
};
