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

export type CopyMissionScanScheduleData = {
  id?: string
  persona_id: string
  mission_id: string
  cron: string
  timezone: string
  enabled: boolean
  next_run_at?: number
  last_run_at?: number
}

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

type Props = {
  personaId: string
  missionId: string
  selectedTagCount: number
  archived?: boolean
}

export function CopyMissionScanSchedulePanel({
  personaId,
  missionId,
  selectedTagCount,
  archived,
}: Props) {
  const [schedule, setSchedule] = useState<CopyMissionScanScheduleData | 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 (!personaId || !missionId) return
    setLoading(true)
    api
      .get<CopyMissionScanScheduleData>(
        `/api/v1/personas/${encodeURIComponent(personaId)}/copy-missions/${encodeURIComponent(missionId)}/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))
  }, [personaId, missionId])

  const save = async () => {
    if (!personaId || !missionId) return
    setSaving(true)
    setError('')
    try {
      const data = await api.put<CopyMissionScanScheduleData>(
        `/api/v1/personas/${encodeURIComponent(personaId)}/copy-missions/${encodeURIComponent(missionId)}/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="space-y-4 rounded-xl border border-line bg-surface-muted/30 p-4">
      <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">已勾選 {selectedTagCount} 標籤</Badge>
          {schedule?.next_run_at ? (
            <Badge tone="neutral">
              下次 {new Date(schedule.next_run_at / 1_000_000).toLocaleString('zh-TW')}
            </Badge>
          ) : null}
        </div>
      </div>

      {archived ? (
        <Notice tone="warning" title="任務已封存" message="封存任務無法啟用定期海巡。" />
      ) : null}

      {selectedTagCount === 0 ? (
        <Notice tone="warning" title="尚未勾選標籤" message="請先儲存搜尋標籤後再啟用排程。" />
      ) : null}

      <Field label="執行頻率">
        <Select value={cron} onChange={(e) => setCron(e.target.value)} disabled={archived}>
          {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)}
          disabled={archived}
          className="h-4 w-4 rounded border-line"
        />
        啟用定期海巡
      </label>

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

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