import { Button, ClickAwayListener, Tooltip, useTheme } from "@mui/material";
import { useState } from "react";

interface CreateButtonWithTooltipProps {
  gender: string;
  age: string;
  ageError: boolean;
  onClick: () => void;
}

export default function CreateButtonWithTooltip({ 
  gender, 
  age, 
  ageError, 
  onClick 
}: CreateButtonWithTooltipProps) {
  const theme = useTheme();
  const [open, setOpen] = useState(false);

  const handleTooltipClose = () => {
    setOpen(false);
  };

  const handleTooltipOpen = () => {
    setOpen(true);
  };

  // Определяем причины неактивности кнопки
  const getDisabledReasons = () => {
    const reasons: string[] = [];
    
    if (!gender) {
      reasons.push("выберите пол");
    }
    
    if (!age) {
      reasons.push("заполните поле возраста");
    }
    
    if (ageError) {
      reasons.push("исправьте ошибку в поле возраста");
    }
    
    return reasons;
  };

  const disabledReasons = getDisabledReasons();
  const isDisabled = !gender || !age || ageError;
  const tooltipText = isDisabled 
    ? disabledReasons.length === 2 
      ? disabledReasons.join(' и ')
      : disabledReasons.join('\n')
    : '';

  return (
    <ClickAwayListener onClickAway={handleTooltipClose}>
      <div style={{ position: 'relative' }}>
        {isDisabled && (
          <div
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              zIndex: 1,
              cursor: 'help'
            }}
            onMouseEnter={handleTooltipOpen}
            onMouseLeave={handleTooltipClose}
            onClick={handleTooltipOpen}
          />
        )}
        <Tooltip
          PopperProps={{
            disablePortal: true,
            sx: {
              "& .MuiTooltip-tooltip": {
                fontSize: "14px",
                padding: "12px",
                maxWidth: "400px",
                whiteSpace: "pre-line"
              }
            }
          }}
          placement="top"
          onClose={handleTooltipClose}
          open={open}
          title={tooltipText}
        >
          <Button
            onClick={onClick}
            variant="contained"
            disabled={isDisabled}
            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>
        </Tooltip>
      </div>
    </ClickAwayListener>
  );
} 