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

const TIMING_OPTIONS = [80, 85, 90, 95, 100, 110, 120, 140]
const TIMING_LABELS = {
  80: 'Min — 80ms',
  85: 'Size 1 — 85ms',
  90: 'Size 2 — 90ms',
  95: 'Size 3 — 95ms',
  100: 'Size 4 — 100ms',
  110: 'Size 5 — 110ms',
  120: 'Size 6 — 120ms',
  140: 'Max — 140ms',
}

export default function EditBellOutputsModal({ open, onClose, onSaved, attr, sub, id }) {
  const maxOutputs = sub?.maxOutputs || 8
  const existingCount = attr?.totalBells || 0
  const existingOutputs = attr?.bellOutputs || []
  const existingTimings = attr?.hammerTimings || []

  const [activeBells, setActiveBells] = useState(existingCount)
  const [rows, setRows] = useState(() =>
    Array.from({ length: maxOutputs }, (_, i) => ({
      output: existingOutputs[i] ?? 0,
      timing: existingTimings[i] ?? 90,
    }))
  )
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')

  const updateRow = (i, field, val) => {
    setRows((prev) => prev.map((r, idx) => idx === i ? { ...r, [field]: Number(val) } : r))
  }

  const activeRows = rows.slice(0, activeBells)

  const handleSave = async () => {
    setSaving(true)
    setError('')
    try {
      await api.put(`/devices/${id}`, {
        device_attributes: {
          totalBells: activeBells,
          bellOutputs: activeRows.map((r) => r.output),
          hammerTimings: activeRows.map((r) => r.timing),
        },
      })
      await onSaved()
      onClose()
    } catch (err) {
      setError(err.message || 'Failed to save.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Edit Bell Outputs"
      size="lg"
      footer={
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button variant="primary" loading={saving} onClick={handleSave}>Sync & Save Settings</Button>
        </div>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
        <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
          Select how many bells are active (1–{maxOutputs}), then assign each an output and hammer timing.
        </p>

        {/* Bell count selector */}
        <div>
          <p style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-secondary)', marginBottom: 'var(--space-2)' }}>
            Active Bells: <strong style={{ color: 'var(--color-text-primary)' }}>{activeBells}</strong>
          </p>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--space-2)' }}>
            {Array.from({ length: maxOutputs }, (_, i) => {
              const n = i + 1
              const isActive = n <= activeBells
              return (
                <button
                  key={n}
                  type="button"
                  onClick={() => setActiveBells(n === activeBells ? 0 : n)}
                  style={{
                    width: '40px',
                    height: '40px',
                    borderRadius: 'var(--radius-md)',
                    border: `1px solid ${isActive ? 'var(--color-primary)' : 'var(--color-border-strong)'}`,
                    backgroundColor: isActive ? 'var(--color-primary-subtle)' : 'var(--color-bg-elevated)',
                    color: isActive ? 'var(--color-primary)' : 'var(--color-text-muted)',
                    fontWeight: isActive ? 'var(--font-weight-semibold)' : 'var(--font-weight-normal)',
                    fontSize: 'var(--font-size-sm)',
                    cursor: 'pointer',
                    transition: 'all 0.15s',
                  }}
                >
                  {n}
                </button>
              )
            })}
          </div>
        </div>

        {/* Per-bell rows */}
        {activeBells > 0 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
            <div
              style={{
                display: 'grid',
                gridTemplateColumns: '56px 1fr 1fr',
                gap: 'var(--space-2)',
                fontSize: 'var(--font-size-sm)',
                color: 'var(--color-text-muted)',
                fontWeight: 'var(--font-weight-semibold)',
                textTransform: 'uppercase',
                letterSpacing: 'var(--tracking-wide)',
                paddingBottom: 'var(--space-1)',
                borderBottom: '1px solid var(--color-border)',
              }}
            >
              <span>Bell</span>
              <span>Output</span>
              <span>Timing</span>
            </div>
            {activeRows.map((row, i) => (
              <div
                key={i}
                style={{ display: 'grid', gridTemplateColumns: '56px 1fr 1fr', gap: 'var(--space-2)', alignItems: 'end' }}
              >
                <span
                  style={{
                    fontSize: 'var(--font-size-sm)',
                    fontWeight: 'var(--font-weight-medium)',
                    color: 'var(--color-text-secondary)',
                    paddingBottom: 'var(--space-2)',
                  }}
                >
                  Bell {i + 1}
                </span>
                <FormField
                  label=""
                  name={`output-${i}`}
                  type="select"
                  value={String(row.output)}
                  onChange={(e) => updateRow(i, 'output', e.target.value)}
                >
                  <option value="0">Disabled</option>
                  {Array.from({ length: maxOutputs }, (_, j) => (
                    <option key={j + 1} value={String(j + 1)}>Output {j + 1}</option>
                  ))}
                </FormField>
                <FormField
                  label=""
                  name={`timing-${i}`}
                  type="select"
                  value={String(row.timing)}
                  onChange={(e) => updateRow(i, 'timing', e.target.value)}
                >
                  {TIMING_OPTIONS.map((ms) => (
                    <option key={ms} value={String(ms)}>{TIMING_LABELS[ms]}</option>
                  ))}
                </FormField>
              </div>
            ))}
          </div>
        )}

        {error && (
          <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>
        )}
      </div>
    </Modal>
  )
}
