import { Box, FormControl, FormLabel, FormGroup, FormControlLabel, Checkbox, Select, MenuItem, useTheme, Button, useMediaQuery, IconButton } from "@mui/material";
import { InfoPopover } from '@ui_kit/InfoPopover';
import CheckboxIcon from "@icons/Checkbox";
import { useState } from "react";
import { useCurrentQuiz } from "@/stores/quizes/hooks";
import { auditoryAdd } from "@/api/auditory";
import { useSnackbar } from "notistack";
import ArrowDownIcon from "@/assets/icons/ArrowDownIcon";
import AgeInputWithSelect from "./AgeInputWithSelect";

interface GenderAndAgeSelectorProps {
  handleAdd: (item: any) => void;
}

export default function GenderAndAgeSelector({ handleAdd }: GenderAndAgeSelectorProps) {
  const theme = useTheme();
  const [age, setAge] = useState<string>('');
  const [gender, setGender] = useState<string[]>([]);
  const [selectOpen, setSelectOpen] = useState<boolean>(false);
  const quiz = useCurrentQuiz();
  const { enqueueSnackbar } = useSnackbar();
  const isMobile = useMediaQuery(theme.breakpoints.down(845));
  const [ageError, setAgeError] = useState(false);

  const addItem = async () => {
    if (!quiz?.backendId) {
      enqueueSnackbar('Ошибка: не выбран квиз', { variant: 'error' });
      return;
    }

    try {
      const [result, error] = await auditoryAdd({
        quizId: quiz.backendId,
        body: {
          sex: gender.includes("male"),
          age
        }
      });

      if (error) {
        enqueueSnackbar('Не удалось добавить ссылку', { variant: 'error' });
        return;
      }

      if (result) {
        handleAdd({
          id: result.ID,
          quiz_id: quiz.backendId,
          sex: gender.includes("male"),
          age,
          deleted: false,
        });
        enqueueSnackbar('Ссылка успешно добавлена', { variant: 'success' });
        // Очищаем форму
        setGender([]);
        setAge('');
      }
    } catch (error) {
      enqueueSnackbar('Произошла ошибка при добавлении', { variant: 'error' });
    }
  };

  return (
    <Box sx={{ display: 'flex', gap: 4, alignItems: "end", flexWrap: "wrap" }}>
      <Box sx={{ display: "inline-flex", flexWrap: isMobile ? "wrap" : "initial" }}>

        <FormControl component="fieldset" variant="standard">
          <Box sx={{ display: 'flex', alignItems: "end", gap: '4px' }}>
            <FormLabel
              sx={{
                '&.Mui-focused': {
                  color: '#4D4D4D',
                },
                color: '#4D4D4D',
                fontSize: '18px',
                fontWeight: 500,
                lineHeight: 1,
                letterSpacing: 0,
                mr: '3px',
              }}
              component="legend">Пол</FormLabel>
            <InfoPopover />
          </Box>
          <FormGroup
            sx={{
              width: "155px",
              justifyContent: "space-between",
              mt: "20px",
              ml: "-9px"
            }}
            row
          >
            <FormControlLabel
              sx={{
                padding: 0,
                '& .MuiTouchRipple-root': {
                  width: '100%',
                  height: '100%',
                  overflow: 'visible',
                },
                '& .MuiSvgIcon-root': {
                  position: 'absolute',
                  left: '50%',
                  top: '50%',
                  transform: 'translate(-50%, -50%)',
                },
                '& .MuiFormControlLabel-label': {
                  fontSize: '18px',
                  fontWeight: 400,
                  fontFamily: 'Rubik',
                  lineHeight: 1,
                  letterSpacing: 0,
                  color: '#4D4D4D',
                  ml: "6px"
                },
                m: 0,
              }}
              control={
                <Checkbox 
                  checked={gender.includes('male')}
                  onChange={(e) => {
                    if (e.target.checked) {
                      setGender([...gender, 'male']);
                    } else {
                      setGender(gender.filter(g => g !== 'male'));
                    }
                  }}
                  icon={<CheckboxIcon />}
                  checkedIcon={<CheckboxIcon checked />}
                />
              }
              label="М"
            />
            <FormControlLabel
              sx={{
                padding: 0,
                '& .MuiTouchRipple-root': {
                  width: '100%',
                  height: '100%',
                  overflow: 'visible',
                },
                '& .MuiSvgIcon-root': {
                  position: 'absolute',
                  left: '50%',
                  top: '50%',
                  transform: 'translate(-50%, -50%)',
                },
                '& .MuiFormControlLabel-label': {
                  fontSize: '18px',
                  fontWeight: 400,
                  fontFamily: 'Rubik',
                  lineHeight: 1,
                  letterSpacing: 0,
                  color: '#4D4D4D',
                },
                m: 0,
              }}
              control={
                <Checkbox 
                  checked={gender.includes('female')}
                  onChange={(e) => {
                    if (e.target.checked) {
                      setGender([...gender, 'female']);
                    } else {
                      setGender(gender.filter(g => g !== 'female'));
                    }
                  }}
                  icon={<CheckboxIcon />}
                  checkedIcon={<CheckboxIcon checked />}
                />
              }
              label="Ж"
            />
          </FormGroup>
        </FormControl>

        <FormControl sx={{ maxWidth: "420px", width: "100%", marginLeft: isMobile ? "0" : "120px", minWidth: "265px" }} variant="filled">
          <Box sx={{
            display: 'flex',
            alignItems: 'end',
            gap: '4px'
          }}>
            <FormLabel sx={{
              color: '#4D4D4D',
              fontSize: "18px",
              fontWeight: 500,
              lineHeight: "100%",
              '&.Mui-focused': {
                color: '#4D4D4D',
              },
            }}>Возраст</FormLabel>
            <InfoPopover />
          </Box>
          <AgeInputWithSelect value={age} onChange={setAge} onErrorChange={setAgeError} />
        </FormControl>
      </Box>

      <Button
        onClick={addItem}
        variant="contained"
        disabled={gender.length === 0 || !age || ageError}
        sx={{
          bgcolor: theme.palette.brightPurple.main,
          borderRadius: "8px",
          width: "130px",
          height: "48px",
          boxShadow: "none",
          textTransform: "none",
          fontSize: "18px",
          '&:hover': { bgcolor: theme.palette.brightPurple.main },
        }}
      >
        Ок
      </Button>
    </Box >
  );
} 