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

type ShipmentViewProps = {
    activePgroup: string,
    pgroups: string,
};

const ShipmentView: React.FC<ShipmentViewProps> = ({activePgroup, pgroups}) => {
    const { shipments, error, defaultContact, fetchAndSetShipments } = useShipments(activePgroup);
    const [selectedShipment, setSelectedShipment] = useState<Shipment | null>(null);
    const [selectedDewar, setSelectedDewar] = useState<Dewar | null>(null);
    const [isCreatingShipment, setIsCreatingShipment] = useState(false);

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

    useEffect(() => {
        // Detect the current environment
        const mode = import.meta.env.MODE;

        // Dynamically set `OpenAPI.BASE` based on the mode
        OpenAPI.BASE =
            mode === 'test'
                ? import.meta.env.VITE_OPENAPI_BASE_TEST
                : mode === 'prod'
                    ? import.meta.env.VITE_OPENAPI_BASE_PROD
                    : import.meta.env.VITE_OPENAPI_BASE_DEV;

        // Log warning if `OpenAPI.BASE` is unresolved
        if (!OpenAPI.BASE) {
            console.error('OpenAPI.BASE is not set. Falling back to a default value.');
            OpenAPI.BASE = 'https://default-url.com'; // Use a consistent fallback
        }

        // Debug for mode and resolved `BASE`
        console.log('Environment Mode:', mode);
        console.log('Resolved OpenAPI.BASE:', OpenAPI.BASE);

        fetchAndSetShipments(); // Fetch data using the base URL
    }, []);

    const handleSelectShipment = (shipment: Shipment | null) => {
        setSelectedShipment(shipment);
        setIsCreatingShipment(false);
    };

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

    const renderShipmentContent = () => {
        if (isCreatingShipment) {
            return (
                <ShipmentForm
                    activePgroup={activePgroup}
                    sx={{ flexGrow: 1 }}
                    onCancel={handleCancelShipmentForm}
                    refreshShipments={fetchAndSetShipments}
                />
            );
        }
        if (selectedShipment) {
            return (
                <ShipmentDetails
                    pgroups={pgroups}
                    activePgroup={activePgroup}
                    isCreatingShipment={isCreatingShipment}
                    sx={{ flexGrow: 1 }}
                    selectedShipment={selectedShipment}
                    selectedDewar={selectedDewar}
                    setSelectedDewar={setSelectedDewar}
                    setSelectedShipment={setSelectedShipment}
                    refreshShipments={fetchAndSetShipments}
                    defaultContact={defaultContact}
                />
            );
        }
        return <div>No shipment details available.</div>;
    };

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

export default ShipmentView;