import { useState, useEffect } from 'react';
import { ShipmentsService, Shipment, ContactPerson } from '../../openapi';

const useShipments = () => {
    const [shipments, setShipments] = useState<Shipment[]>([]);
    const [error, setError] = useState<string | null>(null);
    const [defaultContactPerson, setDefaultContactPerson] = useState<ContactPerson | undefined>();

    const fetchAndSetShipments = async () => {
        try {
            const shipmentsData = await ShipmentsService.fetchShipmentsShipmentsGet();
            setShipments(shipmentsData);
        } catch (error) {
            console.error('Failed to fetch shipments:', error);
            setError('Failed to fetch shipments. Please try again later.');
        }
    };

    const fetchDefaultContactPerson = async () => {
        try {
            const contacts = await ShipmentsService.getShipmentContactPersonsShipmentsContactPersonsGet();
            setDefaultContactPerson(contacts[0]);
        } catch (error) {
            console.error('Failed to fetch contact persons:', error);
            setError('Failed to load contact persons. Please try again later.');
        }
    };

    useEffect(() => {
        fetchAndSetShipments();
        fetchDefaultContactPerson();
    }, []);

    return { shipments, error, defaultContactPerson, fetchAndSetShipments };
};

export default useShipments;