import { useEffect, useCallback, useRef, useState } from 'react';
import { Spin, Typography, theme } from 'antd';
import {
  CloseOutlined,
  MinusOutlined,
  ExpandOutlined,
  LinkOutlined,
} from '@ant-design/icons';
import {
  useChatWidgetStore,
  CHANNELS,
  PANEL_EXPANDED_WIDTH,
  PANEL_EXPANDED_HEIGHT,
  PANEL_MINIMIZED_WIDTH,
  PANEL_TITLE_HEIGHT,
  type ChatPanel as ChatPanelType,
} from '@/stores/chat-widget.store';

const { Text } = Typography;

interface Props {
  panel: ChatPanelType;
  leftOffset: number;
}

export default function ChatPanel({ panel, leftOffset }: Props) {
  const { token } = theme.useToken();
  const rcServiceUrl = useChatWidgetStore((s) => s.rcServiceUrl);
  const rcAuthToken = useChatWidgetStore((s) => s.rcAuthToken);
  const rcEnabled = useChatWidgetStore((s) => s.rcEnabled);
  const rcOnline = useChatWidgetStore((s) => s.rcOnline);
  const closePanel = useChatWidgetStore((s) => s.closePanel);
  const minimizePanel = useChatWidgetStore((s) => s.minimizePanel);
  const expandPanel = useChatWidgetStore((s) => s.expandPanel);

  const [iframeReady, setIframeReady] = useState(false);
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const retryTimers = useRef<ReturnType<typeof setTimeout>[]>([]);

  const channelLabel =
    CHANNELS.find((c) => c.value === panel.channel)?.label ?? panel.channel;

  // iframe auth via postMessage with retry
  const handleIframeLoad = useCallback(() => {
    retryTimers.current.forEach(clearTimeout);
    retryTimers.current = [];

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

    const sendToken = () => {
      if (!iframeRef.current?.contentWindow || !rcServiceUrl) return;
      const targetOrigin = new URL(rcServiceUrl).origin;
      iframeRef.current.contentWindow.postMessage(
        { event: 'login-with-token', loginToken: rcAuthToken },
        targetOrigin,
      );
    };

    sendToken();
    retryTimers.current.push(setTimeout(sendToken, 1000));
    retryTimers.current.push(setTimeout(sendToken, 3000));
    setIframeReady(true);
  }, [rcAuthToken]);

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

  const handlePopOut = () => {
    if (rcServiceUrl) window.open(`${rcServiceUrl}/channel/${panel.channel}`, '_blank');
  };

  const width = panel.isMinimized ? PANEL_MINIMIZED_WIDTH : PANEL_EXPANDED_WIDTH;
  const height = panel.isMinimized ? PANEL_TITLE_HEIGHT : PANEL_EXPANDED_HEIGHT;

  // Determine content state
  const isLoading = rcEnabled === null;
  const isNotEnabled = rcEnabled === false;
  const isOffline = rcEnabled && rcOnline === false;
  const isReady = rcServiceUrl && rcAuthToken && rcEnabled && rcOnline;

  const renderContent = () => {
    if (isNotEnabled) {
      return (
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16, textAlign: 'center' }}>
          <Text type="secondary">Chat not enabled</Text>
        </div>
      );
    }
    if (isOffline) {
      return (
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16, textAlign: 'center' }}>
          <Text type="secondary">Chat offline</Text>
        </div>
      );
    }
    if (isLoading || !isReady) {
      return (
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Spin />
        </div>
      );
    }
    return (
      <>
        {!iframeReady && (
          <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Spin />
          </div>
        )}
        <iframe
          ref={iframeRef}
          src={`${rcServiceUrl}/channel/${panel.channel}?layout=embedded`}
          onLoad={handleIframeLoad}
          style={{
            flex: 1,
            width: '100%',
            border: 'none',
            display: iframeReady ? 'block' : 'none',
          }}
          title={`Chat: #${channelLabel}`}
          allow="microphone; camera"
        />
      </>
    );
  };

  return (
    <div
      style={{
        position: 'fixed',
        bottom: 0,
        left: leftOffset,
        zIndex: 1050,
        width,
        height,
        display: 'flex',
        flexDirection: 'column',
        background: token.colorBgContainer,
        borderRadius: '12px 12px 0 0',
        border: `1px solid ${token.colorBorder}`,
        borderBottom: 'none',
        overflow: 'hidden',
        transition: 'width 0.25s ease, height 0.25s ease, left 0.25s ease',
        boxShadow: '0 -4px 20px rgba(0,0,0,0.3)',
      }}
    >
      {/* Title bar */}
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: 8,
          padding: '0 12px',
          background: token.colorBgElevated,
          borderBottom: panel.isMinimized ? 'none' : `1px solid ${token.colorBorder}`,
          cursor: 'pointer',
          userSelect: 'none',
          minHeight: PANEL_TITLE_HEIGHT,
          flexShrink: 0,
        }}
        onClick={() =>
          panel.isMinimized
            ? expandPanel(panel.id)
            : minimizePanel(panel.id)
        }
      >
        <Text
          strong
          ellipsis
          style={{
            flex: 1,
            minWidth: 0,
            fontSize: 13,
            pointerEvents: 'none',
          }}
        >
          #{channelLabel}
        </Text>

        <div
          style={{ display: 'flex', gap: 8, alignItems: 'center', flexShrink: 0 }}
          onClick={(e) => e.stopPropagation()}
        >
          {panel.isMinimized ? (
            <ExpandOutlined
              style={{ fontSize: 12, color: token.colorTextSecondary, cursor: 'pointer' }}
              onClick={() => expandPanel(panel.id)}
            />
          ) : (
            <MinusOutlined
              style={{ fontSize: 12, color: token.colorTextSecondary, cursor: 'pointer' }}
              onClick={() => minimizePanel(panel.id)}
            />
          )}
          <LinkOutlined
            style={{ fontSize: 12, color: token.colorTextSecondary, cursor: 'pointer' }}
            onClick={handlePopOut}
          />
          <CloseOutlined
            style={{ fontSize: 12, color: token.colorTextSecondary, cursor: 'pointer' }}
            onClick={() => closePanel(panel.id)}
          />
        </div>
      </div>

      {/* Content area — only when expanded */}
      {!panel.isMinimized && renderContent()}
    </div>
  );
}
