/**
 * OfflineToggle Component
 *
 * Button to toggle offline mode for a project.
 * Shows download status, size estimate, and provides download/delete actions.
 */

import React from 'react';
import {
  mdiCloudDownload,
  mdiCloudCheck,
  mdiCloudOff,
  mdiDelete,
} from '@mdi/js';
import Icon from '@mdi/react';
import BaseButton from '../BaseButton';
import { useOfflineMode } from '../../hooks/useOfflineMode';
import { useStorageQuota } from '../../hooks/useStorageQuota';

interface OfflineToggleProps {
  projectId: string | null;
  projectSlug?: string;
  projectName?: string;
  className?: string;
  showLabel?: boolean;
  size?: 'small' | 'medium' | 'large';
}

export function OfflineToggle({
  projectId,
  projectSlug,
  projectName,
  className = '',
  showLabel = true,
  size = 'medium',
}: OfflineToggleProps) {
  const {
    isOfflineCapable,
    isDownloaded,
    isDownloading,
    status,
    progress,
    startDownload,
    pauseDownload,
    resumeDownload,
    cancelDownload,
    deleteOfflineData,
    estimatedSize,
    formatSize,
  } = useOfflineMode({
    projectId,
    projectSlug,
    projectName,
  });

  const { canStore, isWarning, isCritical } = useStorageQuota();

  // Don't render if offline not supported
  if (!isOfflineCapable) {
    return null;
  }

  const handleClick = () => {
    if (isDownloaded) {
      // Show confirmation before deleting
      if (confirm('Remove offline data for this project?')) {
        deleteOfflineData();
      }
    } else if (isDownloading) {
      pauseDownload();
    } else if (status === 'error') {
      resumeDownload();
    } else {
      // Check storage before starting
      if (isCritical) {
        alert(
          'Storage space is critically low. Please free up some space first.',
        );
        return;
      }
      if (isWarning && estimatedSize > 0) {
        if (
          !confirm(
            `Storage space is running low. Download ${formatSize(estimatedSize)} anyway?`,
          )
        ) {
          return;
        }
      }
      startDownload();
    }
  };

  // Determine icon and label
  let icon = mdiCloudDownload;
  let label = 'Download for offline';
  let color: 'info' | 'success' | 'danger' | 'warning' | 'lightDark' = 'info';

  if (isDownloaded) {
    icon = mdiCloudCheck;
    label = 'Available offline';
    color = 'success';
  } else if (isDownloading) {
    icon = mdiCloudDownload;
    label = `Downloading ${progress}%`;
    color = 'info';
  } else if (status === 'error') {
    icon = mdiCloudOff;
    label = 'Retry download';
    color = 'danger';
  } else if (status === 'outdated') {
    icon = mdiCloudDownload;
    label = 'Update available';
    color = 'warning';
  }

  const sizeLabel =
    estimatedSize > 0 && !isDownloaded && !isDownloading
      ? ` (${formatSize(estimatedSize)})`
      : '';

  return (
    <div className={`flex items-center gap-2 ${className}`}>
      <BaseButton
        small={size === 'small'}
        color={color}
        icon={icon}
        label={showLabel ? `${label}${sizeLabel}` : undefined}
        onClick={handleClick}
        disabled={!canStore(estimatedSize) && !isDownloaded}
      />
      {isDownloaded && (
        <button
          onClick={() => {
            if (confirm('Remove offline data for this project?')) {
              deleteOfflineData();
            }
          }}
          className='p-1 text-gray-400 hover:text-red-500 transition-colors'
          title='Remove offline data'
        >
          <Icon path={mdiDelete} size={0.7} />
        </button>
      )}
    </div>
  );
}

export default OfflineToggle;
