import { useParams, useOutletContext } from "@remix-run/react";
import { useSocket } from "../context";
import { useState, useEffect } from "react";

type ContextType = {
  selectedTask: any;
};

export default function TaskSettings() {
  const { id } = useParams<{ id: string }>();
  const socket = useSocket();
  const { selectedTask } = useOutletContext<ContextType>();

  const [frequency, setFrequency] = useState(selectedTask?.scheduledInterval || 1000);
  const [ttl, setTtl] = useState(selectedTask?.timedTTL || 0); // Add TTL state
  const [autoStart, setAutoStart] = useState(selectedTask?.autoStart || false);
  const [saveStatus, setSaveStatus] = useState<"saved" | "unsaved" | "saving">("saved");

  // Update state when selectedTask changes
  useEffect(() => {
    if (selectedTask) {
      setFrequency(selectedTask.scheduledInterval || 1000);
      setTtl(selectedTask.timedTTL || 0);
      setAutoStart(selectedTask.autoStart || false);
    }
  }, [selectedTask]);

  const handleSave = () => {
    if (!socket || !selectedTask || !id) {
      console.error("Cannot save: missing socket connection or task data");
      return;
    }

    setSaveStatus("saving");

    const taskData = {
      id,
      scheduledInterval: frequency,
      ttl, // Add TTL to save data
      autoStart
    };

    socket.emit("l33t_task_save", taskData);
    console.log("Saving task settings:", taskData);

    // Listen for task update to confirm save
    const handleTaskUpdate = (taskId: string, task: any) => {
      if (taskId === id) {
        setSaveStatus("saved");
        setTimeout(() => {
          setSaveStatus("unsaved");
        }, 2000);
        socket.off("l33t_task_update", handleTaskUpdate);
      }
    };

    socket.on("l33t_task_update", handleTaskUpdate);
  };

  return (
    <div className="p-4">
      <div className="space-y-4">
        <div>
          <label className="block text-sm font-medium mb-2">
            Run Frequency (ms)
          </label>
          <input
            type="number"
            value={frequency}
            onChange={(e) => {
              setFrequency(Number(e.target.value));
              setSaveStatus("unsaved");
            }}
            className="w-full p-2 bg-gray-800 rounded border border-gray-700 text-white"
            min="100"
            step="100"
          />
        </div>

        <div>
          <label className="block text-sm font-medium mb-2">
            TTL Timer (ms)
          </label>
          <input
            type="number"
            value={ttl}
            onChange={(e) => {
              setTtl(Number(e.target.value));
              setSaveStatus("unsaved");
            }}
            className="w-full p-2 bg-gray-800 rounded border border-gray-700 text-white"
            min="0"
            step="100"
            placeholder="0 (no limit)"
          />
          <p className="mt-1 text-sm text-gray-400">
            Set to 0 for no time limit
          </p>
        </div>

        <div className="flex items-center">
          <input
            type="checkbox"
            id="autoStart"
            checked={autoStart}
            onChange={(e) => {
              setAutoStart(e.target.checked);
              setSaveStatus("unsaved");
            }}
            className="mr-2 bg-gray-800 border-gray-700 rounded"
          />
          <label htmlFor="autoStart" className="text-sm font-medium">
            Auto Start
          </label>
        </div>

        <button
          onClick={handleSave}
          className={`py-2 px-4 bg-indigo-900 hover:bg-indigo-700 rounded ${
            saveStatus === "saving" ? "animate-pulse" : ""
          }`}
        >
          {saveStatus === "saving" ? "Saving..." : "Save"}
        </button>
      </div>
    </div>
  );
}