// frontend/src/modals/bellcloud/devices/EditAlertsModal.jsx
// Edits: alert type (segmented), tempo, bell assignments, day/night silence.

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'

function extractTime(tsStr) {
  if (!tsStr) return ''
  const d = new Date(
    tsStr.replace(' at ', ' ').replace('UTC+0000', 'UTC').replace(/UTC\+(\d{4})/, 'UTC')
  )
  if (!isNaN(d.getTime())) {
    return `${d.getUTCHours().toString().padStart(2, '0')}:${d.getUTCMinutes().toString().padStart(2, '0')}`
  }
  const match = tsStr.match(/(\d{1,2}):(\d{2})/)
  return match ? `${match[1].padStart(2, '0')}:${match[2]}` : ''
}

function timeToIso(hhmm) {
  if (!hhmm) return ''
  return `2000-01-01T${hhmm}:00Z`
}

const TEMPO_OPTIONS = [500, 1000, 1500, 2000, 2500]

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

// Segmented button group for alert type
function AlertTypeSelector({ value, onChange }) {
  const options = [
    { value: 'disabled', label: 'Disabled' },
    { value: 'single',   label: 'Single Fire' },
    { value: 'multi',    label: 'Hour Indicating' },
  ]
  return (
    <div style={{ display: 'flex', gap: 0, borderRadius: 'var(--radius-md)', overflow: 'hidden', border: '1px solid var(--color-border)' }}>
      {options.map((opt, i) => (
        <button
          key={opt.value}
          type="button"
          onClick={() => onChange(opt.value)}
          style={{
            flex: 1,
            padding: 'var(--space-2) var(--space-3)',
            fontSize: 'var(--font-size-sm)',
            fontWeight: value === opt.value ? 'var(--font-weight-semibold)' : 'var(--font-weight-normal)',
            color: value === opt.value ? 'var(--color-text-inverse)' : 'var(--color-text-muted)',
            backgroundColor: value === opt.value ? 'var(--color-primary-container)' : 'var(--color-bg-elevated)',
            border: 'none',
            borderLeft: i > 0 ? '1px solid var(--color-border)' : 'none',
            cursor: 'pointer',
            transition: 'background-color 0.15s, color 0.15s',
          }}
        >
          {opt.label}
        </button>
      ))}
    </div>
  )
}

// Inline on/off toggle row for silence periods
function SilenceBlock({ title, isOn, onToggle, from, onFromChange, to, onToChange }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
          {title}
        </span>
        <button
          type="button"
          role="switch"
          aria-checked={isOn}
          onClick={onToggle}
          style={{
            position: 'relative',
            width: 36,
            height: 20,
            borderRadius: 'var(--radius-full)',
            backgroundColor: isOn ? 'var(--color-primary-container)' : 'var(--color-bg-island)',
            border: `1px solid ${isOn ? 'var(--color-primary)' : 'var(--color-border-strong)'}`,
            cursor: 'pointer',
            padding: 0,
            transition: 'background-color 0.2s, border-color 0.2s',
            flexShrink: 0,
          }}
        >
          <div style={{
            position: 'absolute',
            top: 2,
            left: isOn ? 17 : 2,
            width: 14,
            height: 14,
            borderRadius: 'var(--radius-full)',
            backgroundColor: isOn ? 'var(--color-primary)' : 'var(--color-text-muted)',
            transition: 'left 0.2s',
          }} />
        </button>
      </div>
      {isOn && (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
          <FormField label="From" name={`${title}-from`} value={from} onChange={e => onFromChange(e.target.value)} placeholder="HH:MM" />
          <FormField label="Until" name={`${title}-to`}  value={to}   onChange={e => onToChange(e.target.value)}   placeholder="HH:MM" />
        </div>
      )}
    </div>
  )
}

export default function EditAlertsModal({ open, onClose, onSaved, clock, attr, id }) {
  const totalBells = attr?.totalBells || 8

  const [alertType,      setAlertType]      = useState(clock?.ringAlerts || 'disabled')
  const [ringIntervals,  setRingIntervals]  = useState(clock?.ringIntervals ?? 1000)
  const [hourBell,       setHourBell]       = useState(String(clock?.hourAlertsBell ?? 0))
  const [halfBell,       setHalfBell]       = useState(String(clock?.halfhourAlertsBell ?? 0))
  const [quarterBell,    setQuarterBell]    = useState(String(clock?.quarterAlertsBell ?? 0))
  const [isDayOn,        setIsDayOn]        = useState(clock?.isDaySilenceOn ?? false)
  const [daySilenceFrom, setDaySilenceFrom] = useState(extractTime(clock?.daySilenceFrom))
  const [daySilenceTo,   setDaySilenceTo]   = useState(extractTime(clock?.daySilenceTo))
  const [isNightOn,      setIsNightOn]      = useState(clock?.isNightSilenceOn ?? false)
  const [nightFrom,      setNightFrom]      = useState(extractTime(clock?.nightSilenceFrom))
  const [nightTo,        setNightTo]        = useState(extractTime(clock?.nightSilenceTo))
  const [saving,         setSaving]         = useState(false)
  const [error,          setError]          = useState('')

  const validationMsg = (() => {
    if (alertType === 'multi' && !ringIntervals) return 'Alert Tempo must be set for Hour Indicating mode.'
    if (isDayOn   && (!daySilenceFrom || !daySilenceTo)) return 'Day Silence is on — set both From and Until times.'
    if (isNightOn && (!nightFrom      || !nightTo))      return 'Night Silence is on — set both From and Until times.'
    return null
  })()

  const handleSave = async () => {
    if (validationMsg) return
    setSaving(true)
    setError('')
    try {
      await api.put(`/devices/${id}`, {
        device_attributes: {
          clockSettings: {
            ...clock,
            ringAlerts:           alertType,
            ringAlertsMasterOn:   alertType !== 'disabled',
            ringIntervals:        alertType === 'multi' ? ringIntervals : clock?.ringIntervals,
            hourAlertsBell:       Number(hourBell),
            halfhourAlertsBell:   Number(halfBell),
            quarterAlertsBell:    Number(quarterBell),
            isDaySilenceOn:       isDayOn,
            daySilenceFrom:       isDayOn && daySilenceFrom ? timeToIso(daySilenceFrom) : (clock?.daySilenceFrom || ''),
            daySilenceTo:         isDayOn && daySilenceTo   ? timeToIso(daySilenceTo)   : (clock?.daySilenceTo   || ''),
            isNightSilenceOn:     isNightOn,
            nightSilenceFrom:     isNightOn && nightFrom ? timeToIso(nightFrom) : (clock?.nightSilenceFrom || ''),
            nightSilenceTo:       isNightOn && nightTo   ? timeToIso(nightTo)   : (clock?.nightSilenceTo   || ''),
          },
        },
      })
      await onSaved()
      onClose()
    } catch (err) {
      setError(err.message || 'Failed to save.')
    } finally {
      setSaving(false)
    }
  }

  const bellOptions = [
    { value: '0', label: 'Disabled' },
    ...Array.from({ length: totalBells }, (_, i) => ({ value: String(i + 1), label: `Bell ${i + 1}` })),
  ]

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Alert Settings"
      size="md"
      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={!!validationMsg} onClick={handleSave}>
            Save Settings
          </Button>
        </div>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>

        {/* Alert type segmented selector */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
          <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontWeight: 'var(--font-weight-medium)' }}>
            Alert Type
          </span>
          <AlertTypeSelector value={alertType} onChange={setAlertType} />
        </div>

        {/* Tempo — only for Hour Indicating */}
        {alertType === 'multi' && (
          <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)' }}>
                Alert Tempo
              </span>
              <span style={{ fontFamily: 'var(--font-family-display)', fontSize: 'var(--font-size-lg)', fontWeight: 'var(--font-weight-bold)', color: 'var(--color-primary)', letterSpacing: 'var(--tracking-tight)' }}>
                {msLabel(ringIntervals)}
              </span>
            </div>
            <input
              type="range"
              min={0}
              max={TEMPO_OPTIONS.length - 1}
              step={1}
              value={TEMPO_OPTIONS.indexOf(ringIntervals) >= 0 ? TEMPO_OPTIONS.indexOf(ringIntervals) : 1}
              onChange={e => setRingIntervals(TEMPO_OPTIONS[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(TEMPO_OPTIONS[0])}</span>
              <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>{msLabel(TEMPO_OPTIONS[TEMPO_OPTIONS.length - 1])}</span>
            </div>
          </div>
        )}

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

        {/* Bell assignments */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 'var(--space-3)' }}>
          <FormField label="Hours Bell" name="hourBell" type="select" value={hourBell} onChange={e => setHourBell(e.target.value)}>
            {bellOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
          </FormField>
          <FormField label="Half-Hours Bell" name="halfBell" type="select" value={halfBell} onChange={e => setHalfBell(e.target.value)}>
            {bellOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
          </FormField>
          <FormField label="Quarters Bell" name="quarterBell" type="select" value={quarterBell} onChange={e => setQuarterBell(e.target.value)}>
            {bellOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
          </FormField>
        </div>

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

        {/* Silence periods */}
        <SilenceBlock
          title="Day Silence"
          isOn={isDayOn}
          onToggle={() => setIsDayOn(v => !v)}
          from={daySilenceFrom}
          onFromChange={setDaySilenceFrom}
          to={daySilenceTo}
          onToChange={setDaySilenceTo}
        />
        <SilenceBlock
          title="Night Silence"
          isOn={isNightOn}
          onToggle={() => setIsNightOn(v => !v)}
          from={nightFrom}
          onFromChange={setNightFrom}
          to={nightTo}
          onToChange={setNightTo}
        />

        {/* Warnings / errors */}
        {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)' }}>
            {validationMsg}
          </p>
        )}
        {error && (
          <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>
        )}
      </div>
    </Modal>
  )
}
