import { useEffect, useState } from 'react';
import { api } from '../../api/client';
import type { FleetTask } from '../../types';
import NeonCard from '../NeonCard/NeonCard';

const ACTIONS = ['sysinfo', 'full_sys_check', 'powershell', 'exec', 'pause', 'resume', 'restart'];
const TRIGGERS = ['on_connect', 'on_reconnect', 'interval_hours', 'cron'] as const;

const emptyTask = (): FleetTask => ({
  name: '',
  enabled: true,
  trigger: 'on_connect',
  action: 'sysinfo',
  interval_hours: 24,
  cron_time: '09:00',
  command: '',
});

export default function FleetTasksPanel() {
  const [tasks, setTasks] = useState<FleetTask[]>([]);
  const [draft, setDraft] = useState<FleetTask>(emptyTask());
  const [msg, setMsg] = useState('');
  const [loading, setLoading] = useState(true);

  const load = () => {
    api.getFleetTasks().then(setTasks).catch(() => setTasks([])).finally(() => setLoading(false));
  };

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

  const save = async () => {
    setMsg('');
    if (!draft.name.trim()) {
      setMsg('Name is required');
      return;
    }
    try {
      await api.saveFleetTask(draft);
      setDraft(emptyTask());
      load();
      setMsg('Task saved.');
    } catch (e) {
      setMsg(e instanceof Error ? e.message : String(e));
    }
  };

  const remove = async (id: string) => {
    await api.deleteFleetTask(id);
    load();
  };

  return (
    <NeonCard accent="amber" tilt3d={false}>
      <h3 className="font-tech" style={{ fontSize: '0.75rem', marginBottom: '0.25rem', letterSpacing: '0.08em' }}>FLEET TASKS</h3>
      <p style={{ color: 'var(--clr-dim)', fontSize: '0.75rem', marginBottom: '0.75rem' }}>Scheduled remote actions on connect / interval</p>
      {loading ? <p className="font-tech">Loading…</p> : (
        <>
          <ul style={{ listStyle: 'none', padding: 0, margin: '0 0 1rem' }}>
            {tasks.length === 0 && <li style={{ color: 'var(--clr-dim)', fontSize: '0.85rem' }}>No tasks configured.</li>}
            {tasks.map((t) => (
              <li key={t.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '0.35rem 0', borderBottom: '1px solid #222' }}>
                <span>
                  <strong>{t.name}</strong>
                  <span style={{ color: 'var(--clr-dim)', marginLeft: '0.5rem', fontSize: '0.75rem' }}>
                    {t.trigger} → {t.action}{!t.enabled && ' (off)'}
                  </span>
                </span>
                <span>
                  <button type="button" className="btn btn-outline btn-sm" onClick={() => setDraft(t)}>Edit</button>
                  {' '}
                  <button type="button" className="btn btn-outline btn-sm" onClick={() => t.id && remove(t.id)}>Delete</button>
                </span>
              </li>
            ))}
          </ul>
          <div className="form-grid" style={{ gap: '0.5rem' }}>
            <input className="input" placeholder="Task name" value={draft.name} onChange={(e) => setDraft({ ...draft, name: e.target.value })} />
            <select className="input" value={draft.trigger} onChange={(e) => setDraft({ ...draft, trigger: e.target.value as FleetTask['trigger'] })}>
              {TRIGGERS.map((tr) => <option key={tr} value={tr}>{tr}</option>)}
            </select>
            <select className="input" value={draft.action} onChange={(e) => setDraft({ ...draft, action: e.target.value })}>
              {ACTIONS.map((a) => <option key={a} value={a}>{a}</option>)}
            </select>
            {draft.trigger === 'interval_hours' && (
              <input className="input" type="number" min={0.25} step={0.25} placeholder="Interval hours"
                value={draft.interval_hours ?? 24}
                onChange={(e) => setDraft({ ...draft, interval_hours: parseFloat(e.target.value) || 24 })} />
            )}
            {draft.trigger === 'cron' && (
              <input className="input mono" placeholder="HH:MM daily" value={draft.cron_time ?? ''} onChange={(e) => setDraft({ ...draft, cron_time: e.target.value })} />
            )}
            {(draft.action === 'powershell' || draft.action === 'exec') && (
              <input className="input mono" placeholder="Command payload" value={draft.command ?? ''} onChange={(e) => setDraft({ ...draft, command: e.target.value })} />
            )}
            <label style={{ display: 'flex', alignItems: 'center', gap: '0.4rem', fontSize: '0.85rem' }}>
              <input type="checkbox" checked={draft.enabled} onChange={(e) => setDraft({ ...draft, enabled: e.target.checked })} />
              Enabled
            </label>
            <button type="button" className="btn btn-primary" onClick={save}>Save task</button>
          </div>
          {msg && <p style={{ marginTop: '0.5rem', fontSize: '0.85rem', color: msg.includes('required') || msg.includes('API') ? '#f66' : '#0f8' }}>{msg}</p>}
        </>
      )}
    </NeonCard>
  );
}
