import { useEffect, useCallback, useRef } from 'react';
import { api } from '@/lib/api';
import { buildServiceUrl } from '@/lib/service-url';
import {
  useChatWidgetStore,
  FAB_LEFT,
  FAB_SIZE,
  PANEL_GAP,
  PANEL_EXPANDED_WIDTH,
  PANEL_MINIMIZED_WIDTH,
} from '@/stores/chat-widget.store';
import ChatPanel from './ChatPanel';

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

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

/**
 * Container that:
 * 1. Fetches RC auth once (shared across all panels)
 * 2. Computes left offsets and renders <ChatPanel> instances
 */
export default function ChatPanelTray() {
  const panels = useChatWidgetStore((s) => s.panels);
  const rcServiceUrl = useChatWidgetStore((s) => s.rcServiceUrl);
  const setRCState = useChatWidgetStore((s) => s.setRCState);
  const initAttempted = useRef(false);

  const initRC = useCallback(async () => {
    if (initAttempted.current) return;
    initAttempted.current = true;

    try {
      const [statusRes, rcConfigRes] = await Promise.all([
        api.get<{ online: boolean; enabled: boolean }>('/rocketchat/status'),
        api.get<RCConfig>('/rocketchat/config'),
      ]);

      if (!rcConfigRes.data.enabled) {
        setRCState({
          serviceUrl: '',
          authToken: '',
          enabled: false,
          online: false,
        });
        return;
      }
      if (!statusRes.data.online) {
        setRCState({
          serviceUrl: '',
          authToken: '',
          enabled: true,
          online: false,
        });
        return;
      }

      const authRes = await api.post<RCAuthResponse>('/rocketchat/auth');
      const serviceUrl = buildServiceUrl(
        rcConfigRes.data.subdomain,
        rcConfigRes.data.domain,
        rcConfigRes.data.embedPort,
      );

      setRCState({
        serviceUrl,
        authToken: authRes.data.authToken,
        enabled: rcConfigRes.data.enabled,
        online: statusRes.data.online,
      });
    } catch {
      // Auth failure — panels will show loading spinner
      setRCState({
        serviceUrl: '',
        authToken: '',
        enabled: true,
        online: false,
      });
    }
  }, [setRCState]);

  // Initialize RC when first panel opens and we don't have state yet
  useEffect(() => {
    if (panels.length > 0 && !rcServiceUrl) {
      initRC();
    }
  }, [panels.length, rcServiceUrl, initRC]);

  // Compute left offsets: FAB_LEFT + FAB_SIZE + GAP, then accumulate
  const TRAY_START = FAB_LEFT + FAB_SIZE + PANEL_GAP;
  let cursor = TRAY_START;
  const offsets: number[] = [];

  for (const panel of panels) {
    offsets.push(cursor);
    const w = panel.isMinimized ? PANEL_MINIMIZED_WIDTH : PANEL_EXPANDED_WIDTH;
    cursor += w + PANEL_GAP;
  }

  return (
    <>
      {panels.map((panel, i) => (
        <ChatPanel key={panel.id} panel={panel} leftOffset={offsets[i] ?? 0} />
      ))}
    </>
  );
}
