import React from 'react';
import { Box, Typography, Alert } from '@mui/material';
import styled, { keyframes, css } from 'styled-components';
import LocationOnIcon from '@mui/icons-material/LocationOn';
import CountdownTimer from './CountdownTimer';

export interface SlotData {
    id: number;
    qr_code: string;
    label: string;
    qr_base: string;
    occupied: boolean;
    dewar_unique_id?: string;
    dewar_name?: string;
    needs_refill?: boolean;
    time_until_refill?: number;
    beamlineLocation?: string;
}

interface SlotProps {
    data: SlotData;
    isSelected: boolean;
    onSelect: (data: SlotData) => void;
}

const pulse = keyframes`
    0% {
        box-shadow: 0 0 5px 5px rgba(255, 0, 0, 0.6);
    }
    50% {
        box-shadow: 0 0 5px 15px rgba(255, 0, 0, 0.2);
    }
    100% {
        box-shadow: 0 0 5px 5px rgba(255, 0, 0, 0.6);
    }
`;

const StyledSlot = styled(Box)<{
        isSelected: boolean;
        isOccupied: boolean;
        atBeamline: boolean;
        needsRefillSoon: boolean
    }>`
    padding: 16px;
    margin: 8px;
    width: 140px;
    height: 220px;
    background-color: ${({ isSelected, isOccupied, atBeamline }) => {
        if (atBeamline) {
            return isSelected ? '#cc7a00' : '#ff9800'; // Darker orange if selected
        }
        if (isOccupied) {
            return isSelected ? '#d32f2f' : '#f44336'; // Darker red if selected
        }
        return isSelected ? '#5a9e5c' : '#88bc8a'; // Darker green if selected
    }};
    color: white;
    cursor: pointer;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    border-radius: 8px;
    box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.1);
    transition: transform 0.2s, background-color 0.2s;
    
    ${({ isSelected }) =>
            isSelected &&
            css`
           border: 3px solid #3f51b5;
       `}
    /* Pulsing animation for occupied slots needing refill */
    ${({ isOccupied, needsRefillSoon }) =>
            isOccupied &&
            needsRefillSoon &&
            css`
                animation: ${pulse} 1.5s infinite;
            `}

    &:hover {
        transform: scale(1.05);
    }
`;

const BottleIcon: React.FC<{ fillHeight: number }> = ({ fillHeight }) => {
    const pixelHeight = (276.777 * fillHeight) / 100; // Calculate height for the LN2 level
    const yPosition = 276.777 - pixelHeight; // Adjust level to "fill" the bottle from the bottom

    return (
        <svg height="80px" width="40px" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 276.777 276.777">
            <defs>
                <clipPath id="bottle-clip">
                    <path
                        d="M190.886,82.273c-3.23-2.586-7.525-7.643-7.525-21.639V43h8.027V0h-106v43h8.027v17.635
                    c0,11.66-1.891,17.93-6.524,21.639c-21.813,17.459-31.121,36.748-31.121,64.5v100.088c0,16.496,13.42,29.916,29.916,29.916
                    h105.405c16.496,0,29.916-13.42,29.916-29.916V146.773C221.007,121.103,210.029,97.594,190.886,82.273z"
                    />
                </clipPath>
            </defs>
            <path
                fill="lightgray"
                d="M190.886,82.273c-3.23-2.586-7.525-7.643-7.525-21.639V43h8.027V0h-106v43h8.027v17.635
                c0,11.66-1.891,17.93-6.524,21.639c-21.813,17.459-31.121,36.748-31.121,64.5v100.088c0,16.496,13.42,29.916,29.916,29.916
                h105.405c16.496,0,29.916-13.42,29.916-29.916V146.773C221.007,121.103,210.029,97.594,190.886,82.273z"
            />
            <rect x="0" y={yPosition} width="100%" height={pixelHeight} fill="#00bfff" clipPath="url(#bottle-clip)" />
        </svg>
    );
};

const Slot: React.FC<SlotProps> = ({ data, isSelected, onSelect }) => {
    const { label, occupied, time_until_refill, dewar_unique_id, dewar_name, beamlineLocation } = data;

    // Calculate fill height for the LN2 bottle level (only visual, no percentage displayed)
    const calculateFillHeight = (timeUntilRefill?: number) => {
        if (timeUntilRefill === undefined || timeUntilRefill <= 0) {
            return 0; // Return 0% if time is undefined or negative
        }
        const maxTime = 172800; // Example maximum time for calculating the level (2 days in seconds)
        return Math.min((timeUntilRefill / maxTime) * 100, 100);
    };

    const fillHeight = calculateFillHeight(time_until_refill);

    // Determine slot state
    const isSpecificBeamline = beamlineLocation === 'X10SA' || beamlineLocation === 'X06SA' || beamlineLocation === 'X06DA';
    const needsRefillSoon = occupied && (time_until_refill !== undefined && time_until_refill <= 10800);


    return (
        <StyledSlot
            isSelected={isSelected}
            isOccupied={occupied}
            atBeamline={isSpecificBeamline}
            needsRefillSoon={needsRefillSoon}
            onClick={() => onSelect(data)}
        >
            {/* Top Content: Label and dewar name */}
            <Box textAlign="center" width="100%" mb={2}>
                <Typography variant="h6">{label}</Typography>
                {dewar_name && <Typography variant="body2">{dewar_name}</Typography>}
            </Box>

            {/* Icons Section: Location and Bottle Icon */}
            <Box
                display="flex"
                flexDirection="row"
                alignItems="center"
                gap="16px"
                justifyContent="center"
                width="100%"
            >
                {/* Location Icon */}
                {isSpecificBeamline && (
                    <Box display="flex" flexDirection="column" alignItems="center">
                        <LocationOnIcon style={{ fontSize: '36px', color: '#37ff00' }} />
                        <Typography variant="caption" style={{ fontWeight: 'bold', textAlign: 'center' }}>
                            {beamlineLocation}
                        </Typography>
                    </Box>
                )}

                {/* Bottle Icon with LN2 Level */}
                {dewar_unique_id && (
                    <Box display="flex" flexDirection="column" alignItems="center">
                        <BottleIcon fillHeight={fillHeight} />
                    </Box>
                )}
            </Box>


            {/* Countdown Timer */}
            {dewar_unique_id && time_until_refill !== undefined && time_until_refill !== -1 && (
                <CountdownTimer key={dewar_unique_id} totalSeconds={time_until_refill} />
            )}

            {/* Warnings */}
            {occupied && time_until_refill === -1 && (
                <Alert severity="warning">This dewar has no recorded refill event. It needs to be refilled.</Alert>
            )}
        </StyledSlot>
    );
};

export default Slot;