// frontend/src/modals/manufacturing/DeleteUnprovisionedModal.jsx
import { useState } from 'react'
import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import api from '@/lib/api'

const UNPROVISIONED_STATUSES = ['manufactured', 'flashed']

export default function DeleteUnprovisionedModal({ open, devices = [], onClose, onDeleted }) {
  const [deleting, setDeleting] = useState(false)
  const [error, setError]       = useState('')

  const targets = devices.filter((d) => UNPROVISIONED_STATUSES.includes(d.mfg_status))

  const handleClose = () => { setError(''); onClose() }

  const handleDelete = async () => {
    setDeleting(true); setError('')
    try {
      await Promise.all(
        targets.map((d) =>
          api.request(`/manufacturing/devices/${d.serial_number}`, { method: 'DELETE' })
        )
      )
      onDeleted()
      handleClose()
    } catch (err) {
      setError(err.message)
      setDeleting(false)
    }
  }

  return (
    <Modal
      open={open}
      onClose={handleClose}
      title="Delete Unprovisioned Devices"
      size="sm"
      footer={
        <div style={{ display: 'flex', gap: 'var(--space-3)' }}>
          <Button variant="ghost" onClick={handleClose}>Cancel</Button>
          <Button
            variant="danger"
            onClick={handleDelete}
            loading={deleting}
            disabled={targets.length === 0}
          >
            Delete {targets.length} Device{targets.length !== 1 ? 's' : ''}
          </Button>
        </div>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
        {targets.length === 0 ? (
          <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)' }}>
            No unprovisioned devices found. Only devices with status <strong>manufactured</strong> or <strong>flashed</strong> can be bulk-deleted.
          </p>
        ) : (
          <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)' }}>
            This will permanently delete <strong>{targets.length} device{targets.length !== 1 ? 's' : ''}</strong> with
            status <strong>manufactured</strong> or <strong>flashed</strong>. Provisioned, sold, and claimed devices are not affected.
            This cannot be undone.
          </p>
        )}

        {error && (
          <div style={{ padding: 'var(--space-3)', borderRadius: 'var(--radius-md)', backgroundColor: 'var(--color-danger-bg)', border: '1px solid var(--color-danger)', color: 'var(--color-danger)', fontSize: 'var(--font-size-sm)' }}>
            {error}
          </div>
        )}
      </div>
    </Modal>
  )
}
