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

type ContextType = {
  selectedTask: any;
};

export default function TaskCode() {
  const { id } = useParams<{ id: string }>();
  const { selectedTask } = useOutletContext<ContextType>();
  const socket = useSocket();
  
  const [currentCode, setCurrentCode] = useState<string>(selectedTask.fileContent);
  const [saveStatus, setSaveStatus] = useState<"saved" | "unsaved" | "saving">("saved");

  useEffect(() => {
    setCurrentCode(selectedTask.fileContent);
  }, [selectedTask]);

  const handleCodeChange = (newCode: string) => {
    setCurrentCode(newCode);
    setSaveStatus("saving");

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

    const taskData = {
      id,
      source: newCode
    };

    socket.emit("l33t_task_save", taskData);
    console.log("Saving task:", taskData);
    
    setTimeout(() => {
      setSaveStatus("saved");
      setTimeout(() => {
        setSaveStatus("unsaved");
      }, 2000);
    }, 500);
  };

  return (
    <div className="h-full flex flex-col px-5">
      <TaskCodeEditor
        onCodeChange={handleCodeChange}
        className="flex-1 min-h-0 border border-indigo-900 rounded-lg overflow-hidden"
        source={selectedTask?.fileContent}
        key={id}
      />
    </div>
  );
}