import { IconButton, Skeleton, useTheme, Tooltip, ClickAwayListener } from "@mui/material";
import { useEffect, useState } from "react";
import CopyIcon from "@/assets/icons/CopyIcon";
import { useSnackbar } from "notistack";

interface CopyButtonProps {
    created_at: number;
    onCopy: (text: string) => void;
    text: string;
}

export const CopyButton = ({ created_at, onCopy, text }: CopyButtonProps) => {
    const theme = useTheme();
    const { enqueueSnackbar } = useSnackbar();
    const [open, setOpen] = useState(false);
    const [timeLeft, setTimeLeft] = useState<string>("");

    const getCreatedTime = (timestamp: number) => {
        // Если timestamp в секундах (10 цифр)
        if (timestamp.toString().length === 10) {
            return new Date(timestamp * 1000).getTime();
        }
        // Если timestamp в миллисекундах (13 цифр)
        return new Date(timestamp).getTime();
    };

    const formatTimeLeft = (milliseconds: number) => {
        const minutes = Math.floor(milliseconds / (1000 * 60));
        const seconds = Math.floor((milliseconds % (1000 * 60)) / 1000);
        return `${minutes}:${seconds.toString().padStart(2, '0')}`;
    };

    const [isLoading, setIsLoading] = useState(() => {
        if (!created_at) return false;
        const now = new Date().getTime();
        const created = getCreatedTime(created_at);
        const diffInMinutes = (now - created) / (1000 * 60);
        return diffInMinutes < 3;
    });

    useEffect(() => {
        if (!created_at) return;
        
        const now = new Date().getTime();
        const created = getCreatedTime(created_at);
        const diffInMinutes = (now - created) / (1000 * 60);
        
        if (now - created < 1000) {
            setIsLoading(true);
        }
        
        if (diffInMinutes < 3) {
            const timeLeft = Math.ceil((3 - diffInMinutes) * 60 * 1000);
            setTimeLeft(formatTimeLeft(timeLeft));
            
            const timer = setInterval(() => {
                const currentTime = new Date().getTime();
                const elapsed = currentTime - created;
                const remaining = 3 * 60 * 1000 - elapsed;
                
                if (remaining <= 0) {
                    setIsLoading(false);
                    clearInterval(timer);
                    return;
                }
                
                setTimeLeft(formatTimeLeft(remaining));
            }, 1000);
            
            return () => clearInterval(timer);
        }
    }, [created_at]);

    const handleClick = () => {
        if (isLoading) return;
        onCopy(text);
        enqueueSnackbar("Ссылка успешно скопирована", { variant: "success" });
    };

    const handleTooltipClose = () => {
        setOpen(false);
    };

    const handleTooltipOpen = () => {
        setOpen(true);
    };

    if (isLoading) {
        return (
            <ClickAwayListener onClickAway={handleTooltipClose}>
                <div>
                    <Tooltip
                        PopperProps={{
                            disablePortal: true,
                            sx: {
                                "& .MuiTooltip-tooltip": {
                                    minWidth: "175px",
                                    maxWidth: "175px",
                                    whiteSpace: "normal",
                                    textAlign: "center"
                                }
                            }
                        }}
                        placement="top"
                        onClose={handleTooltipClose}
                        open={open}
                        title={`Идёт процесс генерации вопросов, он будет закончен через ${timeLeft}`}
                        onMouseEnter={handleTooltipOpen}
                        onMouseLeave={handleTooltipClose}
                        sx={{
                            fontSize: "12px",
                            p: "10px"
                        }}
                    >
                        <Skeleton 
                            variant="circular" 
                            width={18} 
                            height={18} 
                            sx={{ 
                                bgcolor: theme.palette.grey[400],
                                marginRight: "-2px"
                            }} 
                        />
                    </Tooltip>
                </div>
            </ClickAwayListener>
        );
    }

    return (
        <IconButton
            edge="end"
            aria-label="copy"
            sx={{ 
                color: theme.palette.brightPurple.main,
                p: 0, 
                width: 18, 
                height: 18, 
                marginRight: "-2px",
                position: "relative",
                "&:hover": {
                    "&::after": {
                        content: '""',
                        position: "absolute",
                        top: "-15px",
                        left: "-15px",
                        right: "-15px",
                        bottom: "-15px",
                        borderRadius: "50%",
                        backgroundColor: theme.palette.grey[500],
                        opacity: 0.1,
                        zIndex: -1
                    }
                }
            }}
            onClick={handleClick}
        >
            <CopyIcon color={theme.palette.brightPurple.main} />
        </IconButton>
    );
}; 