// frontend/src/modals/bellcloud/devices/EditClockSettingsModal.jsx
// Edits: master switch, ODD/EVEN outputs, pulse and pause durations (sliders).

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'

// Pulse options in milliseconds — shown as sliders with labelled steps
const PULSE_STEPS  = [200, 300, 400, 500, 600, 800, 1000, 1200, 1500, 2000]
const PAUSE_STEPS  = [500, 1000, 1500, 2000, 3000, 4000, 5000]

function msLabel(ms) {
  if (!ms) return '—'
  return ms >= 1000 ? `${(ms / 1000).toFixed(1)}s` : `${ms}ms`
}

// Slider that snaps to a fixed array of allowed values
function StepSlider({ steps, value, onChange, label }) {
  const idx = steps.indexOf(value)
  const currentIdx = idx >= 0 ? idx : 0

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontWeight: 'var(--font-weight-medium)' }}>
          {label}
        </span>
        <span style={{
          fontFamily: 'var(--font-family-display)',
          fontSize: 'var(--font-size-xl)',
          fontWeight: 'var(--font-weight-bold)',
          letterSpacing: 'var(--tracking-tight)',
          color: 'var(--color-primary)',
          lineHeight: 1,
        }}>
          {msLabel(steps[currentIdx])}
        </span>
      </div>
      <input
        type="range"
        min={0}
        max={steps.length - 1}
        step={1}
        value={currentIdx}
        onChange={e => onChange(steps[Number(e.target.value)])}
        style={{ width: '100%', accentColor: 'var(--color-primary)', cursor: 'pointer' }}
      />
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>{msLabel(steps[0])}</span>
        <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>{msLabel(steps[steps.length - 1])}</span>
      </div>
    </div>
  )
}

export default function EditClockSettingsModal({ open, onClose, onSaved, attr, sub, id }) {
  const clock      = attr?.clockSettings || {}
  const maxOutputs = sub?.maxOutputs || 8
  const bellOutputsUsed = (attr?.bellOutputs || []).filter(o => o > 0)

  const existingClockOutputs = clock.clockOutputs || []
  const existingTimings      = clock.clockTimings  || []

  const [hasClock,  setHasClock]  = useState(attr?.hasClock ?? false)
  const [clockOut1, setClockOut1] = useState(String(existingClockOutputs[0] ?? 0))
  const [clockOut2, setClockOut2] = useState(String(existingClockOutputs[1] ?? 0))
  const [runPulse,  setRunPulse]  = useState(existingTimings[0] || PULSE_STEPS[3])   // default 500ms
  const [pauseMs,   setPauseMs]   = useState(existingTimings[1] || PAUSE_STEPS[1])   // default 1000ms
  const [saving,    setSaving]    = useState(false)
  const [error,     setError]     = useState('')

  const out1 = Number(clockOut1)
  const out2 = Number(clockOut2)

  const conflictMsg  = out1 > 0 && out1 === out2 ? 'ODD and EVEN outputs cannot be the same.' : null
  const validationMsg = hasClock && (out1 === 0 || out2 === 0)
    ? 'Both outputs must be assigned when the clock is enabled.'
    : null
  const canSave = !conflictMsg && !validationMsg

  const handleSave = async () => {
    if (!canSave) return
    setSaving(true)
    setError('')
    try {
      await api.put(`/devices/${id}`, {
        device_attributes: {
          hasClock,
          clockSettings: {
            ...clock,
            clockOutputs: [out1, out2].filter(o => o > 0),
            clockTimings: [runPulse, pauseMs],
          },
        },
      })
      await onSaved()
      onClose()
    } catch (err) {
      setError(err.message || 'Failed to save.')
    } finally {
      setSaving(false)
    }
  }

  const outputOptions = Array.from({ length: maxOutputs }, (_, j) => {
    const out = j + 1
    return { out, isBell: bellOutputsUsed.includes(out) }
  })

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Clock Settings"
      size="sm"
      footer={
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button variant="primary" loading={saving} disabled={!canSave} onClick={handleSave}>
            Save Settings
          </Button>
        </div>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>

        {/* Master switch */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <p style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
              Clock Controller
            </p>
            <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', marginTop: 2 }}>
              Enable or disable the clock mechanism entirely
            </p>
          </div>
          <button
            type="button"
            role="switch"
            aria-checked={hasClock}
            onClick={() => setHasClock(v => !v)}
            style={{
              position: 'relative',
              width: 44,
              height: 24,
              borderRadius: 'var(--radius-full)',
              backgroundColor: hasClock ? 'var(--color-success)' : 'var(--color-bg-island)',
              border: `1px solid ${hasClock ? 'var(--color-success)' : 'var(--color-border-strong)'}`,
              cursor: 'pointer',
              flexShrink: 0,
              padding: 0,
              transition: 'background-color 0.2s, border-color 0.2s',
            }}
          >
            <div style={{
              position: 'absolute',
              top: 3,
              left: hasClock ? 21 : 3,
              width: 16,
              height: 16,
              borderRadius: 'var(--radius-full)',
              backgroundColor: hasClock ? 'var(--color-text-inverse)' : 'var(--color-text-muted)',
              transition: 'left 0.2s',
            }} />
          </button>
        </div>

        <div style={{ height: 1, backgroundColor: 'var(--color-border)' }} />

        {/* Outputs */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
          <FormField
            label="ODD Output"
            name="clockOut1"
            type="select"
            value={clockOut1}
            onChange={e => setClockOut1(e.target.value)}
          >
            <option value="0">Disconnected</option>
            {outputOptions.map(({ out, isBell }) => (
              <option key={out} value={String(out)}>
                Output {out}{isBell ? ' (Bell)' : ''}
              </option>
            ))}
          </FormField>
          <FormField
            label="EVEN Output"
            name="clockOut2"
            type="select"
            value={clockOut2}
            onChange={e => setClockOut2(e.target.value)}
          >
            <option value="0">Disconnected</option>
            {outputOptions.map(({ out, isBell }) => (
              <option key={out} value={String(out)}>
                Output {out}{isBell ? ' (Bell)' : ''}
              </option>
            ))}
          </FormField>
        </div>

        <div style={{ height: 1, backgroundColor: 'var(--color-border)' }} />

        {/* Sliders */}
        <StepSlider
          label="Pulse Duration"
          steps={PULSE_STEPS}
          value={runPulse}
          onChange={setRunPulse}
        />
        <StepSlider
          label="Pause Duration"
          steps={PAUSE_STEPS}
          value={pauseMs}
          onChange={setPauseMs}
        />

        {/* Errors / warnings */}
        {(conflictMsg || validationMsg) && (
          <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-warning)', backgroundColor: 'var(--color-warning-bg)', padding: 'var(--space-2) var(--space-3)', borderRadius: 'var(--radius-sm)' }}>
            {conflictMsg || validationMsg}
          </p>
        )}
        {error && (
          <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>
        )}
      </div>
    </Modal>
  )
}
