import { useState, useEffect, useRef } from "react";
import { useParams } from "react-router-dom";
import {
    Box,
    Typography,
    TextField,
    useMediaQuery,
    useTheme,
} from "@mui/material";
import { useDebouncedCallback } from "use-debounce";
import ButtonsOptions from "../ButtonsOptions";
import SwitchRating from "./switchRating";
import TropfyIcon from "../../../assets/icons/questionsPage/tropfyIcon";
import FlagIcon from "../../../assets/icons/questionsPage/FlagIcon";
import HeartIcon from "../../../assets/icons/questionsPage/heartIcon";
import LikeIcon from "../../../assets/icons/questionsPage/likeIcon";
import LightbulbIcon from "../../../assets/icons/questionsPage/lightbulbIcon";
import HashtagIcon from "../../../assets/icons/questionsPage/hashtagIcon";
import StarIconMini from "../../../assets/icons/questionsPage/StarIconMini";
import type { QuizQuestionRating } from "../../../model/questionTypes/rating";
import { updateQuestion } from "@root/questions/actions";


interface Props {
    question: QuizQuestionRating;
}

export type ButtonRatingFrom = {
    name: "star" | "trophie" | "flag" | "heart" | "like" | "bubble" | "hashtag";
    icon: JSX.Element;
};

export default function RatingOptions({ question }: Props) {
    const [switchState, setSwitchState] = useState("setting");
    const [negativeText, setNegativeText] = useState<string>("");
    const [positiveText, setPositiveText] = useState<string>("");
    const [negativeTextWidth, setNegativeTextWidth] = useState<number>(0);
    const [positiveTextWidth, setPositiveTextWidth] = useState<number>(0);
    const quizId = Number(useParams().quizId);
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down(790));
    const negativeRef = useRef<HTMLDivElement>(null);
    const positiveRef = useRef<HTMLDivElement>(null);

    const debounceNegativeDescription = useDebouncedCallback((value) => {
        updateQuestion(question.id, question => {
            if (question.type !== "rating") return;

            question.content.ratingNegativeDescription = value.substring(0, 15);
        });
    }, 200);
    const debouncePositiveDescription = useDebouncedCallback((value) => {
        updateQuestion(question.id, question => {
            if (question.type !== "rating") return;

            question.content.ratingPositiveDescription = value.substring(0, 15);
        });
    }, 200);

    useEffect(() => {
        setNegativeText(question.content.ratingNegativeDescription);
        setPositiveText(question.content.ratingPositiveDescription);
    }, []);

    useEffect(() => {
        setNegativeTextWidth(negativeRef.current?.offsetWidth || 0);
    }, [negativeText]);

    useEffect(() => {
        setPositiveTextWidth(positiveRef.current?.offsetWidth || 0);
    }, [positiveText]);

    const buttonRatingForm: ButtonRatingFrom[] = [
        {
            name: "star",
            icon: <StarIconMini width={35} color={theme.palette.grey2.main} />,
        },
        { name: "trophie", icon: <TropfyIcon color={theme.palette.grey2.main} /> },
        { name: "flag", icon: <FlagIcon color={theme.palette.grey2.main} /> },
        { name: "heart", icon: <HeartIcon color={theme.palette.grey2.main} /> },
        { name: "like", icon: <LikeIcon color={theme.palette.grey2.main} /> },
        {
            name: "bubble",
            icon: <LightbulbIcon color={theme.palette.grey2.main} />,
        },
        { name: "hashtag", icon: <HashtagIcon color={theme.palette.grey2.main} /> },
    ];

    const SSHC = (data: string) => {
        setSwitchState(data);
    };

    return (
        <>
            <Box
                sx={{
                    display: "flex",
                    px: "20px",
                    flexDirection: "column",
                    gap: "20px",
                    marginTop: isMobile ? "20px" : 0,
                }}
            >
                <Box
                    sx={{
                        width: isMobile ? "auto" : `${question.content.steps * 44}px`,
                        maxWidth: "440px",
                        display: "flex",
                        justifyContent: "space-between",
                        padding: "10px 10px 0 10px",
                        gap: isMobile ? "10px" : "30px",
                    }}
                >
                    {Array.from(
                        { length: question.content.steps },
                        (_, index) => index
                    ).map((itemNumber) => (
                        <Box
                            key={itemNumber}
                            {...(itemNumber === 0 || itemNumber === question.content.steps - 1
                                ? {
                                    onClick: () => {
                                        updateQuestion(question.id, question => {
                                            if (question.type !== "rating") return;

                                            question.content.ratingExpanded = true;
                                        });
                                    },
                                    sx: {
                                        cursor: "pointer",
                                        transform: "scale(1.5)",
                                        ":hover": {
                                            transform: "scale(1.7)",
                                            transition: "0.2s",
                                        },
                                    },
                                }
                                : { sx: { transform: "scale(1.5)" } })}
                        >
                            {
                                buttonRatingForm.find(
                                    ({ name }) => question.content.form === name
                                )?.icon
                            }
                        </Box>
                    ))}
                </Box>
                <Box
                    sx={{
                        mb: "20px",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "space-between",
                        maxWidth: "410px",
                        width: "100%",
                    }}
                >
                    <Box sx={{ minWidth: isMobile ? "140px" : "205px" }}>
                        <Typography
                            ref={negativeRef}
                            sx={{
                                position: "absolute",
                                opacity: 0,
                                zIndex: "-100",
                                whiteSpace: "nowrap",
                                fontSize: "16px",
                            }}
                        >
                            {negativeText}
                        </Typography>
                        <TextField
                            defaultValue={question.content.ratingNegativeDescription}
                            value={negativeText}
                            placeholder="Негативно"
                            onChange={({ target }: {target: HTMLInputElement}) => {
                                if (target.value.length <= 15) {
                                    setNegativeText(target.value);
                                    debounceNegativeDescription(target.value);
                                }
                            }}
                            onBlur={({ target }: {target: HTMLInputElement}) => debounceNegativeDescription(target.value)}
                            sx={{
                                width: negativeTextWidth + 10 + "px",
                                maxWidth: isMobile ? "140px" : "230px",
                                background: "transparent",
                                fontSize: "18px",
                                minWidth: "95px",
                                transition: "0.2s",
                                "& .MuiInputBase-root": {
                                    "& .MuiInputBase-input": {
                                        color: theme.palette.grey2.main,
                                        fontSize: "16px",
                                        padding: "0 3px",
                                        borderRadius: "3px",
                                        border: "1px solid",
                                        borderColor: "transparent",
                                        "&:hover, &:focus": {
                                            borderColor: theme.palette.grey2.main,
                                        },
                                    },
                                    "& .MuiOutlinedInput-notchedOutline": {
                                        outline: "none",
                                        border: "none",
                                    },
                                },
                            }}
                        />
                    </Box>
                    <Box sx={{ minWidth: isMobile ? "140px" : "205px", textAlign: isMobile ? "right" : undefined, }}>
                        <Typography
                            ref={positiveRef}
                            sx={{
                                position: "absolute",
                                opacity: 0,
                                zIndex: "-100",
                                whiteSpace: "nowrap",
                                fontSize: "16px",
                            }}
                        >
                            {positiveText}
                        </Typography>
                        <TextField
                            value={positiveText}
                            placeholder="Позитивно"
                            onChange={({ target }: {target: HTMLInputElement}) => {
                                if (target.value.length <= 15) {
                                    setPositiveText(target.value);
                                    debouncePositiveDescription(target.value);
                                }
                            }}
                            onBlur={({ target }: {target: HTMLInputElement}) => debouncePositiveDescription(target.value)}
                            sx={{
                                width: positiveTextWidth + 10 + "px",
                                maxWidth: isMobile ? "140px" : "230px",
                                background: "transparent",
                                fontSize: "18px",
                                minWidth: "95px",
                                transition: "0.2s",
                                "& .MuiInputBase-root": {
                                    "& .MuiInputBase-input": {
                                        color: theme.palette.grey2.main,
                                        fontSize: "16px",
                                        padding: "0 3px",
                                        borderRadius: "3px",
                                        border: "1px solid",
                                        borderColor: "transparent",
                                        "&:hover, &:focus": {
                                            borderColor: theme.palette.grey2.main,
                                        },
                                    },
                                    "& .MuiOutlinedInput-notchedOutline": {
                                        outline: "none",
                                        border: "none",
                                    },
                                },
                            }}
                        />
                    </Box>
                </Box>
            </Box>
            <ButtonsOptions
                switchState={switchState}
                SSHC={SSHC}
                question={question}
            />
            <SwitchRating switchState={switchState} question={question} />
        </>
    );
}
