import { useEffect, useState } from 'react';
import { useParams, Navigate } from 'react-router-dom';
import { Spin, Result } from 'antd';
import { useAuthStore } from '@/stores/auth.store';
import { api } from '@/lib/api';
import axios from 'axios';
import { getErrorMessage } from '@/utils/getErrorMessage';

/**
 * Jitsi TOKEN_AUTH_URL bridge page.
 *
 * When a guest clicks "I am the host" in Jitsi, Jitsi redirects here.
 * This page checks auth, requests a moderator JWT from our API, and
 * redirects back to Jitsi with the token attached.
 */
export default function JitsiAuthPage() {
  const { room } = useParams<{ room: string }>();
  const { isAuthenticated, isLoading } = useAuthStore();
  const [error, setError] = useState<{ status: number; message: string } | null>(null);

  useEffect(() => {
    if (isLoading || !isAuthenticated || !room) return;

    let cancelled = false;

    async function fetchTokenAndRedirect() {
      try {
        const { data } = await api.post<{ token: string; room: string }>('/jitsi/token', { room });

        if (cancelled) return;

        // Derive meet URL: replace "app." prefix with "meet." on the current hostname
        const hostname = window.location.hostname;
        const meetHost = hostname.startsWith('app.')
          ? 'meet.' + hostname.slice(4)
          : hostname;
        const protocol = window.location.protocol;

        window.location.replace(`${protocol}//${meetHost}/${room}?jwt=${data.token}`);
      } catch (err: unknown) {
        if (cancelled) return;
        const status = axios.isAxiosError(err) ? err.response?.status || 500 : 500;
        const msg = getErrorMessage(err, 'Failed to generate meeting token');
        setError({ status, message: msg });
      }
    }

    fetchTokenAndRedirect();

    return () => { cancelled = true; };
  }, [isAuthenticated, isLoading, room]);

  // Still hydrating auth state — show spinner
  if (isLoading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <Spin size="large" />
      </div>
    );
  }

  // Not logged in — redirect to login with return path
  if (!isAuthenticated) {
    return <Navigate to={`/login?redirect=/jitsi-auth/${room}`} replace />;
  }

  // API error
  if (error) {
    const subtitle = error.status === 403
      ? 'Your account does not have permission to host meetings.'
      : error.status === 400
        ? 'Video meetings are not enabled on this platform.'
        : error.message;

    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <Result
          status="error"
          title="Unable to join as host"
          subTitle={subtitle}
        />
      </div>
    );
  }

  // Default: fetching token — show spinner
  return (
    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
      <Spin size="large" tip="Authenticating..." />
    </div>
  );
}
