import React, { useState, useEffect, useCallback } from 'react';
import {
  Clock,
  Plus,
  Trash2,
  X,
  CheckCircle,
  XCircle,
  AlertCircle,
  ChevronDown,
  ChevronRight,
  RefreshCw,
  Pencil,
  Play,
  Pause,
} from 'lucide-react';
import type { CronJob, CronRun } from '@/types/api';
import {
  getCronJobs,
  addCronJob,
  deleteCronJob,
  getCronRuns,
  getCronSettings,
  patchCronSettings,
  patchCronJob,
  runCronJobNow,
  pauseCronJob,
  resumeCronJob,
} from '@/lib/api';
import type { CronSettings } from '@/lib/api';
import { t } from '@/lib/i18n';

function formatDate(iso: string | null): string {
  if (!iso) return '-';
  const d = new Date(iso);
  return d.toLocaleString();
}

function formatDuration(ms: number | null): string {
  if (ms === null || ms === undefined) return '-';
  if (ms < 1000) return `${ms}ms`;
  const secs = ms / 1000;
  if (secs < 60) return `${secs.toFixed(1)}s`;
  return `${(secs / 60).toFixed(1)}m`;
}

function RunHistoryPanel({ jobId }: { jobId: string }) {
  const [runs, setRuns] = useState<CronRun[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchRuns = useCallback(() => {
    setLoading(true);
    setError(null);
    getCronRuns(jobId, 20)
      .then(setRuns)
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  }, [jobId]);

  useEffect(() => { fetchRuns(); }, [fetchRuns]);

  if (loading) {
    return (
      <div className="flex items-center gap-2 px-4 py-3 text-xs" style={{ color: 'var(--pc-text-muted)' }}>
        <div className="h-4 w-4 border-2 rounded-full animate-spin" style={{ borderColor: 'var(--pc-border)', borderTopColor: 'var(--pc-accent)' }} />
        {t('cron.loading_run_history')}
      </div>
    );
  }

  if (error) {
    return (
      <div className="px-4 py-3">
        <div className="flex items-center justify-between">
          <span className="text-xs" style={{ color: 'var(--color-status-error)' }}>
            {t('cron.load_run_history_error')}: {error}
          </span>
          <button
            onClick={fetchRuns}
            className="btn-icon">
            <RefreshCw className="h-3.5 w-3.5" />
          </button>
        </div>
      </div>
    );
  }

  if (runs.length === 0) {
    return (
      <div className="px-4 py-3 flex items-center justify-between">
        <span className="text-xs" style={{ color: 'var(--pc-text-faint)' }}>{t('cron.no_runs')}</span>
        <button
          onClick={fetchRuns}
          className="btn-icon"
        >
          <RefreshCw className="h-3.5 w-3.5" />
        </button>
      </div>
    );
  }

  return (
    <div className="px-4 py-3">
      <div className="flex items-center justify-between mb-2">
        <span className="text-xs font-medium" style={{ color: 'var(--pc-text-secondary)' }}>
          {t('cron.recent_runs')} ({runs.length})
        </span>
        <button
          onClick={fetchRuns}
          className="btn-icon"
          title={t('global.refresh')}
        >
          <RefreshCw className="h-3.5 w-3.5" />
        </button>
      </div>
      <div className="space-y-1.5 max-h-60 overflow-y-auto">
        {runs.map((run) => (
          <div
            key={run.id}
            className="rounded-xl px-3 py-2 text-xs border" style={{ background: 'var(--pc-bg-elevated)', borderColor: 'var(--pc-border)' }}
          >
            <div className="flex items-center justify-between mb-1">
              <div className="flex items-center gap-2">
                {run.status === 'ok' ? (
                  <CheckCircle className="h-3.5 w-3.5" style={{ color: 'var(--color-status-success)' }} />
                ) : (
                  <XCircle className="h-3.5 w-3.5" style={{ color: 'var(--color-status-error)' }} />
                )}
                <span style={{ color: 'var(--pc-text-secondary)' }}>{run.status}</span>
              </div>
              <span style={{ color: 'var(--pc-text-muted)' }}>
                {formatDuration(run.duration_ms)}
              </span>
            </div>
            <div className="flex items-center gap-3" style={{ color: 'var(--pc-text-muted)' }}>
              <span>{formatDate(run.started_at)}</span>
            </div>
            {run.output && (
              <pre className="mt-1.5 rounded-lg p-2 text-xs overflow-x-auto max-h-24 whitespace-pre-wrap break-words font-mono" style={{ background: 'var(--pc-bg-base)', color: 'var(--pc-text-secondary)' }}>
                {run.output}
              </pre>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

export default function Cron() {
  const [jobs, setJobs] = useState<CronJob[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [confirmDelete, setConfirmDelete] = useState<string | null>(null);
  const [expandedJob, setExpandedJob] = useState<string | null>(null);
  const [settings, setSettings] = useState<CronSettings | null>(null);
  const [togglingCatchUp, setTogglingCatchUp] = useState(false);

  // Unified modal: null = closed, 'add' = adding, CronJob = editing
  const [modalJob, setModalJob] = useState<CronJob | 'add' | null>(null);

  // Shared form state for both add and edit
  const [formName, setFormName] = useState('');
  const [formScheduleKind, setFormScheduleKind] = useState<'at' | 'every'>('every');
  const [formScheduleAt, setFormScheduleAt] = useState('');
  const [formScheduleEveryMs, setFormScheduleEveryMs] = useState('60000');
  const [formCommand, setFormCommand] = useState('');
  const [formError, setFormError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [runningJobId, setRunningJobId] = useState<string | null>(null);
  const [togglingJobId, setTogglingJobId] = useState<string | null>(null);
  const [formJobType, setFormJobType] = useState<'shell' | 'agent'>('shell');
  const [formEnabled, setFormEnabled] = useState(true);
  const [formModel, setFormModel] = useState('');
  const [formSessionTarget, setFormSessionTarget] = useState<'isolated' | 'main'>('isolated');
  const [formDeleteAfterRun, setFormDeleteAfterRun] = useState(false);
  const [formAllowedTools, setFormAllowedTools] = useState('');
  const [formDeliveryMode, setFormDeliveryMode] = useState('none');
  const [formDeliveryChannel, setFormDeliveryChannel] = useState('');
  const [formDeliveryTo, setFormDeliveryTo] = useState('');
  const [formDeliveryBestEffort, setFormDeliveryBestEffort] = useState(true);

  const isEditing = modalJob !== null && modalJob !== 'add';

  const openAddModal = () => {
    setFormName('');
    setFormScheduleKind('every');
    setFormScheduleAt('');
    setFormScheduleEveryMs('60000');
    setFormCommand('');
    setFormJobType('shell');
    setFormEnabled(true);
    setFormModel('');
    setFormSessionTarget('isolated');
    setFormDeleteAfterRun(false);
    setFormAllowedTools('');
    setFormDeliveryMode('none');
    setFormDeliveryChannel('');
    setFormDeliveryTo('');
    setFormDeliveryBestEffort(true);
    setFormError(null);
    setModalJob('add');
  };

  const openEditModal = (job: CronJob) => {
    setFormName(job.name ?? '');
    if (job.schedule?.kind === 'at') {
      setFormScheduleKind('at');
      setFormScheduleAt(job.schedule.at ?? '');
      setFormScheduleEveryMs('60000');
    } else if (job.schedule?.kind === 'every') {
      setFormScheduleKind('every');
      setFormScheduleEveryMs(String(job.schedule.every_ms ?? 60000));
      setFormScheduleAt('');
    } else {
      // Legacy cron jobs fallback to "every" in UI to avoid exposing cron syntax.
      setFormScheduleKind('every');
      setFormScheduleEveryMs('60000');
      setFormScheduleAt('');
    }
    setFormCommand(job.prompt ?? job.command);
    setFormJobType(job.job_type === 'agent' ? 'agent' : 'shell');
    setFormEnabled(job.enabled);
    setFormModel(job.model ?? '');
    setFormSessionTarget(job.session_target === 'main' ? 'main' : 'isolated');
    setFormDeleteAfterRun(job.delete_after_run);
    setFormAllowedTools((job.allowed_tools ?? []).join(','));
    setFormDeliveryMode(job.delivery?.mode ?? 'none');
    setFormDeliveryChannel(job.delivery?.channel ?? '');
    setFormDeliveryTo(job.delivery?.to ?? '');
    setFormDeliveryBestEffort(job.delivery?.best_effort ?? true);
    setFormError(null);
    setModalJob(job);
  };

  const closeModal = () => {
    setModalJob(null);
    setFormError(null);
  };

  const fetchJobs = () => {
    setLoading(true);
    getCronJobs().then(setJobs).catch((err) => setError(err.message)).finally(() => setLoading(false));
  };

  const fetchSettings = () => {
    getCronSettings().then(setSettings).catch(() => {});
  };

  const toggleCatchUp = async () => {
    if (!settings) return;
    setTogglingCatchUp(true);
    try {
      const updated = await patchCronSettings({
        catch_up_on_startup: !settings.catch_up_on_startup,
      });
      setSettings(updated);
    } catch {
      // silently fail — user can retry
    } finally {
      setTogglingCatchUp(false);
    }
  };

  useEffect(() => {
    fetchJobs();
    fetchSettings();
  }, []);

  const handleSubmit = async () => {
    const atValue = formScheduleAt.trim();
    const everyMsValue = Number(formScheduleEveryMs);
    // Convert datetime-local value (local time) to a proper UTC ISO string
    const atUtc = atValue ? new Date(atValue).toISOString() : '';
    const schedule =
      formScheduleKind === 'at'
        ? { kind: 'at' as const, at: atUtc }
        : { kind: 'every' as const, every_ms: everyMsValue };

    const scheduleInvalid =
      (formScheduleKind === 'at' && !atValue) ||
      (formScheduleKind === 'every' && (!Number.isFinite(everyMsValue) || everyMsValue <= 0 || !Number.isInteger(everyMsValue)));

    if (scheduleInvalid || !formCommand.trim()) {
      setFormError(t('cron.validation_error'));
      return;
    }
    const allowedTools = formAllowedTools
      .split(',')
      .map((v) => v.trim())
      .filter(Boolean);
    const delivery = formDeliveryMode === 'announce'
      ? {
          mode: 'announce',
          channel: formDeliveryChannel.trim() || undefined,
          to: formDeliveryTo.trim() || undefined,
          best_effort: formDeliveryBestEffort,
        }
      : { mode: 'none' };

    setSubmitting(true);
    setFormError(null);
    try {
      if (isEditing) {
        const updated = await patchCronJob((modalJob as CronJob).id, {
          name: formName.trim() || undefined,
          schedule,
          command: formJobType === 'shell' ? formCommand.trim() : undefined,
          prompt: formJobType === 'agent' ? formCommand.trim() : undefined,
          enabled: formEnabled,
          model: formModel.trim() || undefined,
          session_target: formSessionTarget,
          delete_after_run: formDeleteAfterRun,
          allowed_tools: allowedTools.length > 0 ? allowedTools : undefined,
          delivery,
        });
        setJobs((prev) => prev.map((j) => (j.id === updated.id ? updated : j)));
      } else {
        const job = await addCronJob({
          name: formName.trim() || undefined,
          schedule,
          command: formJobType === 'shell' ? formCommand.trim() : undefined,
          prompt: formJobType === 'agent' ? formCommand.trim() : undefined,
          job_type: formJobType,
          enabled: formEnabled,
          model: formModel.trim() || undefined,
          session_target: formSessionTarget,
          delete_after_run: formDeleteAfterRun,
          allowed_tools: allowedTools.length > 0 ? allowedTools : undefined,
          delivery,
        });
        setJobs((prev) => [...prev, job]);
      }
      closeModal();
    } catch (err: unknown) {
      setFormError(
        err instanceof Error
          ? err.message
          : t(isEditing ? 'cron.edit_error' : 'cron.add_error'),
      );
    } finally {
      setSubmitting(false);
    }
  };

  const handleRunNow = async (job: CronJob) => {
    setRunningJobId(job.id);
    try {
      await runCronJobNow(job.id);
      fetchJobs();
      if (expandedJob === job.id) {
        setExpandedJob(null);
        setTimeout(() => setExpandedJob(job.id), 0);
      }
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : t('cron.run_error'));
    } finally {
      setRunningJobId(null);
    }
  };

  const handleToggleEnabled = async (job: CronJob) => {
    setTogglingJobId(job.id);
    try {
      const updated = job.enabled ? await pauseCronJob(job.id) : await resumeCronJob(job.id);
      setJobs((prev) => prev.map((j) => (j.id === updated.id ? updated : j)));
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : t('cron.toggle_error'));
    } finally {
      setTogglingJobId(null);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await deleteCronJob(id);
      setJobs((prev) => prev.filter((j) => j.id !== id));
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : t('cron.delete_error'));
    } finally {
      setConfirmDelete(null);
    }
  };

  const statusIcon = (status: string | null) => {
    if (!status) return null;
    switch (status.toLowerCase()) {
      case 'ok':
        case 'success':
          return <CheckCircle className="h-4 w-4" style={{ color: 'var(--color-status-success)' }} />;
      case 'error':
        case 'failed':
          return <XCircle className="h-4 w-4" style={{ color: 'var(--color-status-error)' }} />;
      default:
        return <AlertCircle className="h-4 w-4" style={{ color: 'var(--color-status-warning)' }} />;
    }
  };

  if (error) {
    return (
      <div className="p-6 animate-fade-in">
        <div className="rounded-2xl border p-4" style={{ background: 'rgba(239, 68, 68, 0.08)', borderColor: 'rgba(239, 68, 68, 0.2)', color: '#f87171' }}>
          {t('cron.load_error')}: {error}
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="h-8 w-8 border-2 rounded-full animate-spin" style={{ borderColor: 'var(--pc-border)', borderTopColor: 'var(--pc-accent)' }} />
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full p-6 gap-6 animate-fade-in overflow-hidden">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Clock className="h-5 w-5" style={{ color: 'var(--pc-accent)' }} />
          <h2 className="text-sm font-semibold uppercase tracking-wider" style={{ color: 'var(--pc-text-primary)' }}>
            {t('cron.scheduled_tasks')} ({jobs.length})
          </h2>
        </div>
        <button
          onClick={openAddModal}
          className="btn-electric flex items-center gap-2 text-sm px-4 py-2"
        >
          <Plus className="h-4 w-4" />{t('cron.add_job')}
        </button>
      </div>

      {/* Catch-up toggle */}
      {settings && (
        <div className="glass-card px-4 py-3 flex items-center justify-between">
          <div>
            <span className="text-sm font-medium" style={{ color: 'var(--pc-text-primary)' }}>
              {t('cron.catch_up_title')}
            </span>
            <p className="text-xs mt-0.5" style={{ color: 'var(--pc-text-muted)' }}>
              {t('cron.catch_up_desc')}
            </p>
          </div>
          <button
            onClick={toggleCatchUp}
            disabled={togglingCatchUp}
            className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors duration-300 focus:outline-none ${
              settings.catch_up_on_startup
                ? 'bg-[#0080ff]'
                : 'bg-[#1a1a3e]'
            }`}
          >
            <span
              className={`inline-block h-4 w-4 rounded-full bg-white transition-transform duration-300 ${
                settings.catch_up_on_startup
                  ? 'translate-x-6'
                  : 'translate-x-1'
              }`}
            />
          </button>
        </div>
      )}

      {/* Unified Add / Edit Modal */}
      {modalJob !== null && (
        <div className="fixed inset-0 modal-backdrop flex items-center justify-center z-50">
          <div className="surface-panel w-full max-w-md mx-4 animate-fade-in-scale max-h-[calc(100vh-2rem)] flex flex-col">
            <div className="flex items-center justify-between p-6 pb-4">
              <h3 className="text-lg font-semibold" style={{ color: 'var(--pc-text-primary)' }}>
                {isEditing ? t('cron.edit_modal_title') : t('cron.add_modal_title')}
              </h3>
              <button
                onClick={closeModal}
                className="btn-icon"
              >
                <X className="h-5 w-5" />
              </button>
            </div>
            <div className="px-6 pb-2 overflow-y-auto min-h-0">
              {formError && (
                <div className="mb-4 rounded-xl border p-3 text-sm animate-fade-in" style={{ background: 'rgba(239, 68, 68, 0.08)', borderColor: 'rgba(239, 68, 68, 0.2)', color: '#f87171' }}>
                  {formError}
                </div>
              )}
              <div className="space-y-4">
                <div>
                <label className="block text-xs font-semibold mb-1.5 uppercase tracking-wider" style={{ color: 'var(--pc-text-secondary)' }}>
                  {t('cron.name_optional')}
                </label>
                <input type="text" value={formName} onChange={(e) => setFormName(e.target.value)} placeholder={t('cron.name_placeholder')} className="input-electric w-full px-3 py-2.5 text-sm" />
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5 uppercase tracking-wider" style={{ color: 'var(--pc-text-secondary)' }}>
                  {t('cron.schedule_required')} <span style={{ color: 'var(--color-status-error)' }}>*</span>
                </label>
                <div className="space-y-2">
                  <select
                    value={formScheduleKind}
                    onChange={(e) => setFormScheduleKind(e.target.value as 'at' | 'every')}
                    className="input-electric w-full px-3 py-2.5 text-sm"
                  >
                    <option value="at">{t('cron.schedule_kind_at')}</option>
                    <option value="every">{t('cron.schedule_kind_every')}</option>
                  </select>
                  {formScheduleKind === 'at' && (
                    <input
                      type="datetime-local"
                      value={formScheduleAt}
                      onChange={(e) => setFormScheduleAt(e.target.value)}
                      className="input-electric w-full px-3 py-2.5 text-sm"
                    />
                  )}
                  {formScheduleKind === 'every' && (
                    <input
                      type="number"
                      min={1}
                      step={1}
                      value={formScheduleEveryMs}
                      onChange={(e) => setFormScheduleEveryMs(e.target.value)}
                      placeholder={t('cron.schedule_every_ms_placeholder')}
                      className="input-electric w-full px-3 py-2.5 text-sm"
                    />
                  )}
                </div>
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5 uppercase tracking-wider" style={{ color: 'var(--pc-text-secondary)' }}>
                  {t('cron.job_type')}
                </label>
                <select
                  value={formJobType}
                  onChange={(e) => setFormJobType(e.target.value as 'shell' | 'agent')}
                  className="input-electric w-full px-3 py-2.5 text-sm"
                >
                  <option value="shell">{t('cron.job_type_shell')}</option>
                  <option value="agent">{t('cron.job_type_agent')}</option>
                </select>
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5 uppercase tracking-wider" style={{ color: 'var(--pc-text-secondary)' }}>
                  {t('cron.command_required')} <span style={{ color: 'var(--color-status-error)' }}>*</span>
                </label>
                <textarea
                  value={formCommand}
                  onChange={(e) => setFormCommand(e.target.value)}
                  placeholder={formJobType === 'agent' ? t('cron.command_agent_placeholder') : t('cron.command_shell_placeholder')}
                  rows={4}
                  className="input-electric w-full px-3 py-2.5 text-sm resize-y"
                />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <label className="text-xs flex items-center gap-2" style={{ color: 'var(--pc-text-secondary)' }}>
                  <input type="checkbox" checked={formEnabled} onChange={(e) => setFormEnabled(e.target.checked)} />
                  {t('cron.enable_job')}
                </label>
                <label className="text-xs flex items-center gap-2" style={{ color: 'var(--pc-text-secondary)' }}>
                  <input type="checkbox" checked={formDeleteAfterRun} onChange={(e) => setFormDeleteAfterRun(e.target.checked)} />
                  {t('cron.delete_after_run')}
                </label>
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5 uppercase tracking-wider" style={{ color: 'var(--pc-text-secondary)' }}>
                  {t('cron.session_target')}
                </label>
                <select value={formSessionTarget} onChange={(e) => setFormSessionTarget(e.target.value as 'isolated' | 'main')} className="input-electric w-full px-3 py-2.5 text-sm">
                  <option value="isolated">{t('cron.session_target_isolated')}</option>
                  <option value="main">{t('cron.session_target_main')}</option>
                </select>
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5 uppercase tracking-wider" style={{ color: 'var(--pc-text-secondary)' }}>
                  {t('cron.model_optional')}
                </label>
                <input type="text" value={formModel} onChange={(e) => setFormModel(e.target.value)} placeholder={t('cron.model_placeholder')} className="input-electric w-full px-3 py-2.5 text-sm" />
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5 uppercase tracking-wider" style={{ color: 'var(--pc-text-secondary)' }}>
                  {t('cron.allowed_tools')}
                </label>
                <input type="text" value={formAllowedTools} onChange={(e) => setFormAllowedTools(e.target.value)} placeholder={t('cron.allowed_tools_placeholder')} className="input-electric w-full px-3 py-2.5 text-sm" />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-semibold mb-1.5 uppercase tracking-wider" style={{ color: 'var(--pc-text-secondary)' }}>
                    {t('cron.delivery_mode')}
                  </label>
                  <select value={formDeliveryMode} onChange={(e) => setFormDeliveryMode(e.target.value)} className="input-electric w-full px-3 py-2.5 text-sm">
                    <option value="none">{t('cron.delivery_mode_none')}</option>
                    <option value="announce">{t('cron.delivery_mode_announce')}</option>
                  </select>
                </div>
                <label className="text-xs flex items-end gap-2 pb-2" style={{ color: 'var(--pc-text-secondary)' }}>
                  <input type="checkbox" checked={formDeliveryBestEffort} onChange={(e) => setFormDeliveryBestEffort(e.target.checked)} />
                  {t('cron.delivery_best_effort')}
                </label>
              </div>
              {formDeliveryMode === 'announce' && (
                <div className="grid grid-cols-2 gap-3">
                  <input type="text" value={formDeliveryChannel} onChange={(e) => setFormDeliveryChannel(e.target.value)} placeholder={t('cron.delivery_channel')} className="input-electric w-full px-3 py-2.5 text-sm" />
                  <input type="text" value={formDeliveryTo} onChange={(e) => setFormDeliveryTo(e.target.value)} placeholder={t('cron.delivery_target')} className="input-electric w-full px-3 py-2.5 text-sm" />
                </div>
              )}
              </div>
            </div>
            <div className="flex justify-end gap-3 p-6 pt-4">
              <button
                onClick={closeModal}
                className="btn-secondary px-4 py-2 text-sm font-medium"
              >
                {t('cron.cancel')}
              </button>
              <button
                onClick={handleSubmit}
                disabled={submitting}
                className="btn-electric px-4 py-2 text-sm font-medium"
              >
                {submitting
                  ? t(isEditing ? 'cron.saving' : 'cron.adding')
                  : t(isEditing ? 'cron.save' : 'cron.add_job')}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Jobs Table */}
      {jobs.length === 0 ? (
        <div className="card p-8 text-center">
          <Clock className="h-10 w-10 mx-auto mb-3" style={{ color: 'var(--pc-text-faint)' }} />
          <p style={{ color: 'var(--pc-text-muted)' }}>{t('cron.empty')}</p>
        </div>
      ) : (
        <div className="card overflow-auto rounded-2xl flex-1 min-h-0">
          <table className="table-electric">
            <thead>
              <tr>
                <th>{t('cron.id')}</th>
                <th>{t('cron.name')}</th>
                <th>{t('cron.command')}</th>
                <th>{t('cron.next_run')}</th>
                <th>{t('cron.last_status')}</th>
                <th>{t('cron.enabled')}</th>
                <th className="text-right">{t('cron.actions')}</th>
              </tr>
            </thead>
            <tbody>
              {jobs.map((job) => (
                <React.Fragment key={job.id}>
                  <tr>
                    <td className="font-mono text-xs">
                      <button
                        onClick={() =>
                          setExpandedJob((prev) =>
                            prev === job.id ? null : job.id,
                          )
                      }
                        className="flex items-center gap-1 btn-icon"
                        title={t('cron.toggle_run_history')}
                      >
                        {expandedJob === job.id ? (
                          <ChevronDown className="h-3.5 w-3.5" />
                        ) : (
                          <ChevronRight className="h-3.5 w-3.5" />
                        )}
                        {job.id.slice(0, 8)}
                      </button>
                    </td>
                    <td className="font-medium text-sm" style={{ color: 'var(--pc-text-primary)' }}>
                      {job.name ?? '-'}
                    </td>
                    <td className="font-mono text-xs max-w-[200px] truncate" style={{ color: 'var(--pc-text-secondary)' }}>
                      {job.prompt ?? job.command}
                    </td>
                    <td className="text-xs" style={{ color: 'var(--pc-text-muted)' }}>
                      {formatDate(job.next_run)}
                    </td>
                    <td>
                      <div className="flex items-center gap-1.5">
                        {statusIcon(job.last_status)}
                        <span className="text-xs capitalize" style={{ color: 'var(--pc-text-secondary)' }}>
                          {job.last_status ?? '-'}
                        </span>
                      </div>
                    </td>
                    <td>
                      <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-[10px] font-semibold border"
                        style={job.enabled ? { color: 'var(--color-status-success)', borderColor: 'rgba(0, 230, 138, 0.2)', background: 'rgba(0, 230, 138, 0.06)' } : { color: 'var(--pc-text-faint)', borderColor: 'var(--pc-border)', background: 'transparent' }}>
                        {job.enabled ? t('cron.enabled_status') : t('cron.disabled_status')}
                      </span>
                    </td>
                    <td className="text-right">
                      <div className="flex items-center justify-end gap-2">
                        <button
                          onClick={() => handleRunNow(job)}
                          className="btn-icon"
                          title={t('cron.run_now')}
                          disabled={runningJobId === job.id}
                        >
                          <Play className="h-4 w-4" />
                        </button>
                        <button
                          onClick={() => handleToggleEnabled(job)}
                          className="btn-icon"
                          title={job.enabled ? t('cron.pause_job') : t('cron.resume_job')}
                          disabled={togglingJobId === job.id}
                        >
                          {job.enabled ? <Pause className="h-4 w-4" /> : <Play className="h-4 w-4" />}
                        </button>
                        <button
                          onClick={() => openEditModal(job)}
                          className="btn-icon"
                          title={t('cron.edit')}
                        >
                          <Pencil className="h-4 w-4" />
                        </button>
                        {confirmDelete === job.id ? (
                          <div className="flex items-center justify-end gap-2 animate-fade-in">
                            <span className="text-xs" style={{ color: 'var(--color-status-error)' }}>
                              {t('cron.confirm_delete')}
                            </span>
                            <button
                              onClick={() => handleDelete(job.id)}
                              className="text-xs font-medium"
                              style={{ color: 'var(--color-status-error)' }}
                            >
                              {t('cron.yes')}
                            </button>
                            <button
                              onClick={() => setConfirmDelete(null)}
                              className="text-xs font-medium"
                              style={{ color: 'var(--pc-text-muted)' }}
                            >
                              {t('cron.no')}
                            </button>
                          </div>
                        ) : (
                          <button
                            onClick={() => setConfirmDelete(job.id)}
                            className="btn-icon"
                          >
                            <Trash2 className="h-4 w-4" />
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                  {expandedJob === job.id && (
                    <tr>
                      <td colSpan={7} style={{ background: 'var(--pc-bg-elevated)' }}>
                        <RunHistoryPanel jobId={job.id} />
                      </td>
                    </tr>
                  )}
                </React.Fragment>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
