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

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

  if (status !== 'done' || tracks.length === 0) {
    return null
  }

  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 }}>
      <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>
  )
}