import { useState, useEffect, useCallback, useRef } from 'react';
import { ConfigProvider, App, Button, Spin, Result, theme } from 'antd';
import { MessageOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import { buildServiceUrl } from '@/lib/service-url';
import { useSettingsStore } from '@/stores/settings.store';
import VolunteerFooterNav from '@/components/VolunteerFooterNav';

const FOOTER_HEIGHT = 44;

interface RCConfig {
  enabled: boolean;
  embedPort: number;
  subdomain: string;
  domain: string;
}

interface RCAuthResponse {
  authToken: string;
  rcUserId: string;
}

export default function VolunteerChatPage() {
  const { settings } = useSettingsStore();

  const [online, setOnline] = useState<boolean | null>(null);
  const [rcConfig, setRcConfig] = useState<RCConfig | null>(null);
  const [authToken, setAuthToken] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const iframeRef = useRef<HTMLIFrameElement>(null);

  const fetchAndAuth = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const [statusRes, configRes] = await Promise.all([
        api.get<{ online: boolean; enabled: boolean }>('/rocketchat/status'),
        api.get<RCConfig>('/rocketchat/config'),
      ]);
      setOnline(statusRes.data.online);
      setRcConfig(configRes.data);

      if (statusRes.data.online && statusRes.data.enabled) {
        const authRes = await api.post<RCAuthResponse>('/rocketchat/auth');
        setAuthToken(authRes.data.authToken);
      }
    } catch {
      setOnline(false);
      setError('Could not connect to chat service');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchAndAuth();
  }, [fetchAndAuth]);

  // Retry postMessage pattern — RC's iframe listener may not be ready on first load
  const retryTimers = useRef<ReturnType<typeof setTimeout>[]>([]);

  const handleIframeLoad = useCallback(() => {
    retryTimers.current.forEach(clearTimeout);
    retryTimers.current = [];

    if (!authToken || !iframeRef.current?.contentWindow) return;

    const sendToken = () => {
      if (!iframeRef.current?.contentWindow) return;
      // Derive target origin from the Rocket.Chat service URL for security
      try {
        if (!rcConfig?.subdomain || !rcConfig?.domain || !rcConfig?.embedPort) return;
        const rcUrl = buildServiceUrl(rcConfig.subdomain, rcConfig.domain, rcConfig.embedPort);
        const targetOrigin = rcUrl ? new URL(rcUrl).origin : '*';
        iframeRef.current.contentWindow.postMessage(
          { event: 'login-with-token', loginToken: authToken },
          targetOrigin,
        );
      } catch {
        // Fallback: don't send if we can't determine origin
      }
    };

    sendToken();
    retryTimers.current.push(setTimeout(sendToken, 1000));
    retryTimers.current.push(setTimeout(sendToken, 3000));
  }, [authToken]);

  useEffect(() => {
    return () => retryTimers.current.forEach(clearTimeout);
  }, []);

  const contentHeight = `calc(100dvh - ${FOOTER_HEIGHT}px)`;

  const renderContent = () => {
    if (loading) {
      return (
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: contentHeight, background: '#0d1b2a' }}>
          <Spin size="large" />
        </div>
      );
    }

    if (!rcConfig?.enabled) {
      return (
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: contentHeight, background: '#0d1b2a' }}>
          <Result
            icon={<MessageOutlined style={{ fontSize: 48 }} />}
            status="info"
            title="Chat Not Available"
            subTitle="Team chat has not been enabled yet."
          />
        </div>
      );
    }

    if (!online || error) {
      return (
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: contentHeight, background: '#0d1b2a' }}>
          <Result
            status="error"
            title="Chat Unavailable"
            subTitle={error || 'Chat service is not running.'}
            extra={<Button type="primary" onClick={fetchAndAuth}>Retry</Button>}
          />
        </div>
      );
    }

    const serviceUrl = buildServiceUrl(rcConfig.subdomain, rcConfig.domain, rcConfig.embedPort);

    return (
      <iframe
        ref={iframeRef}
        src={`${serviceUrl}/channel/general`}
        onLoad={handleIframeLoad}
        style={{
          width: '100%',
          height: contentHeight,
          border: 'none',
          display: 'block',
        }}
        title="Team Chat"
        allow="microphone; camera"
      />
    );
  };

  return (
    <ConfigProvider
      theme={{
        algorithm: theme.darkAlgorithm,
        token: {
          colorPrimary: settings?.publicColorPrimary ?? '#3498db',
          colorBgBase: settings?.publicColorBgBase ?? '#0d1b2a',
          colorBgContainer: settings?.publicColorBgContainer ?? '#1b2838',
          colorBgElevated: settings?.publicColorBgContainer ?? '#1b2838',
          borderRadius: 8,
        },
      }}
    >
      <App>
        <div style={{ height: '100dvh', overflow: 'hidden', background: '#0d1b2a' }}>
          {/* Chat content — RC's full UI provides its own header/nav */}
          {renderContent()}

          {/* Footer nav */}
          <VolunteerFooterNav
            style={{
              position: 'fixed',
              bottom: 0,
              left: 0,
              right: 0,
              zIndex: 1200,
            }}
          />
        </div>
      </App>
    </ConfigProvider>
  );
}
