import React from 'react'
import { Paper, Typography, Button, List, ListItem, ListItemText, IconButton, Divider } from '@mui/material'
import { Download, FolderZip } from '@mui/icons-material'
import { useTaskStore } from '../stores/taskStore'
import { getDownloadZipUrl } from '../api/client'
import { formatFileSize } from '../utils/formatters'

export const DownloadSection: React.FC = () => {
  const { taskId, tracks, status } = useTaskStore()

  console.log('[DownloadSection] Rendering:', { status, tracks, taskId })

  // Check if we should show the download section
  if (status !== 'done' || !tracks || tracks.length === 0 || !taskId) {
    return null
  }

  // If we get here, we have tracks
  console.log('[DownloadSection] Showing tracks:', tracks)

  const handleDownloadZip = () => {
    const url = getDownloadZipUrl(taskId)
    window.open(url, '_blank')
  }

  const handleDownloadTrack = (filename: string) => {
    const url = `/api/download/${taskId}/${filename}`
    window.open(url, '_blank')
  }

  return (
    <Paper sx={{ p: 3, mt: 3 }}>
      <Typography variant="h6" sx={{ mb: 2 }}>
        📥 Download Results
      </Typography>

      <Button
        variant="contained"
        color="primary"
        startIcon={<FolderZip />}
        onClick={handleDownloadZip}
        sx={{ mb: 2 }}
        fullWidth
      >
        Download All as ZIP
      </Button>

      <Divider sx={{ my: 2 }} />

      <Typography variant="subtitle2" sx={{ mb: 1 }}>
        Individual Tracks
      </Typography>

      <List dense>
        {tracks.map((track, index) => (
          <ListItem
            key={index}
            secondaryAction={
              <IconButton edge="end" onClick={() => handleDownloadTrack(track.filename)} size="small">
                <Download />
              </IconButton>
            }
          >
            <ListItemText
              primary={track.filename}
              secondary={formatFileSize(track.size)}
            />
          </ListItem>
        ))}
      </List>
    </Paper>
  )
}
