import { useEffect, useState } from 'react'
import { api, ApiError } from '../api/client'
import { Badge, Button, ErrorText, Field, Notice, Select } from './ui'

export type BrandScanScheduleData = {
  id?: string
  brand_id: string
  cron: string
  timezone: string
  enabled: boolean
  next_run_at?: number
  last_run_at?: number
}

import { CRON_PRESETS } from '../lib/scheduleCatalog'

type Props = {
  brandId: string
  selectedNodeCount: number
}

export function PersonaScanSchedulePanel({ brandId, selectedNodeCount }: Props) {
  const [schedule, setSchedule] = useState<BrandScanScheduleData | null>(null)
  const [cron, setCron] = useState('0 9 * * *')
  const [enabled, setEnabled] = useState(false)
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    if (!brandId) return
    setLoading(true)
    api
      .get<BrandScanScheduleData>(
        `/api/v1/brands/${encodeURIComponent(brandId)}/scan-schedule`,
        { auth: true },
      )
      .then((data) => {
        setSchedule(data)
        setCron(data.cron || '0 9 * * *')
        setEnabled(Boolean(data.enabled))
      })
      .catch((e) => {
        setError(e instanceof ApiError ? e.message : '載入排程失敗')
      })
      .finally(() => setLoading(false))
  }, [brandId])

  const save = async () => {
    if (!brandId) return
    setSaving(true)
    setError('')
    try {
      const data = await api.put<BrandScanScheduleData>(
        `/api/v1/brands/${encodeURIComponent(brandId)}/scan-schedule`,
        { cron, timezone: 'Asia/Taipei', enabled },
        { auth: true },
      )
      setSchedule(data)
      setCron(data.cron)
      setEnabled(data.enabled)
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '儲存排程失敗')
    } finally {
      setSaving(false)
    }
  }

  if (loading) {
    return <p className="text-sm text-ink-secondary">載入定期海巡設定…</p>
  }

  return (
    <div className="ac-island-card space-y-4 p-5">
      <div className="space-y-1">
        <h3 className="text-sm font-bold text-ink">定期雙軌海巡</h3>
        <p className="text-sm leading-relaxed text-ink-secondary">
          依目前勾選的節點自動重跑海巡。請先儲存勾選後再啟用排程。
        </p>
        <div className="flex flex-wrap gap-2">
          <Badge tone={enabled ? 'success' : 'neutral'}>{enabled ? '已啟用' : '未啟用'}</Badge>
          <Badge tone="sky">已勾選 {selectedNodeCount} 節點</Badge>
          {schedule?.next_run_at ? (
            <Badge tone="neutral">
              下次 {new Date(schedule.next_run_at / 1_000_000).toLocaleString('zh-TW')}
            </Badge>
          ) : null}
        </div>
      </div>

      {selectedNodeCount === 0 ? (
        <Notice tone="warning" title="尚未勾選節點" message="排程會使用圖譜中 selected_for_scan 的節點。" />
      ) : null}

      <Field label="執行頻率">
        <Select value={cron} onChange={(e) => setCron(e.target.value)}>
          {CRON_PRESETS.map((preset) => (
            <option key={preset.value} value={preset.value}>
              {preset.label}
            </option>
          ))}
        </Select>
      </Field>

      <label className="flex items-center gap-2 text-sm text-ink">
        <input
          type="checkbox"
          checked={enabled}
          onChange={(e) => setEnabled(e.target.checked)}
          className="h-4 w-4 rounded border-line"
        />
        啟用定期海巡
      </label>

      <Button onClick={() => void save()} disabled={saving}>
        {saving ? '儲存中…' : '儲存排程'}
      </Button>

      <ErrorText message={error} />
    </div>
  )
}