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

const BOARD_TYPES = [
  { value: 'vesper_pro',  name: 'VESPER PRO',   codename: 'vesper-pro',    desc: 'Full-featured pro controller',  family: 'vesper'  },
  { value: 'vesper_plus', name: 'VESPER PLUS',  codename: 'vesper-plus',   desc: 'Extended output controller',    family: 'vesper'  },
  { value: 'vesper',      name: 'VESPER',       codename: 'vesper-basic',  desc: 'Standard bell controller',      family: 'vesper'  },
  { value: 'agnus',       name: 'AGNUS',        codename: 'agnus-basic',   desc: 'Standard carillon module',      family: 'agnus'   },
  { value: 'agnus_mini',  name: 'AGNUS MINI',   codename: 'agnus-mini',    desc: 'Compact carillon module',       family: 'agnus'   },
  { value: 'chronos_pro', name: 'CHRONOS PRO',  codename: 'chronos-pro',   desc: 'Pro clock controller',          family: 'chronos' },
  { value: 'chronos',     name: 'CHRONOS',      codename: 'chronos-basic', desc: 'Basic clock controller',        family: 'chronos' },
]

// Family accent tokens (used only as CSS vars via inline style — not raw hex)
const FAMILY_ACCENT = {
  vesper:  { color: 'var(--color-info)',    bg: 'var(--color-info-bg)',    border: 'rgba(123,208,255,0.35)'  },
  agnus:   { color: 'var(--color-warning)', bg: 'var(--color-warning-bg)', border: 'rgba(251,191,36,0.35)'   },
  chronos: { color: 'var(--color-danger)',  bg: 'var(--color-danger-bg)',  border: 'rgba(255,92,92,0.35)'    },
}

function BoardTile({ bt, isSelected, onClick }) {
  const pal = FAMILY_ACCENT[bt.family]
  const [hovered, setHovered] = useState(false)
  const active = isSelected || hovered
  return (
    <button
      type="button"
      onClick={onClick}
      aria-pressed={isSelected}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        backgroundColor: isSelected ? pal.bg : hovered ? 'var(--color-bg-surface)' : 'var(--color-bg-abyss)',
        border: `1px solid ${active ? pal.color : 'var(--color-border-strong)'}`,
        borderRadius: 'var(--radius-md)',
        padding: 'var(--space-3)',
        textAlign: 'left',
        cursor: 'pointer',
        transition: 'border-color 0.15s, background-color 0.15s, box-shadow 0.15s',
        boxShadow: active ? `0 0 0 1px ${pal.border}, 0 0 14px ${pal.border}` : 'none',
        width: '100%',
      }}
    >
      <p style={{
        fontSize: 'var(--font-size-xs)',
        fontWeight: 'var(--font-weight-bold)',
        letterSpacing: 'var(--tracking-wide)',
        color: active ? pal.color : 'var(--color-text-primary)',
        marginBottom: 'var(--space-1)',
        fontFamily: 'var(--font-family-display)',
      }}>{bt.name}</p>
      <p style={{ fontSize: 'var(--font-size-xs)', fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-muted)', opacity: 0.75 }}>{bt.codename}</p>
    </button>
  )
}

export default function NewBatchModal({ open, onClose, onCreated }) {
  const [boardType, setBoardType]     = useState(null)
  const [boardVersion, setBoardVersion] = useState('1.0')
  const [quantity, setQuantity]       = useState(1)
  const [saving, setSaving]           = useState(false)
  const [error, setError]             = useState('')
  const [result, setResult]           = useState(null)
  const [copied, setCopied]           = useState(false)

  const handleClose = () => {
    setResult(null); setError(''); setBoardType(null); setBoardVersion('1.0'); setQuantity(1)
    onClose()
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    if (!boardType) return
    setError(''); setSaving(true)
    try {
      const data = await api.post('/manufacturing/batch', {
        board_type: boardType,
        board_version: boardVersion.trim(),
        quantity: Number(quantity),
      })
      setResult(data)
      if (onCreated) onCreated(data)
    } catch (err) {
      setError(err.message)
    } finally {
      setSaving(false)
    }
  }

  const copyAll = () => {
    if (!result) return
    navigator.clipboard.writeText(result.serial_numbers.join('\n'))
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  const boardName = BOARD_TYPES.find((b) => b.value === result?.board_type)?.name || result?.board_type

  return (
    <Modal
      open={open}
      onClose={handleClose}
      title={result ? 'Batch Created' : 'New Batch'}
      size="md"
      footer={
        result ? (
          <div style={{ display: 'flex', gap: 'var(--space-3)' }}>
            <Button variant="secondary" onClick={copyAll}>
              {copied ? 'Copied!' : 'Copy All Serials'}
            </Button>
            <Button variant="primary" onClick={handleClose}>Done</Button>
          </div>
        ) : (
          <div style={{ display: 'flex', gap: 'var(--space-3)' }}>
            <Button variant="ghost" onClick={handleClose}>Cancel</Button>
            <Button
              variant="primary"
              type="submit"
              form="new-batch-form"
              loading={saving}
              disabled={!boardType}
            >
              Generate {quantity} Serial{Number(quantity) > 1 ? 's' : ''}
            </Button>
          </div>
        )
      }
    >
      {!result ? (
        <form id="new-batch-form" onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
          {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>
            <p style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-secondary)', marginBottom: 'var(--space-3)', letterSpacing: 'var(--tracking-wide)', textTransform: 'uppercase' }}>
              Board Type
            </p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
              {[
                { family: 'vesper',  label: 'Vesper Family'  },
                { family: 'agnus',   label: 'Agnus Family'   },
                { family: 'chronos', label: 'Chronos Family' },
              ].map(({ family, label }) => (
                <div key={family}>
                  <p style={{
                    fontSize: 'var(--font-size-xs)',
                    fontWeight: 'var(--font-weight-semibold)',
                    color: FAMILY_ACCENT[family].color,
                    letterSpacing: 'var(--tracking-wide)',
                    textTransform: 'uppercase',
                    marginBottom: 'var(--space-2)',
                  }}>{label}</p>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 'var(--space-2)' }}>
                    {BOARD_TYPES.filter((b) => b.family === family).map((bt) => (
                      <BoardTile key={bt.value} bt={bt} isSelected={boardType === bt.value} onClick={() => setBoardType(bt.value)} />
                    ))}
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div style={{ display: 'flex', gap: 'var(--space-3)', paddingTop: 'var(--space-2)' }}>
            <div style={{ width: '120px' }}>
              <FormField label="Board Revision" name="board_version" type="text" value={boardVersion}
                onChange={(e) => setBoardVersion(e.target.value)}
                hint="e.g. 1.0, 2.1" required />
            </div>
            <div style={{ width: '120px' }}>
              <FormField label="Quantity" name="quantity" type="number" value={quantity}
                onChange={(e) => setQuantity(e.target.value)}
                min={1} max={100} required />
            </div>
          </div>

        </form>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <p style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)', marginBottom: 'var(--space-1)' }}>
                {result.serial_numbers.length} device{result.serial_numbers.length !== 1 ? 's' : ''} registered
              </p>
              <p style={{ fontSize: 'var(--font-size-xs)', fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-muted)' }}>
                Batch: {result.batch_id}
              </p>
            </div>
            <StatusBadge variant="info">{boardName} Rev {result.board_version}</StatusBadge>
          </div>

          <div style={{
            backgroundColor: 'var(--color-bg-abyss)',
            border: '1px solid var(--color-border)',
            borderRadius: 'var(--radius-md)',
            padding: 'var(--space-3)',
            maxHeight: '240px',
            overflowY: 'auto',
          }}>
            {result.serial_numbers.map((sn) => (
              <div key={sn} style={{
                fontFamily: 'var(--font-family-mono)',
                fontSize: 'var(--font-size-sm)',
                color: 'var(--color-text-primary)',
                padding: '2px 0',
              }}>{sn}</div>
            ))}
          </div>
        </div>
      )}
    </Modal>
  )
}
