'use client';

import { Alert, Snackbar, Box, Typography, CircularProgress } from '@mui/material';
import { CloudOff, CloudQueue, CloudDone, Wifi, WifiOff } from '@mui/icons-material';
import { useIsOnline, useSyncStatus } from '@/store/hooks';

export const NetworkStatusIndicator: React.FC = () => {
  const isOnline = useIsOnline();
  const { syncing, pendingCount } = useSyncStatus();

  // Show nothing if online and no pending sync
  if (isOnline && !syncing && pendingCount === 0) {
    return null;
  }

  return (
    <Snackbar
      open={true}
      anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      sx={{ top: 80 }}
    >
      <Alert
        severity={isOnline ? (syncing ? 'info' : 'warning') : 'error'}
        icon={
          syncing ? (
            <CircularProgress size={20} />
          ) : isOnline ? (
            <CloudQueue />
          ) : (
            <WifiOff />
          )
        }
        sx={{
          width: '100%',
          maxWidth: 400,
          borderRadius: 2,
        }}
      >
        <Box>
          <Typography variant="body2" fontWeight="600">
            {!isOnline && 'You are offline'}
            {isOnline && syncing && 'Syncing changes...'}
            {isOnline && !syncing && pendingCount > 0 && `${pendingCount} changes pending`}
          </Typography>
          <Typography variant="caption">
            {!isOnline && 'Your changes will be saved and synced when you reconnect'}
            {isOnline && syncing && 'Please wait while we sync your data'}
            {isOnline && !syncing && pendingCount > 0 && 'Waiting to sync'}
          </Typography>
        </Box>
      </Alert>
    </Snackbar>
  );
};

/**
 * Small status badge for the app bar
 */
export const NetworkStatusBadge: React.FC = () => {
  const isOnline = useIsOnline();
  const { syncing, pendingCount } = useSyncStatus();

  if (isOnline && !syncing && pendingCount === 0) {
    return null;
  }

  return (
    <Box
      sx={{
        display: 'flex',
        alignItems: 'center',
        gap: 0.5,
        px: 1.5,
        py: 0.5,
        borderRadius: 2,
        bgcolor: isOnline ? 'warning.light' : 'error.light',
        color: isOnline ? 'warning.dark' : 'error.dark',
      }}
    >
      {syncing ? (
        <CircularProgress size={14} />
      ) : isOnline ? (
        <CloudQueue sx={{ fontSize: 16 }} />
      ) : (
        <WifiOff sx={{ fontSize: 16 }} />
      )}
      <Typography variant="caption" fontWeight="600">
        {!isOnline && 'Offline'}
        {isOnline && syncing && 'Syncing'}
        {isOnline && !syncing && pendingCount > 0 && pendingCount}
      </Typography>
    </Box>
  );
};
