import React, { ReactElement } from 'react';

import { useAppDispatch, useAppSelector } from '../store/hooks';
import { isDev } from '../shared/utils';

import { cleanupAsync, isDesynced, updateWindowsAsync } from '../store/windowsSlice';
import { useLiveQuery } from 'dexie-react-hooks';
import { getBackupEveryNSeconds, getIsBackupOverdue, getLatestBackup, getTabvanaWindowId } from '../db/prefs';
import { requestBackupPermission, setBackupDir, maybeBackup } from '../db/backup';
import { faArrowsRotate, faBroom, faGear, faPlugCircleBolt } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { openOptionsPageInWindow } from '../chrome/chromeActions';
import IconButton from '@mui/joy/IconButton';
import { Button, CircularProgress, Tooltip } from '@mui/joy';

import { useActiveProgress, clearAllProgress, useCompletedProgress } from '../db/progress';
import { clearQueue } from '../db/queue';

const GlobalButtons = React.memo((): ReactElement => {
  const tabvanaWindowId = useLiveQuery(getTabvanaWindowId);
  const isBackupOverdue = useLiveQuery(getIsBackupOverdue);
  const { totalWork, completedWork, activeTasks, operations } = useActiveProgress();
  const completedProgressTasks = useCompletedProgress();

  const dispatch = useAppDispatch();
  const desynced = useAppSelector(isDesynced);
  const working = activeTasks > 0;

  const handleCancelTasks = async () => {
    await clearQueue();
    await clearAllProgress();
  };

  const tooltipContent = (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', minWidth: '200px' }}>
      {operations.length > 0 ? (
        <>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span><strong>Total: {completedWork} / {totalWork}</strong></span>
          </div>
          {Object.entries(
            operations.reduce((acc, op) => {
              if (!acc[op.type]) acc[op.type] = { current: 0, total: 0 };
              acc[op.type].current += op.current;
              acc[op.type].total += op.total;
              return acc;
            }, {} as Record<string, { current: number; total: number }>)
          ).map(([type, stats]) => {
            const label = type === 'generateEmbedding' 
              ? 'Generating embeddings' 
              : type === 'backup' 
                ? 'Backup in progress' 
                : type === 'renormalize'
                  ? 'Renormalizing database'
                  : type === 'similarity'
                    ? 'Calculating similarities'
                    : type.charAt(0).toUpperCase() + type.slice(1);
            
            return (
              <div key={type}>
                {label}: {stats.current} / {stats.total}
              </div>
            );
          })}
          <Button size="sm" color="danger" variant="soft" onClick={handleCancelTasks} sx={{ mt: 1 }} fullWidth>
            Cancel Tasks
          </Button>
        </>
      ) : (
        <div>No active background tasks</div>
      )}
      {completedProgressTasks.length > 0 && (
        <>
          <div style={{ borderTop: '1px solid var(--joy-palette-divider)', marginTop: '8px', paddingTop: '8px', fontSize: '0.85em', color: 'var(--joy-palette-text-tertiary)' }}>
            <strong>Completed Tasks ({completedProgressTasks.length})</strong>
          </div>
          {completedProgressTasks.map((op, i) => {
            const label = op.type === 'generateEmbedding' 
              ? 'Generated embeddings' 
              : op.type === 'backup' 
                ? 'Backup completed' 
                : op.type === 'renormalize'
                  ? 'Renormalized database'
                  : op.type === 'similarity'
                    ? 'Calculated similarities'
                    : op.type.charAt(0).toUpperCase() + op.type.slice(1) + ' completed';
            return (
              <div key={op.id || i} style={{ fontSize: '0.85em', color: 'var(--joy-palette-text-tertiary)' }}>
                {label} ({op.total})
              </div>
            );
          })}
        </>
      )}
    </div>
  );

  return (
    <div
      style={{
        position: 'absolute',
        top: '2px',
        right: '10px',
        zIndex: '999',
      }}
    >
      <Tooltip title={tooltipContent} placement="bottom" sx={{ zIndex: 99999 }}>
        <CircularProgress
          size="sm"
          determinate={activeTasks === 0 || totalWork > 0}
          value={activeTasks === 0 ? 0 : (totalWork > 0 ? (completedWork / totalWork) * 100 : undefined)}
          color={activeTasks > 0 ? 'primary' : 'neutral'}
          sx={{
            verticalAlign: 'middle',
            margin: '0.2rem',
            ...(activeTasks > 0 && {
              animation: 'pulse 1.5s ease-in-out infinite',
              '@keyframes pulse': {
                '0%': { opacity: 0.6 },
                '50%': { opacity: 1 },
                '100%': { opacity: 0.6 },
              },
            }),
          }}
        >
          {/* totalWork > 0 && <span style={{fontSize: '0.6rem'}}>{Math.round((completedWork / totalWork) * 100)}%</span> */}
        </CircularProgress>
      </Tooltip>
      {isBackupOverdue && (
        <Button
          color="danger"
          onClick={async () => {
            if (await requestBackupPermission()) {
              await maybeBackup(true);
              return;
            }
            await setBackupDir();
            await maybeBackup(true);
          }}
        >
          Set Backup Dir
        </Button>
      )}
      {desynced && (
        <Tooltip title="Force Update" placement="bottom">
          <Button
            size="sm"
            variant="soft"
            onClick={() => dispatch(updateWindowsAsync())}
            title="Force Update"
            color="danger"
          >
            <FontAwesomeIcon icon={faArrowsRotate} />
          </Button>
        </Tooltip>
      )}
      {isDev && (
        <Tooltip title="Reload Extension (Dev)" placement="bottom">
          <IconButton onClick={() => chrome.runtime.reload()} title="Reload Extension">
            <FontAwesomeIcon icon={faPlugCircleBolt} />
          </IconButton>
        </Tooltip>
      )}
      <Tooltip title="Clean Up: Stash untagged, Snooze all." placement="bottom">
        <IconButton>
          <FontAwesomeIcon
            icon={faBroom}
            onClick={() => {
              dispatch(cleanupAsync(tabvanaWindowId));
            }}
            title="Clean Up"
          />
        </IconButton>
      </Tooltip>

      <Tooltip title="Settings" placement="bottom">
        <IconButton>
          <FontAwesomeIcon
            icon={faGear}
            onClick={() => openOptionsPageInWindow()}
            title="Settings"
          />
        </IconButton>
      </Tooltip>
    </div>
  );
});

export default GlobalButtons;
