import { useRosettaColors } from "@/app/hooks/useRosettaColors";
import { useImageViewer } from "@/app/providers/ImageViewerProvider/useImageViewer";
import { AspectRatio, Button, Flex, Paper, Text } from "@mantine/core";
import { IconArrowDown } from "@tabler/icons-react";
import { useEffect, useRef, useState } from "react";
import { AttachmentProps } from "./MessageAttachments";
import { AnimatedRoundedProgress } from "../AnimatedRoundedProgress/AnimatedRoundedProgress";
import { ImageToView } from "@/app/providers/ImageViewerProvider/ImageViewerProvider";
import { DownloadStatus, useAttachment } from "@/app/providers/AttachmentProvider/useAttachment";
import { PopoverLockIconAvatar } from "../PopoverLockIconAvatar/PopoverLockIconAvatar";
import { useRosettaBreakpoints } from "@/app/hooks/useRosettaBreakpoints";
import { blurhashToBase64Image } from "@/app/workers/image/image";

export function MessageAvatar(props: AttachmentProps) {
    const colors = useRosettaColors();
    const {
        downloadPercentage, 
        //uploadedPercentage, 
        download, 
        downloadStatus,
        getBlob,
        getPreview} = useAttachment(props.attachment, props.chacha_key_plain);
    const mainRef = useRef<HTMLDivElement>(null);
    const { open } = useImageViewer();
    const preview = getPreview();
    const [blob, setBlob] = useState(props.attachment.blob);
    const {lg} = useRosettaBreakpoints();
    const [blurhashPreview, setBlurhashPreview] = useState("");


    useEffect(() => {
        constructBlob();
        constructFromBlurhash();
    }, [downloadStatus]);

    const constructBlob = async () => {
        let blob = await getBlob();
        setBlob(blob);
    }

    const openImageViewer = () => {
        const images: ImageToView[] = [{
            src: blob,
            caption: props.text,
            timestamp: props.timestamp
        }];

        open(images, 0);
    }

    const onClick = () => {
        if (downloadStatus == DownloadStatus.DOWNLOADED) {
            openImageViewer();
            return;
        }
        if (downloadStatus == DownloadStatus.NOT_DOWNLOADED) {
            download();
            return;
        }
    }

    const constructFromBlurhash = async () => {
        if (preview.length < 20) return;
        const blob = await blurhashToBase64Image(preview, 200, 220);
        setBlurhashPreview(blob);
    }

    return (
        <Paper withBorder p={'sm'}>
            <Flex gap={'sm'} direction={'row'}>
                <AspectRatio onClick={onClick} ref={mainRef} style={{
                    height: 60,
                    width: 60,
                    userSelect: 'none'
                }} ratio={16 / 9} pos={'relative'}>
                    {blob != "" && (
                        <img style={{
                            height: 60,
                            width: 60,
                            borderRadius: '50%',
                            objectFit: 'cover'
                        }} src={blob}></img>)}
                    {downloadStatus != DownloadStatus.DOWNLOADED && downloadStatus != DownloadStatus.PENDING && preview.length >= 20 && (
                        <>
                            <img style={{
                                width: 60,
                                height: 60,
                                borderRadius: '50%',
                                objectFit: 'cover'
                            }} src={blurhashPreview == "" ? undefined : blurhashPreview}></img>
                        </>
                    )}
                </AspectRatio>
                <Flex direction={"column"}>
                    <Flex direction={'row'} gap={5} align={'center'}>
                        <Text fw={500} fz={'sm'}>Avatar</Text>
                        <PopoverLockIconAvatar></PopoverLockIconAvatar>
                    </Flex>
                    <Text fz={'xs'} c={'dimmed'}>
                        An avatar image shared in the message.
                    </Text>
                    {downloadStatus != DownloadStatus.DOWNLOADED && (
                        <Flex direction={'row'} mt={'xs'} justify={'flex-end'} align={'center'} gap={'sm'}>
                            {lg && <Text fz={9} c={'dimmed'}>Avatars are end-to-end encrypted</Text>}
                            <Flex align={'center'}>
                                {downloadStatus == DownloadStatus.NOT_DOWNLOADED && 
                                    <Button leftSection={<IconArrowDown size={14}></IconArrowDown>} size={'xs'} variant={'light'} onClick={download}>Download</Button>
                                }
                                {downloadStatus == DownloadStatus.DOWNLOADING && 
                                    <Button leftSection={<AnimatedRoundedProgress size={14} color={colors.brandColor} value={downloadPercentage}></AnimatedRoundedProgress>} size={'xs'} variant={'light'}>Download</Button>
                                }
                            </Flex>
                        </Flex>                        
                    )}
                </Flex>
            </Flex>
        </Paper>
    );
}
