import { useEffect, useState } from 'react'
import { api } from '../api/client'
import { ApiError } from '../api/client'
import { useAuth } from '../auth/AuthContext'
import {
  Button,
  Card,
  ErrorText,
  Field,
  Input,
  PageTitle,
  StatusBadge,
  Table,
  TableAction,
  TablePanel,
  TableShell,
} from '../components/ui'
import type { JobScheduleData, Pagination } from '../types/api'

export function JobSchedulesPage() {
  const { uid } = useAuth()
  const [schedules, setSchedules] = useState<JobScheduleData[]>([])
  const [pagination, setPagination] = useState<Pagination | null>(null)
  const [error, setError] = useState('')
  const [form, setForm] = useState({
    template_type: 'placement-scan',
    scope: 'persona',
    scope_id: '',
    cron: '0 9 * * *',
    timezone: 'Asia/Taipei',
    enabled: false,
  })

  const load = async () => {
    setError('')
    try {
      const data = await api.get<{ list: JobScheduleData[]; pagination: Pagination }>(
        '/api/v1/job/schedules',
        { auth: true, query: { page: 1, pageSize: 20 } },
      )
      setSchedules(data.list)
      setPagination(data.pagination)
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '載入失敗')
    }
  }

  useEffect(() => {
    if (uid) setForm((f) => ({ ...f, scope_id: uid }))
    load()
  }, [uid])

  const create = async () => {
    setError('')
    try {
      await api.post('/api/v1/job/schedules', form, { auth: true })
      await load()
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '建立失敗')
    }
  }

  const toggle = async (id: string, enabled: boolean) => {
    const path = enabled ? 'disable' : 'enable'
    await api.post(`/api/v1/job/schedules/${id}/${path}`, {}, { auth: true })
    await load()
  }

  return (
    <div>
      <PageTitle title="Job 排程" subtitle="建立、列表、啟用/停用" />
      <Card className="mb-4 grid gap-3 md:grid-cols-2">
        <Field label="Template Type" hint="建議在海巡研究頁用人設專用排程；此處可手動建立">
          <Input
            value={form.template_type}
            onChange={(e) => setForm((f) => ({ ...f, template_type: e.target.value }))}
            placeholder="placement-scan"
          />
        </Field>
        <Field label="Scope">
          <Input
            value={form.scope}
            onChange={(e) => setForm((f) => ({ ...f, scope: e.target.value }))}
            placeholder="persona"
          />
        </Field>
        <Field label="Cron">
          <Input value={form.cron} onChange={(e) => setForm((f) => ({ ...f, cron: e.target.value }))} />
        </Field>
        <Field label="Scope ID">
          <Input
            value={form.scope_id}
            onChange={(e) => setForm((f) => ({ ...f, scope_id: e.target.value }))}
          />
        </Field>
        <Field label="Timezone">
          <Input
            value={form.timezone}
            onChange={(e) => setForm((f) => ({ ...f, timezone: e.target.value }))}
          />
        </Field>
        <div className="flex flex-wrap gap-2 md:col-span-2">
          <Button onClick={create}>建立定時排程任務</Button>
          <Button variant="ghost" onClick={load}>
            重新載入排程列表
          </Button>
        </div>
        <ErrorText message={error} />
      </Card>
      <TablePanel title="島民服務處排程" count={pagination?.total}>
        <TableShell>
          <Table minWidth="40rem">
            <thead>
              <tr>
                <th>ID</th>
                <th>Cron</th>
                <th>模板</th>
                <th>狀態</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {schedules.map((s) => (
                <tr key={s.id}>
                  <td className="font-mono text-xs">{s.id.slice(0, 8)}…</td>
                  <td className="font-semibold">{s.cron}</td>
                  <td>{s.template_type}</td>
                  <td>
                    <StatusBadge className={s.enabled ? 'ac-status-badge--success' : 'ac-status-badge--muted'}>
                      {s.enabled ? '啟用中' : '已停用'}
                    </StatusBadge>
                  </td>
                  <td>
                    <TableAction variant={s.enabled ? 'danger' : 'link'} onClick={() => toggle(s.id, s.enabled)}>
                      {s.enabled ? '停用' : '啟用'}
                    </TableAction>
                  </td>
                </tr>
              ))}
            </tbody>
          </Table>
        </TableShell>
      </TablePanel>
    </div>
  )
}