import { useState } from "react";
import { api } from "../lib/api";
import { useNavigate } from "react-router";

interface Session {
  id: string;
  appId: string;
  userId: string | null;
  mode: "stream" | "local";
  status: "starting" | "started" | "ending" | "ended";
  tier: "demo" | "prod";
  serverId: string | null;
  appPid: number | null;
  cirrusPid: number | null;
  streamerPort: number | null;
  playerPort: number | null;
  sfuPort: number | null;
  startAt: string;
  endAt: string | null;
}

function TestPage() {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const navigate = useNavigate();

  const handleStartSession = async () => {
    setIsLoading(true);
    setError(null);

    try {
      const response = await api
        .post("sessions", {
          json: {
            appId: "c1a06420-ca72-4a89-893e-3fe669bbbb99",
            mode: "stream",
            tier: "demo",
          },
        })
        .json<{ session: Session }>();

      // Перенаправляем на страницу сессии
      navigate(`/sessions/${response.session.id}`);
    } catch (err) {
      console.error("Failed to start session:", err);
      setError(
        err instanceof Error ? err.message : "Не удалось запустить приложение"
      );
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="flex flex-col justify-center items-center p-4 min-h-screen bg-gray-50">
      <div className="p-8 w-full max-w-md bg-white rounded-lg shadow-md">
        <h1 className="mb-4 text-2xl font-bold text-gray-900">
          Тестовая страница
        </h1>
        <p className="mb-6 text-gray-600">
          Запустите демо-приложение без авторизации
        </p>

        <button
          onClick={handleStartSession}
          disabled={isLoading}
          className="px-4 py-3 w-full font-medium text-white bg-blue-600 rounded-lg transition-colors hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
        >
          {isLoading ? "Запуск..." : "Запустить приложение"}
        </button>

        {error && (
          <div className="p-3 mt-4 text-sm text-red-700 bg-red-100 rounded-lg">
            {error}
          </div>
        )}
      </div>
    </div>
  );
}

export default TestPage;
