import React, { useEffect, useState } from 'react'
import { apiLoadTimeslotSettings, apiSaveTimeslotSettings } from '../api/timeslotApi'
import generateSlots from '../utils/generateSlots'
import Heading from './Heading'
import Loading from './Loading'

const START_HOURS = Array.from({ length: 24 }, (_, h) => String(h).padStart(2, '0') + ':00')
const END_HOURS = Array.from({ length: 24 }, (_, h) => String(h + 1).padStart(2, '0') + ':00')
const DURATIONS = [1, 2, 3, 4, 6, 8, 12]

const TimeslotSettingsTab = () => {
  const [loaded, setLoaded] = useState(false)
  const [loadError, setLoadError] = useState(false)
  const [saving, setSaving] = useState(false)
  const [saveError, setSaveError] = useState(false)
  const [saved, setSaved] = useState(false)
  const [settings, setSettings] = useState({
    enabled: false,
    startTime: '08:00',
    endTime: '20:00',
    duration: 2,
    maxOrders: 10,
  })

  useEffect(() => {
    if (!loaded) {
      apiLoadTimeslotSettings((data) => {
        setSettings({
          enabled: !!data.enabled,
          startTime: data.startTime || '08:00',
          endTime: data.endTime || '20:00',
          duration: parseInt(data.duration, 10) || 2,
          maxOrders: parseInt(data.maxOrders, 10) || 10,
        })
        setLoaded(true)
      }, () => {
        setLoadError(true)
      })
    }
  }, [loaded])

  const update = (patch) => {
    setSettings(prev => ({ ...prev, ...patch }))
  }

  const handleSave = (e) => {
    e.preventDefault()
    setSaving(true)
    setSaveError(false)
    setSaved(false)
    apiSaveTimeslotSettings(settings, () => {
      setSaving(false)
      setSaved(true)
    }, () => {
      setSaving(false)
      setSaveError(true)
    })
  }

  const slots = generateSlots(settings.startTime, settings.endTime, settings.duration)

  return (
    <div className="dreamfox-tab">
      <Heading text="Timeslot Settings" />
      {loadError && <p className="dreamfox-field__error">Error loading timeslot settings. Please refresh the page.</p>}
      {!loaded && !loadError && <Loading message="Loading..." />}
      {loaded &&
        <div className="dreamfox-content">
          <div className="dreamfox-field">
            <label className="dreamfox-field__label" htmlFor="dreamfox-ts-enabled">Enable timeslots</label>
            <div className="dreamfox-label">
              <input
                type="checkbox"
                id="dreamfox-ts-enabled"
                checked={settings.enabled}
                onChange={e => update({ enabled: e.target.checked })}
              />
              <small>When enabled, customers must choose a delivery timeslot at checkout.</small>
            </div>
          </div>

          {settings.enabled && <>
            <div className="dreamfox-field">
              <label className="dreamfox-field__label" htmlFor="dreamfox-ts-start">Delivery window start</label>
              <div className="dreamfox-field__content">
                <select id="dreamfox-ts-start" value={settings.startTime} onChange={e => update({ startTime: e.target.value })}>
                  {START_HOURS.map(h => <option key={h} value={h}>{h}</option>)}
                </select>
              </div>
            </div>

            <div className="dreamfox-field">
              <label className="dreamfox-field__label" htmlFor="dreamfox-ts-end">Delivery window end</label>
              <div className="dreamfox-field__content">
                <select id="dreamfox-ts-end" value={settings.endTime} onChange={e => update({ endTime: e.target.value })}>
                  {END_HOURS.map(h => <option key={h} value={h}>{h}</option>)}
                </select>
              </div>
            </div>

            <div className="dreamfox-field">
              <label className="dreamfox-field__label" htmlFor="dreamfox-ts-duration">Timeslot duration (hours)</label>
              <div className="dreamfox-field__content">
                <select id="dreamfox-ts-duration" value={settings.duration} onChange={e => update({ duration: parseInt(e.target.value, 10) })}>
                  {DURATIONS.map(d => <option key={d} value={d}>{d}</option>)}
                </select><br/>
                <small>Maximum 12 hours per slot.</small>
              </div>
            </div>

            <div className="dreamfox-field">
              <label className="dreamfox-field__label" htmlFor="dreamfox-ts-max">Max orders per timeslot</label>
              <div className="dreamfox-field__content">
                <input
                  type="number"
                  id="dreamfox-ts-max"
                  min="1"
                  value={settings.maxOrders}
                  onChange={e => {
                    const value = parseInt(e.target.value, 10)
                    update({ maxOrders: isNaN(value) ? 1 : Math.max(1, value) })
                  }}
                /><br/>
                <small>Full slots are hidden automatically at checkout.</small>
              </div>
            </div>

            <div className="dreamfox-field">
              <label className="dreamfox-field__label">Slot preview</label>
              <div className="dreamfox-field__content">
                <span className="dreamfox-ts-preview">
                  {slots.length ? slots.join(', ') : '— no slots fit in this window —'}
                </span><br/>
                <small>Updates automatically when you change start, end or duration.</small>
              </div>
            </div>
          </>}

          {saving && <Loading message="Saving..." />}
          {!saving && <input className="button-large button-primary" type="button" value="Save Timeslot Settings" onClick={handleSave} />}
          {saved && <p className="dreamfox-ts-saved">Saved!</p>}
          {saveError && <p className="dreamfox-field__error">Something went wrong while saving. Please try again.</p>}
        </div>
      }
    </div>
  )
}

export default TimeslotSettingsTab
