import { useState, useEffect } from "react";
import { useDraftSocket } from "~/hooks/useDraftSocket";
import { logger } from "~/lib/logger";

export function meta() {
  return [{ title: "Socket Test - Brackt" }];
}

export default function TestSocket() {
  const [messages, setMessages] = useState<string[]>([]);
  const { isConnected, on, off, emit } = useDraftSocket("test-season-123");

  useEffect(() => {
    // Listen for test messages
    const handleTestMessage = (data: unknown) => {
      logger.log("Received test message:", data);
      setMessages((prev) => [...prev, JSON.stringify(data)]);
    };

    on("test-message", handleTestMessage);

    return () => {
      off("test-message", handleTestMessage);
    };
  }, [on, off]);

  const sendTestMessage = () => {
    emit("test-event", {
      message: "Hello from client!",
      timestamp: new Date().toISOString(),
    });
    setMessages((prev) => [...prev, "Sent: Hello from client!"]);
  };

  return (
    <div className="container mx-auto p-8">
      <h1 className="text-3xl font-bold mb-4">Socket.IO Test Page</h1>
      
      <div className="mb-4">
        <div className="flex items-center gap-2">
          <div
            className={`w-3 h-3 rounded-full ${
              isConnected ? "bg-emerald-500" : "bg-coral-accent"
            }`}
          />
          <span className="font-semibold">
            Status: {isConnected ? "Connected" : "Disconnected"}
          </span>
        </div>
      </div>

      <button
        onClick={sendTestMessage}
        disabled={!isConnected}
        className="px-4 py-2 bg-primary text-primary-foreground rounded hover:bg-primary/90 disabled:bg-muted disabled:text-muted-foreground disabled:cursor-not-allowed"
      >
        Send Test Message
      </button>

      <div className="mt-6">
        <h2 className="text-xl font-semibold mb-2">Messages:</h2>
        <div className="bg-muted p-4 rounded max-h-96 overflow-y-auto">
          {messages.length === 0 ? (
            <p className="text-muted-foreground">No messages yet...</p>
          ) : (
            <ul className="space-y-2">
              {messages.map((msg, idx) => (
                // eslint-disable-next-line react/no-array-index-key
                <li key={idx} className="text-sm font-mono bg-card p-2 rounded">
                  {msg}
                </li>
              ))}
            </ul>
          )}
        </div>
      </div>

      <div className="mt-6 p-4 bg-amber-accent/10 border border-amber-accent/30 rounded">
        <h3 className="font-semibold mb-2">Instructions:</h3>
        <ol className="list-decimal list-inside space-y-1 text-sm">
          <li>Check that the status shows "Connected"</li>
          <li>Open browser console to see connection logs</li>
          <li>Check server logs for "Client connected" message</li>
          <li>Click "Send Test Message" to test two-way communication</li>
        </ol>
      </div>
    </div>
  );
}
