import { useNavigate, Link, Outlet, useLoaderData, useParams, useLocation } from "@remix-run/react";
import { useEffect, useState } from "react";
import TimedStatus from "../components/TimedStatus";
import { useSocket } from "../context";
import { loaderAgentById } from "../loaders";
import type { L33tAgent } from "l33t-lib";

export const loader = loaderAgentById;

export default function StreamDetail() {
  const navigate = useNavigate();
  const location = useLocation();
  const { id } = useParams<{ id: string }>();
  const initialAgent = useLoaderData<typeof loader>();
  const [agent, setAgent] = useState<L33tAgent>(initialAgent);
  const socket = useSocket();

  // Update agent state when route changes
  useEffect(() => {
    setAgent(initialAgent);
  }, [initialAgent]);

  // Socket update handler
  useEffect(() => {
    if (!socket) return;

    const handleL33tUpdate = (agentId: string, updatedAgent: L33tAgent) => {
      if (agentId === id) {
        console.log("Updating agent:", agentId, updatedAgent);
        setAgent(updatedAgent);
      }
    };

    socket.on("l33t_update", handleL33tUpdate);
    
    // Cleanup socket listener
    return () => {
      socket.off("l33t_update", handleL33tUpdate);
    };
  }, [socket, id]);

  // Escape key handler
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        navigate("..");
      }
    };

    document.addEventListener("keydown", handleKeyDown);
    return () => {
      document.removeEventListener("keydown", handleKeyDown);
    };
  }, [navigate]);

  if (!agent) {
    return <div>Loading...</div>;
  }

  return (
    <div className="fixed flex-col max-w-3xl top-0 right-0
                    from-[rgba(49,46,129,0.9)] visa-[rgba(0,0,0,1)]  to-[rgba(0,0,0,0.8)] bg-gradient-to-tl
                    w-3/5 min-h-full h-full 
                    bg-opacity-00 drop-shadow-2xl text-white">
      <div className="rounded-lg p-6 w-full max-h-screen overflow-y-auto">
        <div className="flex items-center content-center mb-4">
          <h2 className="text-2xl font-bold mb-0"> {id}</h2>
          <TimedStatus className="ml-auto" timed={agent} />
        </div>

        <ul className="flex mb-4 text-sm text-center text-white-500">
          <li className="me-2">
            <Link 
              to="detections" 
              className={`inline-flex items-center justify-center p-4 border-b-2 rounded-t-lg group
                ${location.pathname.includes('/detections') 
                  ? 'text-gray-100 border-gray-300' 
                  : 'text-gray-400 border-transparent hover:text-gray-100 hover:border-gray-300'}`}
            >
              <i className="fa-light fa-xl fa-gauge me-2"></i>Detections
            </Link>
          </li>

          <li className="me-2">
            <Link 
              to="areas" 
              className={`inline-flex items-center justify-center p-4 border-b-2 rounded-t-lg group
                ${location.pathname.includes('/areas') 
                  ? 'text-gray-100 border-gray-300' 
                  : 'text-gray-400 border-transparent hover:text-gray-100 hover:border-gray-300'}`}
            >
              <i className="fa-light fa-xl fa-cubes-stacked me-2"></i>Areas
            </Link>
          </li>

          <li className="me-2">
            <Link 
              to="image" 
              className={`inline-flex items-center justify-center p-4 border-b-2 rounded-t-lg group
                ${location.pathname.includes('/image') 
                  ? 'text-gray-100 border-gray-300' 
                  : 'text-gray-400 border-transparent hover:text-gray-100 hover:border-gray-300'}`}
            >
              <i className="fa-duotone fa-xl fa-solid fa-sliders-up me-2"></i>Image
            </Link>
          </li>
        </ul>

        <Outlet />
      </div>
    </div>
  );
}