
import { useState, useCallback } from 'react';

import Tooltip from '@mui/material/Tooltip';
import IconButton from '@mui/material/IconButton';
import { useColorScheme } from '@mui/material/styles';

import { CONFIG } from 'src/config-global';
import { Iconify } from 'src/components/iconify';
import { SvgColor, svgColorClasses } from 'src/components/svg-color';

import { useSettingsContext } from 'src/components/settings/context';

// ----------------------------------------------------------------------

function FullScreenButton() {
  const [fullscreen, setFullscreen] = useState(false);

  const onToggle = useCallback(() => {
    if (!document.fullscreenElement) {
      document.documentElement.requestFullscreen();
      setFullscreen(true);
    } else if (document.exitFullscreen) {
      document.exitFullscreen();
      setFullscreen(false);
    }
  }, []);

  return (
    <Tooltip title={fullscreen ? 'Выйти из полноэкранного режима' : 'Полный экран'}>
      <IconButton
        onClick={onToggle}
        sx={{
          p: 0,
          width: 40,
          height: 40,
          [`& .${svgColorClasses.root}`]: {
            background: (theme) =>
              `linear-gradient(135deg, ${theme.vars.palette.grey[500]} 0%, ${theme.vars.palette.grey[600]} 100%)`,
            ...(fullscreen && {
              background: (theme) =>
                `linear-gradient(135deg, ${theme.vars.palette.primary.light} 0%, ${theme.vars.palette.primary.main} 100%)`,
            }),
          },
        }}
      >
        <SvgColor
          src={`${CONFIG.site.basePath}/assets/icons/setting/${fullscreen ? 'ic-exit-full-screen' : 'ic-full-screen'}.svg`}
          sx={{ width: 18, height: 18 }}
        />
      </IconButton>
    </Tooltip>
  );
}

// ----------------------------------------------------------------------

export function SettingsButton({ sx, ...other }) {
  const settings = useSettingsContext();
  const { mode, setMode } = useColorScheme();

  const isDark = mode === 'dark' || settings.colorScheme === 'dark';

  const handleToggle = () => {
    const next = isDark ? 'light' : 'dark';
    settings.onUpdateField('colorScheme', next);
    setMode(next);
  };

  return (
    <>
      <FullScreenButton />
      <Tooltip title={isDark ? 'Светлая тема' : 'Тёмная тема'}>
        <IconButton
          onClick={handleToggle}
          sx={{ p: 0, width: 40, height: 40, ...sx }}
          {...other}
        >
          <Iconify
            icon={isDark ? 'solar:sun-bold-duotone' : 'solar:moon-bold-duotone'}
            width={22}
          />
        </IconButton>
      </Tooltip>
    </>
  );
}
