import { Box, FormControl, FormLabel, RadioGroup, FormControlLabel, Radio, Select, MenuItem, useTheme, Button } 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";

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 quiz = useCurrentQuiz();
  const { enqueueSnackbar } = useSnackbar();

  const isFormValid = gender && age;

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

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

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

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

  return (
    <Box sx={{ display: 'flex', gap: 4, alignItems: "center" }}>
      <Box>

        <FormControl component="fieldset" variant="standard">
          <Box sx={{ display: 'flex', alignItems: "center", 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>
          <RadioGroup
            sx={{
              width: "155px",
              justifyContent: "space-between",
              mt: "9px",
              ml: "-9px"
            }}
            row
            aria-label="gender"
            name="row-radio-buttons-group"
            value={gender}
            onChange={(e) => setGender(e.target.value)}
          >
            <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,
              }}
              value="male"
              control={<Radio 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,
              }}
              value="female"
              control={<Radio icon={<CheckboxIcon />} checkedIcon={<CheckboxIcon checked />} />}
              label="Ж"
            />
          </RadioGroup>
        </FormControl>

        <FormControl sx={{ minWidth: "420px", marginLeft: "15px" }} variant="filled">
          <Box sx={{
            display: 'flex',
            alignItems: 'center',
            gap: '4px'
          }}>
            <FormLabel sx={{
              color: '#4D4D4D',
              fontSize: "18px",
              fontWeight: 500,
              lineHeight: "100%",
              '&.Mui-focused': {
                color: '#4D4D4D',
              },
            }}>Возраст</FormLabel>
            <InfoPopover />
          </Box>
          <Select
            value={age}
            onChange={(e) => setAge(e.target.value)}
            displayEmpty
            inputProps={{ 'aria-label': 'age', disableUnderline: true }}
            disableUnderline
            sx={{
              height: "48px",
              maxWidth: "420px",
              borderRadius: "8px",
              border: "1px solid #9A9AAF",
              '& .MuiSelect-filled': {
                height: "100%",
                width: "100%",
              },
              '& .MuiSelect-select': {
                height: "100%",
                width: "100%",
                p: "10px 20px"
              },
              '& .MuiOutlinedInput-notchedOutline': {
                borderColor: '#E0E0E0',
              },
              '&:hover .MuiOutlinedInput-notchedOutline': {
                borderColor: '#B0B0B0',
              },
              '&.Mui-focused .MuiOutlinedInput-notchedOutline': {
                borderColor: '#7E2AEA',
              },
              mt: "17px",
            }}
          >
            <MenuItem value="">Выберите возраст</MenuItem>
            <MenuItem value="18-24">18-24</MenuItem>
            <MenuItem value="25-34">25-34</MenuItem>
            <MenuItem value="35-44">35-44</MenuItem>
            <MenuItem value="45-54">45-54</MenuItem>
            <MenuItem value="55+">55+</MenuItem>
          </Select>
        </FormControl>
      </Box>

      <Button
      onClick={addItem}
        variant="contained"
        disabled={!isFormValid}
        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>
  );
} 