'use client';

import { useState } from 'react';
import { X } from 'lucide-react';
import type { ScheduledTask } from '../../lib/types';
import { parseCron, cronToHuman } from '../../lib/cron';

interface TaskEditorProps {
  task?: ScheduledTask;
  onSave: (task: ScheduledTask) => void;
  onClose: () => void;
}

export function TaskEditor({ task, onSave, onClose }: TaskEditorProps) {
  const [name, setName] = useState(task?.name || '');
  const [schedule, setSchedule] = useState(task?.schedule || '0 8 * * *');
  const [model, setModel] = useState(task?.model || '');
  const [prompt, setPrompt] = useState(task?.prompt || '');
  const [enabled, setEnabled] = useState(task?.enabled ?? false);
  const [inputType, setInputType] = useState<string>(task?.inputSource?.type || 'static');
  const [inputCommand, setInputCommand] = useState(
    task?.inputSource?.type === 'command' ? task.inputSource.command : ''
  );
  const [inputFilePath, setInputFilePath] = useState(
    task?.inputSource?.type === 'file' ? task.inputSource.path : ''
  );
  const [outputType, setOutputType] = useState<string>(task?.outputAction?.type || 'conversation');

  const cronCheck = parseCron(schedule);
  const humanSchedule = cronCheck.valid ? cronToHuman(schedule) : '';

  const handleSave = () => {
    if (!name.trim() || !prompt.trim() || !cronCheck.valid) return;

    const inputSource = (() => {
      if (inputType === 'command') return { type: 'command' as const, command: inputCommand };
      if (inputType === 'file') return { type: 'file' as const, path: inputFilePath };
      if (inputType === 'clipboard') return { type: 'clipboard' as const };
      return { type: 'static' as const };
    })();

    const outputAction = (() => {
      if (outputType === 'clipboard') return { type: 'clipboard' as const };
      if (outputType === 'notification') return { type: 'notification' as const };
      return { type: 'conversation' as const };
    })();

    const result: ScheduledTask = {
      id: task?.id || crypto.randomUUID(),
      name: name.trim(),
      schedule,
      scheduleHuman: humanSchedule,
      model,
      prompt: prompt.trim(),
      inputSource,
      outputAction,
      enabled,
      lastRun: task?.lastRun,
      runHistory: task?.runHistory || [],
      createdAt: task?.createdAt || Date.now(),
    };

    onSave(result);
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60">
      <div className="w-full max-w-lg rounded-lg border border-white/10 bg-[var(--bg-elevated)] p-5">
        <div className="mb-4 flex items-center justify-between">
          <h2 className="text-lg font-semibold text-[var(--text-primary)]">
            {task ? 'Edit Task' : 'New Scheduled Task'}
          </h2>
          <button
            type="button"
            onClick={onClose}
            className="text-[var(--text-tertiary)] hover:text-[var(--text-primary)]"
          >
            <X size={18} />
          </button>
        </div>

        <div className="space-y-3">
          <div>
            <label className="mb-1 block text-xs text-[var(--text-secondary)]">Name *</label>
            <input
              value={name}
              onChange={e => setName(e.target.value)}
              className="w-full rounded border border-white/10 bg-[var(--surface-card)] px-3 py-1.5 text-sm text-[var(--text-primary)] outline-none"
              placeholder="Morning Brief"
            />
          </div>

          <div>
            <label className="mb-1 block text-xs text-[var(--text-secondary)]">
              Cron Schedule *
            </label>
            <input
              value={schedule}
              onChange={e => setSchedule(e.target.value)}
              className="w-full rounded border border-white/10 bg-[var(--surface-card)] px-3 py-1.5 font-mono text-sm text-[var(--text-primary)] outline-none"
              placeholder="0 8 * * *"
            />
            {cronCheck.valid ? (
              <p className="mt-1 text-[10px] text-[var(--accent-secondary)]">{humanSchedule}</p>
            ) : (
              <p className="mt-1 text-[10px] text-[var(--danger)]">{cronCheck.error}</p>
            )}
          </div>

          <div>
            <label className="mb-1 block text-xs text-[var(--text-secondary)]">
              Model (blank = default)
            </label>
            <input
              value={model}
              onChange={e => setModel(e.target.value)}
              className="w-full rounded border border-white/10 bg-[var(--surface-card)] px-3 py-1.5 text-sm text-[var(--text-primary)] outline-none"
              placeholder="Auto-detect"
            />
          </div>

          <div>
            <label className="mb-1 block text-xs text-[var(--text-secondary)]">Prompt *</label>
            <textarea
              value={prompt}
              onChange={e => setPrompt(e.target.value)}
              rows={4}
              className="w-full resize-y rounded border border-white/10 bg-[var(--surface-card)] px-3 py-1.5 text-sm text-[var(--text-primary)] outline-none"
              placeholder="Use {input} for dynamic input from source"
            />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="mb-1 block text-xs text-[var(--text-secondary)]">
                Input Source
              </label>
              <select
                value={inputType}
                onChange={e => setInputType(e.target.value)}
                className="w-full rounded border border-white/10 bg-[var(--surface-card)] px-3 py-1.5 text-sm text-[var(--text-primary)] outline-none"
              >
                <option value="static">None (static prompt)</option>
                <option value="command">Shell command</option>
                <option value="file">File</option>
                <option value="clipboard">Clipboard</option>
              </select>
            </div>
            <div>
              <label className="mb-1 block text-xs text-[var(--text-secondary)]">
                Output Action
              </label>
              <select
                value={outputType}
                onChange={e => setOutputType(e.target.value)}
                className="w-full rounded border border-white/10 bg-[var(--surface-card)] px-3 py-1.5 text-sm text-[var(--text-primary)] outline-none"
              >
                <option value="conversation">New conversation</option>
                <option value="clipboard">Copy to clipboard</option>
                <option value="notification">Browser notification</option>
              </select>
            </div>
          </div>

          {inputType === 'command' && (
            <div>
              <label className="mb-1 block text-xs text-[var(--text-secondary)]">Command</label>
              <input
                value={inputCommand}
                onChange={e => setInputCommand(e.target.value)}
                className="w-full rounded border border-white/10 bg-[var(--surface-card)] px-3 py-1.5 font-mono text-sm text-[var(--text-primary)] outline-none"
                placeholder="git diff --stat"
              />
            </div>
          )}

          {inputType === 'file' && (
            <div>
              <label className="mb-1 block text-xs text-[var(--text-secondary)]">File Path</label>
              <input
                value={inputFilePath}
                onChange={e => setInputFilePath(e.target.value)}
                className="w-full rounded border border-white/10 bg-[var(--surface-card)] px-3 py-1.5 font-mono text-sm text-[var(--text-primary)] outline-none"
                placeholder="/path/to/file.txt"
              />
            </div>
          )}

          <div className="flex items-center gap-2">
            <input
              type="checkbox"
              checked={enabled}
              onChange={e => setEnabled(e.target.checked)}
              id="task-enabled"
              className="h-4 w-4"
            />
            <label htmlFor="task-enabled" className="text-sm text-[var(--text-secondary)]">
              Enabled
            </label>
          </div>
        </div>

        <div className="mt-5 flex justify-end gap-2">
          <button
            type="button"
            onClick={onClose}
            className="rounded border border-white/10 px-4 py-1.5 text-sm text-[var(--text-secondary)] hover:text-[var(--text-primary)]"
          >
            Cancel
          </button>
          <button
            type="button"
            onClick={handleSave}
            disabled={!name.trim() || !prompt.trim() || !cronCheck.valid}
            className="rounded bg-[var(--accent-primary)] px-4 py-1.5 text-sm text-white disabled:opacity-50"
          >
            Save
          </button>
        </div>
      </div>
    </div>
  );
}
