import React, { useState, useEffect } from 'react';
import Grid from '@mui/material/Grid';
import ShipmentPanel from '../components/ShipmentPanel';
import ShipmentDetails from '../components/ShipmentDetails';
import ShipmentForm from '../components/ShipmentForm';
import { Dewar, OpenAPI, ContactPerson, ShipmentsService } from '../../openapi';

type ShipmentViewProps = React.PropsWithChildren<Record<string, never>>;

const API_BASE_URL = 'http://127.0.0.1:8000';
OpenAPI.BASE = API_BASE_URL;  // Setting API base URL

const ShipmentView: React.FC<ShipmentViewProps> = () => {
    const [isCreatingShipment, setIsCreatingShipment] = useState(false);
    const [selectedShipment, setSelectedShipment] = useState<ShipmentsService | null>(null);
    const [selectedDewar, setSelectedDewar] = useState<Dewar | null>(null);
    const [shipments, setShipments] = useState<ShipmentsService[]>([]);
    const [error, setError] = useState<string | null>(null);
    const [defaultContactPerson, setDefaultContactPerson] = useState<ContactPerson | undefined>();

    // Function to fetch and set shipments
    const fetchAndSetShipments = async () => {
        try {
            const shipmentsData: ShipmentsService[] = await ShipmentsService.fetchShipmentsShipmentsGet();
            shipmentsData.sort((a, b) => new Date(b.shipment_date).getTime() - new Date(a.shipment_date).getTime());
            setShipments(shipmentsData);
            console.log('Fetched and set shipments:', shipmentsData);
        } catch (error) {
            console.error('Failed to fetch shipments:', error);
            setError('Failed to fetch shipments. Please try again later.');
        }
    };

    // Function to fetch the default contact person
    const fetchDefaultContactPerson = async () => {
        try {
            const contacts: ContactPerson[] = 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.');
        }
    };

    // Use effects to fetch data on component mount
    useEffect(() => {
        fetchAndSetShipments();
        fetchDefaultContactPerson();
    }, []);

    useEffect(() => {
        console.log('Updated shipments:', shipments);
    }, [shipments]);

    // Handlers for selecting shipment and canceling form
    const handleSelectShipment = (shipment: ShipmentsService | null) => {
        setSelectedShipment(shipment);
        setIsCreatingShipment(false);
    };

    const handleCancelShipmentForm = () => {
        setIsCreatingShipment(false);
    };

    // Render the shipment content based on state
    const renderShipmentContent = () => {
        if (isCreatingShipment) {
            return (
                <ShipmentForm
                    sx={{ flexGrow: 1 }}
                    onCancel={handleCancelShipmentForm}
                    refreshShipments={fetchAndSetShipments}
                />
            );
        }
        if (selectedShipment) {
            return (
                <ShipmentDetails
                    isCreatingShipment={isCreatingShipment}
                    sx={{ flexGrow: 1 }}
                    selectedShipment={selectedShipment}
                    selectedDewar={selectedDewar}
                    setSelectedDewar={setSelectedDewar}
                    setSelectedShipment={setSelectedShipment}
                    refreshShipments={fetchAndSetShipments}
                    defaultContactPerson={defaultContactPerson}
                />
            );
        }
        return <div>No shipment details available.</div>;
    };

    // Render the main layout
    return (
        <Grid container spacing={2} sx={{ height: '100vh' }}>
            <Grid
                item
                xs={12}
                md={3}
                sx={{
                    display: 'flex',
                    flexDirection: 'column',
                    flexGrow: 0,
                }}
            >
                <ShipmentPanel
                    setCreatingShipment={setIsCreatingShipment}
                    selectShipment={handleSelectShipment}
                    shipments={shipments}
                    selectedShipment={selectedShipment}
                    refreshShipments={fetchAndSetShipments}
                    error={error}
                />
            </Grid>
            <Grid
                item
                xs={12}
                md={8}
                sx={{
                    display: 'flex',
                    flexDirection: 'column',
                    flexGrow: 1,
                }}
            >
                {renderShipmentContent()}
            </Grid>
        </Grid>
    );
};

export default ShipmentView;