import React, { useEffect, useRef } from 'react'
import { Box, Paper, Typography, LinearProgress, Alert, Chip } from '@mui/material'
import { useTaskStore } from '../stores/taskStore'

export const ProgressDisplay: React.FC = () => {
  const { status, progress, message, error, tracks, logs } = useTaskStore()
  const logContainerRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (logContainerRef.current) {
      logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight
    }
  }, [logs])

  if (!status) {
    return null
  }

  const getStatusColor = () => {
    switch (status) {
      case 'pending':
        return 'info'
      case 'processing':
        return 'warning'
      case 'done':
        return 'success'
      case 'error':
        return 'error'
      default:
        return 'default'
    }
  }

  const getStatusLabel = () => {
    switch (status) {
      case 'pending':
        return 'Waiting'
      case 'processing':
        return 'Processing'
      case 'done':
        return 'Complete'
      case 'error':
        return 'Error'
      default:
        return 'Unknown'
    }
  }

  return (
    <Paper sx={{ p: 3 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Typography variant="h6">📊 Progress</Typography>
        <Chip label={getStatusLabel()} color={getStatusColor()} size="small" />
      </Box>

      <Box sx={{ mb: 2 }}>
        <LinearProgress
          variant="determinate"
          value={progress}
          color={status === 'error' ? 'error' : status === 'done' ? 'success' : 'primary'}
          sx={{ height: 10, borderRadius: 5 }}
        />
        <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
          {progress}% – {message}
        </Typography>
      </Box>

      {error && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
      )}

      {tracks.length > 0 && status === 'done' && (
        <Alert severity="success" sx={{ mb: 2 }}>
          ✅ {tracks.length} track(s) extracted successfully!
        </Alert>
      )}

      <Box
        ref={logContainerRef}
        sx={{
          maxHeight: 200,
          overflowY: 'auto',
          bgcolor: 'background.default',
          p: 2,
          borderRadius: 1,
          fontFamily: 'monospace',
          fontSize: '12px',
          lineHeight: 1.6,
        }}
      >
        {logs.length === 0 ? (
          <Typography variant="caption" color="text.secondary">
            Waiting for progress updates...
          </Typography>
        ) : (
          logs.map((log, index) => (
            <div key={index} style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
              {log}
            </div>
          ))
        )}
      </Box>
    </Paper>
  )
}