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

const useShipments = (activePgroup: string) => {
    const [shipments, setShipments] = useState<Shipment[]>([]);
    const [error, setError] = useState<string | null>(null);
    const [defaultContact, setDefaultContact] = useState<Contact | undefined>();

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

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

    useEffect(() => {
        if (activePgroup) {
            fetchAndSetShipments();
            fetchDefaultContact();
        }
    }, [activePgroup]); // Refetch shipments when activePgroup changes

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

export default useShipments;