import { useState, useEffect } from 'react'
import api from '@/services/api'
import dayjs from 'dayjs'

// Types for Calendar entities
type SlotType = 'work' | 'on_call' | 'entertainment' | 'system'
type EventType = 'job' | 'entertainment' | 'system_event'
type SlotStatus = 'not_started' | 'ongoing' | 'deferred' | 'skipped' | 'paused' | 'finished' | 'aborted'

interface TimeSlotResponse {
  slot_id: string  // real int id or "plan-{planId}-{date}" for virtual
  date: string
  slot_type: SlotType
  estimated_duration: number
  scheduled_at: string  // HH:mm
  started_at: string | null
  attended: boolean
  actual_duration: number | null
  event_type: EventType | null
  event_data: Record<string, any> | null
  priority: number
  status: SlotStatus
  plan_id: number | null
  is_virtual: boolean
  created_at: string | null
  updated_at: string | null
}

interface DayViewResponse {
  date: string
  user_id: number
  slots: TimeSlotResponse[]
}

interface SchedulePlanResponse {
  id: number
  slot_type: SlotType
  estimated_duration: number
  event_type: string | null
  event_data: Record<string, any> | null
  at_time: string
  on_day: string | null
  on_week: number | null
  on_month: string | null
  is_active: boolean
  created_at: string
  updated_at: string | null
}

interface PlanListResponse {
  plans: SchedulePlanResponse[]
}

type Weekday = 'sun' | 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat'
type MonthName = 'jan' | 'feb' | 'mar' | 'apr' | 'may' | 'jun' | 'jul' | 'aug' | 'sep' | 'oct' | 'nov' | 'dec'

interface WorkloadWarning {
  period: string
  slot_type: string
  current: number
  minimum: number
  message: string
}

interface ScheduleResponse {
  slot: TimeSlotResponse
  warnings: WorkloadWarning[]
}

const SLOT_TYPES: { value: SlotType; label: string }[] = [
  { value: 'work', label: 'Work' },
  { value: 'on_call', label: 'On Call' },
  { value: 'entertainment', label: 'Entertainment' },
  { value: 'system', label: 'System' },
]

const EVENT_TYPES: { value: EventType; label: string }[] = [
  { value: 'job', label: 'Job' },
  { value: 'entertainment', label: 'Entertainment' },
  { value: 'system_event', label: 'System Event' },
]

const WEEKDAYS: { value: Weekday; label: string }[] = [
  { value: 'sun', label: 'Sunday' },
  { value: 'mon', label: 'Monday' },
  { value: 'tue', label: 'Tuesday' },
  { value: 'wed', label: 'Wednesday' },
  { value: 'thu', label: 'Thursday' },
  { value: 'fri', label: 'Friday' },
  { value: 'sat', label: 'Saturday' },
]

const MONTHS: { value: MonthName; label: string }[] = [
  { value: 'jan', label: 'January' },
  { value: 'feb', label: 'February' },
  { value: 'mar', label: 'March' },
  { value: 'apr', label: 'April' },
  { value: 'may', label: 'May' },
  { value: 'jun', label: 'June' },
  { value: 'jul', label: 'July' },
  { value: 'aug', label: 'August' },
  { value: 'sep', label: 'September' },
  { value: 'oct', label: 'October' },
  { value: 'nov', label: 'November' },
  { value: 'dec', label: 'December' },
]

const SLOT_TYPE_ICONS: Record<string, string> = {
  work: '💼',
  on_call: '📞',
  entertainment: '🎮',
  system: '⚙️',
}

const STATUS_CLASSES: Record<string, string> = {
  not_started: 'status-open',
  ongoing: 'status-undergoing',
  deferred: 'status-pending',
  skipped: 'status-closed',
  paused: 'status-pending',
  finished: 'status-completed',
  aborted: 'status-closed',
}

export default function CalendarPage() {
  const [selectedDate, setSelectedDate] = useState(dayjs().format('YYYY-MM-DD'))
  const [slots, setSlots] = useState<TimeSlotResponse[]>([])
  const [plans, setPlans] = useState<SchedulePlanResponse[]>([])
  const [loading, setLoading] = useState(false)
  const [activeTab, setActiveTab] = useState<'daily' | 'plans'>('daily')
  const [error, setError] = useState('')

  // Create/Edit slot modal state
  const [showSlotModal, setShowSlotModal] = useState(false)
  const [editingSlot, setEditingSlot] = useState<TimeSlotResponse | null>(null)
  const [slotForm, setSlotForm] = useState({
    slot_type: 'work' as SlotType,
    scheduled_at: '09:00',
    estimated_duration: 25,
    event_type: '' as string,
    event_data_code: '',
    event_data_event: '',
    priority: 50,
  })
  const [slotSaving, setSlotSaving] = useState(false)
  const [warnings, setWarnings] = useState<WorkloadWarning[]>([])
  const [showPlanModal, setShowPlanModal] = useState(false)
  const [editingPlan, setEditingPlan] = useState<SchedulePlanResponse | null>(null)
  const [planSaving, setPlanSaving] = useState(false)
  const [planForm, setPlanForm] = useState({
    slot_type: 'work' as SlotType,
    estimated_duration: 25,
    at_time: '09:00',
    on_day: '' as Weekday | '',
    on_week: '' as string,
    on_month: '' as MonthName | '',
    event_type: '' as string,
    event_data_code: '',
    event_data_event: '',
  })

  const fetchSlots = async (date: string) => {
    setLoading(true)
    setError('')
    try {
      const { data } = await api.get<DayViewResponse>(`/calendar/day?date=${date}`)
      setSlots(Array.isArray(data?.slots) ? data.slots : [])
    } catch (err: any) {
      setError(err.response?.data?.detail || 'Failed to load calendar')
      setSlots([])
    } finally {
      setLoading(false)
    }
  }

  const fetchPlans = async () => {
    try {
      const { data } = await api.get<PlanListResponse>('/calendar/plans')
      setPlans(Array.isArray(data?.plans) ? data.plans : [])
    } catch (err: any) {
      console.error('Failed to load plans:', err)
    }
  }

  useEffect(() => {
    fetchSlots(selectedDate)
    fetchPlans()
  }, [])

  useEffect(() => {
    if (activeTab === 'daily') {
      fetchSlots(selectedDate)
    }
  }, [selectedDate])

  const handleDateChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSelectedDate(e.target.value)
  }

  const goToday = () => setSelectedDate(dayjs().format('YYYY-MM-DD'))
  const goPrev = () => setSelectedDate(dayjs(selectedDate).subtract(1, 'day').format('YYYY-MM-DD'))
  const goNext = () => setSelectedDate(dayjs(selectedDate).add(1, 'day').format('YYYY-MM-DD'))

  const formatPlanSchedule = (plan: SchedulePlanResponse) => {
    const parts: string[] = [`at ${plan.at_time}`]
    if (plan.on_day) parts.push(`on ${plan.on_day}`)
    if (plan.on_week) parts.push(`week ${plan.on_week}`)
    if (plan.on_month) parts.push(`in ${plan.on_month}`)
    return parts.join(' · ')
  }

  // --- Slot create/edit ---
  const openCreateSlotModal = () => {
    setEditingSlot(null)
    setSlotForm({
      slot_type: 'work',
      scheduled_at: '09:00',
      estimated_duration: 25,
      event_type: '',
      event_data_code: '',
      event_data_event: '',
      priority: 50,
    })
    setWarnings([])
    setError('')
    setShowSlotModal(true)
  }

  const openEditSlotModal = (slot: TimeSlotResponse) => {
    setEditingSlot(slot)
    setSlotForm({
      slot_type: slot.slot_type,
      scheduled_at: slot.scheduled_at,
      estimated_duration: slot.estimated_duration,
      event_type: slot.event_type || '',
      event_data_code: slot.event_data?.code || '',
      event_data_event: slot.event_data?.event || '',
      priority: slot.priority,
    })
    setWarnings([])
    setError('')
    setShowSlotModal(true)
  }

  const buildEventData = () => {
    if (!slotForm.event_type) return null
    if (slotForm.event_type === 'job') {
      return slotForm.event_data_code ? { type: 'Task', code: slotForm.event_data_code } : null
    }
    if (slotForm.event_type === 'system_event') {
      return slotForm.event_data_event ? { event: slotForm.event_data_event } : null
    }
    return null
  }

  const buildPlanEventData = () => {
    if (!planForm.event_type) return null
    if (planForm.event_type === 'job') {
      return planForm.event_data_code ? { type: 'Task', code: planForm.event_data_code } : null
    }
    if (planForm.event_type === 'system_event') {
      return planForm.event_data_event ? { event: planForm.event_data_event } : null
    }
    return null
  }

  const openCreatePlanModal = () => {
    setEditingPlan(null)
    setPlanForm({
      slot_type: 'work',
      estimated_duration: 25,
      at_time: '09:00',
      on_day: '',
      on_week: '',
      on_month: '',
      event_type: '',
      event_data_code: '',
      event_data_event: '',
    })
    setError('')
    setShowPlanModal(true)
  }

  const openEditPlanModal = (plan: SchedulePlanResponse) => {
    setEditingPlan(plan)
    setPlanForm({
      slot_type: plan.slot_type,
      estimated_duration: plan.estimated_duration,
      at_time: plan.at_time.slice(0, 5),
      on_day: (plan.on_day?.toLowerCase() as Weekday | undefined) || '',
      on_week: plan.on_week ? String(plan.on_week) : '',
      on_month: (plan.on_month?.toLowerCase() as MonthName | undefined) || '',
      event_type: plan.event_type || '',
      event_data_code: plan.event_data?.code || '',
      event_data_event: plan.event_data?.event || '',
    })
    setError('')
    setShowPlanModal(true)
  }

  const handleSavePlan = async () => {
    setPlanSaving(true)
    setError('')
    try {
      const payload: any = {
        slot_type: planForm.slot_type,
        estimated_duration: planForm.estimated_duration,
        at_time: planForm.at_time,
        on_day: planForm.on_day || null,
        on_week: planForm.on_week ? Number(planForm.on_week) : null,
        on_month: planForm.on_month || null,
        event_type: planForm.event_type || null,
        event_data: buildPlanEventData(),
      }

      if (editingPlan) {
        await api.patch(`/calendar/plans/${editingPlan.id}`, payload)
      } else {
        await api.post('/calendar/plans', payload)
      }

      setShowPlanModal(false)
      fetchPlans()
      if (activeTab === 'daily') {
        fetchSlots(selectedDate)
      }
    } catch (err: any) {
      setError(err.response?.data?.detail || 'Save plan failed')
    } finally {
      setPlanSaving(false)
    }
  }

  const handleSaveSlot = async () => {
    setSlotSaving(true)
    setError('')
    setWarnings([])
    try {
      const payload: any = {
        slot_type: slotForm.slot_type,
        scheduled_at: slotForm.scheduled_at,
        estimated_duration: slotForm.estimated_duration,
        priority: slotForm.priority,
        event_type: slotForm.event_type || null,
        event_data: buildEventData(),
      }

      let response: any
      if (editingSlot) {
        // Edit existing slot
        if (editingSlot.is_virtual) {
          response = await api.patch(`/calendar/slots/virtual/${editingSlot.slot_id}`, payload)
        } else if (editingSlot.slot_id) {
          response = await api.patch(`/calendar/slots/${editingSlot.slot_id}`, payload)
        } else {
          throw new Error('Missing slot identifier for edit')
        }
      } else {
        // Create new slot
        payload.date = selectedDate
        response = await api.post('/calendar/slots', payload)
      }

      // Check for warnings in response
      if (response.data?.warnings && response.data.warnings.length > 0) {
        setWarnings(response.data.warnings)
      }

      setShowSlotModal(false)
      fetchSlots(selectedDate)
    } catch (err: any) {
      const detail = err.response?.data?.detail
      if (typeof detail === 'string' && detail.toLowerCase().includes('overlap')) {
        setError(`⚠️ Overlap conflict: ${detail}`)
      } else if (detail && typeof detail === 'object') {
        const message = typeof detail.message === 'string' ? detail.message : 'Save failed'
        const conflicts = Array.isArray(detail.conflicts) ? detail.conflicts : []
        if (conflicts.length > 0) {
          const summary = conflicts
            .map((conflict: any) => `${conflict.slot_type || 'slot'} at ${conflict.scheduled_at || 'unknown time'}`)
            .join(', ')
          setError(`⚠️ ${message}: ${summary}`)
        } else {
          setError(`⚠️ ${message}`)
        }
      } else {
        setError(detail || 'Save failed')
      }
    } finally {
      setSlotSaving(false)
    }
  }

  // --- Slot cancel ---
  const handleCancelSlot = async (slot: TimeSlotResponse) => {
    if (!confirm(`Cancel this ${slot.slot_type} slot at ${slot.scheduled_at}?`)) return
    setError('')
    try {
      if (slot.is_virtual) {
        await api.post(`/calendar/slots/virtual/${slot.slot_id}/cancel`)
      } else if (slot.slot_id) {
        await api.post(`/calendar/slots/${slot.slot_id}/cancel`)
      } else {
        throw new Error('Missing slot identifier for cancel')
      }
      fetchSlots(selectedDate)
    } catch (err: any) {
      setError(err.response?.data?.detail || 'Cancel failed')
    }
  }

  // --- Plan cancel ---
  const handleCancelPlan = async (plan: SchedulePlanResponse) => {
    if (!confirm(`Cancel plan #${plan.id}? This won't affect past materialized slots.`)) return
    setError('')
    try {
      await api.post(`/calendar/plans/${plan.id}/cancel`)
      fetchPlans()
    } catch (err: any) {
      setError(err.response?.data?.detail || 'Cancel plan failed')
    }
  }

  // Check if a date is in the past
  const isPastDate = dayjs(selectedDate).isBefore(dayjs().startOf('day'))

  return (
    <div className="calendar-page">
      <div className="page-header" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <h2>📅 Calendar</h2>
      </div>

      {/* Tab switcher */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
        <button
          className={activeTab === 'daily' ? 'btn-primary' : 'btn-secondary'}
          onClick={() => setActiveTab('daily')}
        >
          Daily View
        </button>
        <button
          className={activeTab === 'plans' ? 'btn-primary' : 'btn-secondary'}
          onClick={() => setActiveTab('plans')}
        >
          Plans ({plans.length})
        </button>
      </div>

      {error && <div className="error-message" style={{ color: 'var(--danger)', marginBottom: 12 }}>{error}</div>}

      {/* Workload warnings banner */}
      {warnings.length > 0 && (
        <div style={{ background: 'var(--warning-bg, #fff3cd)', border: '1px solid var(--warning-border, #ffc107)', borderRadius: 8, padding: 12, marginBottom: 12 }}>
          <strong>⚠️ Workload Warnings:</strong>
          <ul style={{ margin: '4px 0 0 16px', padding: 0 }}>
            {warnings.map((w, i) => (
              <li key={i}>{w.message} ({w.period} {w.slot_type}: {w.current}/{w.minimum} min)</li>
            ))}
          </ul>
        </div>
      )}

      {activeTab === 'daily' && (
        <>
          {/* Date navigation */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16 }}>
            <button className="btn-secondary" onClick={goPrev}>◀</button>
            <input
              type="date"
              value={selectedDate}
              onChange={handleDateChange}
              style={{ fontSize: '1rem', padding: '4px 8px' }}
            />
            <button className="btn-secondary" onClick={goNext}>▶</button>
            <button className="btn-transition" onClick={goToday}>Today</button>
            {!isPastDate && (
              <button className="btn-primary" onClick={openCreateSlotModal} style={{ marginLeft: 'auto' }}>+ New Slot</button>
            )}
          </div>

          {/* Deferred slots notice */}
          {slots.some(s => s.status === 'deferred') && (
            <div style={{ background: 'var(--warning-bg, #fff3cd)', border: '1px solid var(--warning-border, #ffc107)', borderRadius: 8, padding: 10, marginBottom: 12, fontSize: '0.9rem' }}>
              ⏳ Some slots are <strong>deferred</strong> — they were postponed due to scheduling conflicts or agent unavailability.
            </div>
          )}

          {/* Slot list */}
          {loading ? (
            <div className="loading">Loading...</div>
          ) : slots.length === 0 ? (
            <div className="empty" style={{ padding: '40px 0', color: 'var(--text-secondary)', textAlign: 'center' }}>
              No slots scheduled for {dayjs(selectedDate).format('MMMM D, YYYY')}.
            </div>
          ) : (
            <div className="milestone-grid">
              {slots.map((slot) => (
                <div
                  key={slot.slot_id}
                  className="milestone-card"
                  style={{ opacity: slot.is_virtual ? 0.8 : 1 }}
                >
                  <div className="milestone-card-header" style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                    <span style={{ fontSize: '1.2rem' }}>{SLOT_TYPE_ICONS[slot.slot_type] || '📋'}</span>
                    <span className="badge">{slot.slot_type.replace('_', ' ')}</span>
                    <span className={`badge ${STATUS_CLASSES[slot.status] || ''}`}>{slot.status.replace('_', ' ')}</span>
                    {slot.is_virtual && <span className="badge" style={{ background: 'var(--text-secondary)', color: 'white', fontSize: '0.7rem' }}>plan</span>}
                    <span style={{ marginLeft: 'auto', fontWeight: 600 }}>{slot.scheduled_at}</span>
                  </div>
                  <div style={{ marginTop: 8, display: 'flex', gap: 16, fontSize: '0.9rem', color: 'var(--text-secondary)' }}>
                    <span>⏱ {slot.estimated_duration} min</span>
                    <span>⚡ Priority: {slot.priority}</span>
                    {slot.event_type && <span>📌 {slot.event_type.replace('_', ' ')}</span>}
                  </div>
                  {slot.event_data && slot.event_data.code && (
                    <div style={{ marginTop: 4, fontSize: '0.85rem', color: 'var(--text-secondary)' }}>
                      🔗 {slot.event_data.code}
                    </div>
                  )}
                  {slot.event_data && slot.event_data.event && (
                    <div style={{ marginTop: 4, fontSize: '0.85rem', color: 'var(--text-secondary)' }}>
                      📣 {slot.event_data.event}
                    </div>
                  )}
                  {/* Action buttons for non-past, modifiable slots */}
                  {!isPastDate && (slot.status === 'not_started' || slot.status === 'deferred') && (
                    <div style={{ marginTop: 8, display: 'flex', gap: 6 }}>
                      <button
                        className="btn-transition"
                        style={{ padding: '4px 10px', fontSize: '0.8rem' }}
                        onClick={() => openEditSlotModal(slot)}
                      >
                        ✏️ Edit
                      </button>
                      <button
                        className="btn-danger"
                        style={{ padding: '4px 10px', fontSize: '0.8rem' }}
                        onClick={() => handleCancelSlot(slot)}
                      >
                        ❌ Cancel
                      </button>
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </>
      )}

      {activeTab === 'plans' && (
        <>
          <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 16 }}>
            <button className="btn-primary" onClick={openCreatePlanModal}>+ New Plan</button>
          </div>

          <div className="milestone-grid">
          {plans.length === 0 ? (
            <div className="empty" style={{ padding: '40px 0', color: 'var(--text-secondary)', textAlign: 'center' }}>
              No schedule plans configured.
            </div>
          ) : (
            plans.map((plan) => (
              <div key={plan.id} className="milestone-card">
                <div className="milestone-card-header" style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                  <span style={{ fontSize: '1.2rem' }}>{SLOT_TYPE_ICONS[plan.slot_type] || '📋'}</span>
                  <span className="badge">{plan.slot_type.replace('_', ' ')}</span>
                  {!plan.is_active && <span className="badge status-closed">inactive</span>}
                  <span style={{ marginLeft: 'auto', fontWeight: 600 }}>Plan #{plan.id}</span>
                </div>
                <div style={{ marginTop: 8, fontSize: '0.9rem', color: 'var(--text-secondary)' }}>
                  <div>🔄 {formatPlanSchedule(plan)}</div>
                  <div>⏱ {plan.estimated_duration} min</div>
                  {plan.event_type && <div>📌 {plan.event_type.replace('_', ' ')}</div>}
                </div>
                {plan.is_active && (
                  <div style={{ marginTop: 8, display: 'flex', gap: 8 }}>
                    <button
                      className="btn-transition"
                      style={{ padding: '4px 10px', fontSize: '0.8rem' }}
                      onClick={() => openEditPlanModal(plan)}
                    >
                      ✏️ Edit Plan
                    </button>
                    <button
                      className="btn-danger"
                      style={{ padding: '4px 10px', fontSize: '0.8rem' }}
                      onClick={() => handleCancelPlan(plan)}
                    >
                      ❌ Cancel Plan
                    </button>
                  </div>
                )}
              </div>
            ))
          )}
          </div>
        </>
      )}

      {/* Create/Edit Slot Modal */}
      {showSlotModal && (
        <div className="modal-overlay" onClick={() => setShowSlotModal(false)}>
          <div className="modal" onClick={(e) => e.stopPropagation()}>
            <h3>{editingSlot ? 'Edit Slot' : 'New Slot'}</h3>
            <p style={{ color: 'var(--text-secondary)', fontSize: '0.9rem' }}>
              Date: <strong>{dayjs(selectedDate).format('MMMM D, YYYY')}</strong>
            </p>

            <label style={{ display: 'block', marginBottom: 8 }}>
              <strong>Slot Type</strong>
              <select
                value={slotForm.slot_type}
                onChange={(e) => setSlotForm({ ...slotForm, slot_type: e.target.value as SlotType })}
                style={{ width: '100%', marginTop: 4 }}
              >
                {SLOT_TYPES.map((t) => (
                  <option key={t.value} value={t.value}>{t.label}</option>
                ))}
              </select>
            </label>

            <label style={{ display: 'block', marginBottom: 8 }}>
              <strong>Scheduled At</strong>
              <input
                type="time"
                value={slotForm.scheduled_at}
                onChange={(e) => setSlotForm({ ...slotForm, scheduled_at: e.target.value })}
                style={{ width: '100%', marginTop: 4 }}
              />
            </label>

            <label style={{ display: 'block', marginBottom: 8 }}>
              <strong>Estimated Duration (minutes, 1–50)</strong>
              <input
                type="number"
                min={1}
                max={50}
                value={slotForm.estimated_duration}
                onChange={(e) => setSlotForm({ ...slotForm, estimated_duration: Number(e.target.value) })}
                style={{ width: '100%', marginTop: 4 }}
              />
            </label>

            <label style={{ display: 'block', marginBottom: 8 }}>
              <strong>Priority (0–99)</strong>
              <input
                type="number"
                min={0}
                max={99}
                value={slotForm.priority}
                onChange={(e) => setSlotForm({ ...slotForm, priority: Number(e.target.value) })}
                style={{ width: '100%', marginTop: 4 }}
              />
            </label>

            <label style={{ display: 'block', marginBottom: 8 }}>
              <strong>Event Type</strong>
              <select
                value={slotForm.event_type}
                onChange={(e) => setSlotForm({ ...slotForm, event_type: e.target.value })}
                style={{ width: '100%', marginTop: 4 }}
              >
                <option value="">None</option>
                {EVENT_TYPES.map((t) => (
                  <option key={t.value} value={t.value}>{t.label}</option>
                ))}
              </select>
            </label>

            {slotForm.event_type === 'job' && (
              <label style={{ display: 'block', marginBottom: 8 }}>
                <strong>Job Code</strong>
                <input
                  type="text"
                  value={slotForm.event_data_code}
                  onChange={(e) => setSlotForm({ ...slotForm, event_data_code: e.target.value })}
                  placeholder="e.g. TASK-42"
                  style={{ width: '100%', marginTop: 4 }}
                />
              </label>
            )}

            {slotForm.event_type === 'system_event' && (
              <label style={{ display: 'block', marginBottom: 8 }}>
                <strong>System Event</strong>
                <select
                  value={slotForm.event_data_event}
                  onChange={(e) => setSlotForm({ ...slotForm, event_data_event: e.target.value })}
                  style={{ width: '100%', marginTop: 4 }}
                >
                  <option value="">Select event</option>
                  <option value="ScheduleToday">Schedule Today</option>
                  <option value="SummaryToday">Summary Today</option>
                  <option value="ScheduledGatewayRestart">Scheduled Gateway Restart</option>
                </select>
              </label>
            )}

            <div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
              <button
                className="btn-primary"
                onClick={handleSaveSlot}
                disabled={slotSaving}
              >
                {slotSaving ? 'Saving...' : 'Save'}
              </button>
              <button className="btn-back" onClick={() => setShowSlotModal(false)}>Cancel</button>
            </div>
          </div>
        </div>
      )}

      {showPlanModal && (
        <div className="modal-overlay" onClick={() => setShowPlanModal(false)}>
          <div className="modal" onClick={(e) => e.stopPropagation()}>
            <h3>{editingPlan ? 'Edit Plan' : 'New Plan'}</h3>

            <label style={{ display: 'block', marginBottom: 8 }}>
              <strong>Slot Type</strong>
              <select
                value={planForm.slot_type}
                onChange={(e) => setPlanForm({ ...planForm, slot_type: e.target.value as SlotType })}
                style={{ width: '100%', marginTop: 4 }}
              >
                {SLOT_TYPES.map((t) => (
                  <option key={t.value} value={t.value}>{t.label}</option>
                ))}
              </select>
            </label>

            <label style={{ display: 'block', marginBottom: 8 }}>
              <strong>At Time</strong>
              <input
                type="time"
                value={planForm.at_time}
                onChange={(e) => setPlanForm({ ...planForm, at_time: e.target.value })}
                style={{ width: '100%', marginTop: 4 }}
              />
            </label>

            <label style={{ display: 'block', marginBottom: 8 }}>
              <strong>Estimated Duration (minutes, 1–50)</strong>
              <input
                type="number"
                min={1}
                max={50}
                value={planForm.estimated_duration}
                onChange={(e) => setPlanForm({ ...planForm, estimated_duration: Number(e.target.value) })}
                style={{ width: '100%', marginTop: 4 }}
              />
            </label>

            <label style={{ display: 'block', marginBottom: 8 }}>
              <strong>On Day (optional)</strong>
              <select
                value={planForm.on_day}
                onChange={(e) => setPlanForm({ ...planForm, on_day: e.target.value as Weekday | '' })}
                style={{ width: '100%', marginTop: 4 }}
              >
                <option value="">Every day</option>
                {WEEKDAYS.map((d) => (
                  <option key={d.value} value={d.value}>{d.label}</option>
                ))}
              </select>
            </label>

            <label style={{ display: 'block', marginBottom: 8 }}>
              <strong>On Week (optional)</strong>
              <select
                value={planForm.on_week}
                onChange={(e) => setPlanForm({ ...planForm, on_week: e.target.value })}
                style={{ width: '100%', marginTop: 4 }}
              >
                <option value="">Every matching week</option>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
              </select>
            </label>

            <label style={{ display: 'block', marginBottom: 8 }}>
              <strong>On Month (optional)</strong>
              <select
                value={planForm.on_month}
                onChange={(e) => setPlanForm({ ...planForm, on_month: e.target.value as MonthName | '' })}
                style={{ width: '100%', marginTop: 4 }}
              >
                <option value="">Every month</option>
                {MONTHS.map((m) => (
                  <option key={m.value} value={m.value}>{m.label}</option>
                ))}
              </select>
            </label>

            <label style={{ display: 'block', marginBottom: 8 }}>
              <strong>Event Type</strong>
              <select
                value={planForm.event_type}
                onChange={(e) => setPlanForm({ ...planForm, event_type: e.target.value })}
                style={{ width: '100%', marginTop: 4 }}
              >
                <option value="">None</option>
                {EVENT_TYPES.map((t) => (
                  <option key={t.value} value={t.value}>{t.label}</option>
                ))}
              </select>
            </label>

            {planForm.event_type === 'job' && (
              <label style={{ display: 'block', marginBottom: 8 }}>
                <strong>Job Code</strong>
                <input
                  type="text"
                  value={planForm.event_data_code}
                  onChange={(e) => setPlanForm({ ...planForm, event_data_code: e.target.value })}
                  placeholder="e.g. TASK-42"
                  style={{ width: '100%', marginTop: 4 }}
                />
              </label>
            )}

            {planForm.event_type === 'system_event' && (
              <label style={{ display: 'block', marginBottom: 8 }}>
                <strong>System Event</strong>
                <select
                  value={planForm.event_data_event}
                  onChange={(e) => setPlanForm({ ...planForm, event_data_event: e.target.value })}
                  style={{ width: '100%', marginTop: 4 }}
                >
                  <option value="">Select event</option>
                  <option value="ScheduleToday">Schedule Today</option>
                  <option value="SummaryToday">Summary Today</option>
                  <option value="ScheduledGatewayRestart">Scheduled Gateway Restart</option>
                </select>
              </label>
            )}

            <div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
              <button className="btn-primary" onClick={handleSavePlan} disabled={planSaving}>
                {planSaving ? 'Saving...' : 'Save Plan'}
              </button>
              <button className="btn-back" onClick={() => setShowPlanModal(false)}>Cancel</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
