// frontend/src/modals/devices/EditBacklightModal.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'

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')}`
  }
  return ''
}

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

const toBool = (v) => v === 'true' || v === true

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

  const [isOn, setIsOn] = useState(String(clock?.isBacklightAutomationOn ?? false))
  const [output, setOutput] = useState(String(clock?.backlightOutput ?? 0))
  const [onTime, setOnTime] = useState(extractTime(clock?.backlightTurnOnTime))
  const [offTime, setOffTime] = useState(extractTime(clock?.backlightTurnOffTime))
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')

  const validationMsg = (() => {
    if (!toBool(isOn)) return null
    if (!output || output === '0') return 'An output must be assigned when backlight automation is enabled.'
    if (!onTime || !offTime) return 'Both Turn On and Turn Off times must be set.'
    return null
  })()

  const handleSave = async () => {
    if (validationMsg) return
    setSaving(true)
    setError('')
    try {
      await api.put(`/devices/${id}`, {
        device_attributes: {
          clockSettings: {
            ...clock,
            isBacklightAutomationOn: toBool(isOn),
            backlightOutput: Number(output),
            backlightTurnOnTime: toBool(isOn) && onTime ? timeToIso(onTime) : '',
            backlightTurnOffTime: toBool(isOn) && offTime ? timeToIso(offTime) : '',
          },
        },
      })
      await onSaved()
      onClose()
    } catch (err) {
      setError(err.message || 'Failed to save.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Edit Backlight 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={!!validationMsg} onClick={handleSave}>
            Sync & Save Settings
          </Button>
        </div>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
        {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>
        )}
        <FormField
          label="Automation"
          name="isOn"
          type="select"
          value={isOn}
          onChange={(e) => setIsOn(e.target.value)}
        >
          <option value="true">Automated</option>
          <option value="false">Disabled</option>
        </FormField>
        <FormField
          label="Output"
          name="output"
          type="select"
          value={output}
          onChange={(e) => setOutput(e.target.value)}
        >
          <option value="0">Disabled</option>
          {Array.from({ length: maxOutputs }, (_, j) => {
            const out = j + 1
            const isBell = bellOutputsUsed.includes(out)
            const isClock = clockOutputsUsed.includes(out)
            return (
              <option key={out} value={String(out)}>
                Output {out}{isBell ? ' (Bell)' : isClock ? ' (Clock)' : ''}
              </option>
            )
          })}
        </FormField>
        {toBool(isOn) && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
            <FormField
              label="Turn On Time"
              name="onTime"
              value={onTime}
              onChange={(e) => setOnTime(e.target.value)}
              placeholder="HH:MM"
            />
            <FormField
              label="Turn Off Time"
              name="offTime"
              value={offTime}
              onChange={(e) => setOffTime(e.target.value)}
              placeholder="HH:MM"
            />
          </div>
        )}
        {error && (
          <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>
        )}
      </div>
    </Modal>
  )
}
