import { ChangeEvent, useEffect, useRef, useState } from "react";
import { Box, Button, Typography } from "@mui/material";

import type {
    QuizQuestionFile,
    UploadFileType,
} from "@model/questionTypes/file";

const UPLOAD_FILE_TYPES_MAP: Record<UploadFileType, string> = {
    picture: "image/*",
    video: "video/*",
    audio: "audio/*",
    document:
        ".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.pdf",
} as const;

interface Props {
    question: QuizQuestionFile;
}

export default function File({ question }: Props) {
    const fileInputRef = useRef<HTMLInputElement>(null);
    const [file, setFile] = useState<File | null>(null);
    const [acceptedType, setAcceptedType] = useState<any>(
        UPLOAD_FILE_TYPES_MAP.picture
    );

    useEffect(() => {
        setAcceptedType(UPLOAD_FILE_TYPES_MAP[question.content.type]);
    }, [question.content.type]);

    function handleFileChange(event: ChangeEvent<HTMLInputElement>) {
        if (!event.target.files?.[0]) return setFile(null);
        setFile(event.target.files[0]);
    }

    return (
        <Box
            sx={{
                display: "flex",
                flexDirection: "column",
                alignItems: "start",
                gap: 1,
            }}
        >
            <Typography variant="h6" data-cy="question-title">{question.title}</Typography>
            <Button variant="contained" onClick={() => fileInputRef.current?.click()}>
                Загрузить файл
                <input
                    ref={fileInputRef}
                    onChange={handleFileChange}
                    type="file"
                    accept={acceptedType}
                    data-cy="file-upload-input"
                    style={{
                        display: "none",
                    }}
                />
            </Button>
            {file && <Typography data-cy="chosen-file-name">Выбран файл: {file.name}</Typography>}
        </Box>
    );
}
