import { Box, Chip, Tooltip, Typography, CircularProgress } from '@mui/material'
import { CheckCircle, Error, Warning, CloudOff, Info } from '@mui/icons-material'
import { useProviderStatus } from '../hooks/useProviderStatus'
import StatusIndicator from './StatusIndicator'

interface ProviderStatusProps {
  compact?: boolean
  showDetails?: boolean
}

export default function ProviderStatusDisplay({ compact = false, showDetails = false }: ProviderStatusProps) {
  const { status, isLoading, error } = useProviderStatus()

  if (isLoading) {
    return compact ? (
      <CircularProgress size={16} />
    ) : (
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <CircularProgress size={20} />
        <Typography variant="body2">Loading provider status...</Typography>
      </Box>
    )
  }

  if (error) {
    return (
      <Chip
        icon={<Error />}
        label="Provider status unavailable"
        color="error"
        size="small"
        variant="outlined"
      />
    )
  }

  if (!status) {
    return null
  }

  const activeProvider = status.active_provider
  const providerHealth = activeProvider ? status.providers[activeProvider] : null

  if (compact) {
    return (
      <Tooltip
        title={
          activeProvider
            ? `Active: ${activeProvider}${providerHealth ? ` (${providerHealth.status})` : ''}`
            : 'No active provider'
        }
      >
        <Box>
          {providerHealth ? (
            <StatusIndicator
              status={
                providerHealth.status === 'healthy'
                  ? 'connected'
                  : providerHealth.status === 'degraded'
                  ? 'warning'
                  : 'error'
              }
              label={activeProvider || 'None'}
            />
          ) : (
            <Chip label={activeProvider || 'None'} size="small" color="default" variant="outlined" />
          )}
        </Box>
      </Tooltip>
    )
  }

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
        <Typography variant="subtitle2">Data Providers</Typography>
        {activeProvider && (
          <Chip
            label={`Active: ${activeProvider}`}
            color={providerHealth?.status === 'healthy' ? 'success' : 'default'}
            size="small"
          />
        )}
      </Box>

      {showDetails && (
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
          {Object.entries(status.providers).map(([name, health]) => (
            <Box
              key={name}
              sx={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                p: 1,
                border: '1px solid',
                borderColor: 'divider',
                borderRadius: 1,
              }}
            >
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <StatusIndicator
                  status={
                    health.status === 'healthy'
                      ? 'connected'
                      : health.status === 'degraded'
                      ? 'warning'
                      : 'error'
                  }
                  label={name}
                />
                {name === activeProvider && (
                  <Chip label="Active" size="small" color="primary" variant="outlined" />
                )}
              </Box>
              <Box sx={{ display: 'flex', gap: 2, alignItems: 'center' }}>
                {health.avg_response_time > 0 && (
                  <Typography variant="caption" color="text.secondary">
                    {health.avg_response_time.toFixed(3)}s avg
                  </Typography>
                )}
                <Typography variant="caption" color="text.secondary">
                  {health.success_count} success, {health.failure_count} failures
                </Typography>
              </Box>
            </Box>
          ))}
        </Box>
      )}
    </Box>
  )
}
