import { useEffect, useRef } from 'react';
import { Badge, Button, Typography, theme } from 'antd';
import { MessageOutlined, CloseOutlined, CheckOutlined } from '@ant-design/icons';
import {
  useChatWidgetStore,
  CHANNELS,
  MAX_PANELS,
  FAB_LEFT,
  FAB_SIZE,
} from '@/stores/chat-widget.store';

const { Text } = Typography;

/** Bottom of FAB from viewport bottom */
const FAB_BOTTOM = 24;
/** Gap between FAB and the picker panel */
const PICKER_GAP = 8;
/** Panel width */
const PICKER_WIDTH = 200;

export default function ChatWidgetFAB() {
  const { token } = theme.useToken();
  const panels = useChatWidgetStore((s) => s.panels);
  const pickerOpen = useChatWidgetStore((s) => s.pickerOpen);
  const togglePicker = useChatWidgetStore((s) => s.togglePicker);
  const closePicker = useChatWidgetStore((s) => s.closePicker);
  const openChannel = useChatWidgetStore((s) => s.openChannel);
  const panelRef = useRef<HTMLDivElement>(null);
  const fabRef = useRef<HTMLButtonElement>(null);

  const openChannels = new Set(panels.map((p) => p.channel));
  const isFull = panels.length >= MAX_PANELS;

  const handleSelect = (channel: string) => {
    openChannel(channel);
    closePicker();
  };

  // Close on click-outside
  useEffect(() => {
    if (!pickerOpen) return;
    const handler = (e: MouseEvent) => {
      const target = e.target as Node;
      if (
        panelRef.current?.contains(target) ||
        fabRef.current?.contains(target)
      )
        return;
      closePicker();
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [pickerOpen, closePicker]);

  // Close on Escape
  useEffect(() => {
    if (!pickerOpen) return;
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape') closePicker();
    };
    document.addEventListener('keydown', handler);
    return () => document.removeEventListener('keydown', handler);
  }, [pickerOpen, closePicker]);

  // Picker panel bottom: align so it sits just above the FAB
  const pickerBottom = FAB_BOTTOM + FAB_SIZE + PICKER_GAP;

  return (
    <>
      {/* ── Channel picker panel ─────────────────────── */}
      <div
        ref={panelRef}
        style={{
          position: 'fixed',
          bottom: pickerBottom,
          left: FAB_LEFT,
          width: PICKER_WIDTH,
          zIndex: 1051,
          background: token.colorBgElevated,
          borderRadius: token.borderRadiusLG,
          boxShadow: '0 8px 24px rgba(0,0,0,0.35)',
          overflow: 'hidden',
          // animation: scale + slide up from FAB origin
          transformOrigin: 'bottom left',
          transform: pickerOpen ? 'scale(1) translateY(0)' : 'scale(0.75) translateY(12px)',
          opacity: pickerOpen ? 1 : 0,
          pointerEvents: pickerOpen ? 'auto' : 'none',
          transition: 'transform 0.2s cubic-bezier(0.34,1.56,0.64,1), opacity 0.15s ease',
        }}
      >
        {/* Header */}
        <div
          style={{
            padding: '10px 14px',
            borderBottom: `1px solid ${token.colorBorderSecondary}`,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}
        >
          <Text strong style={{ fontSize: 13 }}>Open Channel</Text>
          <CloseOutlined
            style={{ fontSize: 12, color: token.colorTextTertiary, cursor: 'pointer' }}
            onClick={closePicker}
          />
        </div>

        {/* Channel list */}
        <div style={{ padding: '6px 0' }}>
          {CHANNELS.map((ch) => {
            const isOpen = openChannels.has(ch.value);
            const disabled = !isOpen && isFull;
            return (
              <div
                key={ch.value}
                onClick={() => !disabled && handleSelect(ch.value)}
                style={{
                  padding: '8px 14px',
                  cursor: disabled ? 'not-allowed' : 'pointer',
                  opacity: disabled ? 0.4 : 1,
                  display: 'flex',
                  alignItems: 'center',
                  gap: 8,
                  background: isOpen ? token.colorBgTextHover : undefined,
                  transition: 'background 0.15s',
                }}
                onMouseEnter={(e) => {
                  if (!disabled && !isOpen)
                    (e.currentTarget as HTMLDivElement).style.background = token.colorBgTextHover;
                }}
                onMouseLeave={(e) => {
                  if (!isOpen)
                    (e.currentTarget as HTMLDivElement).style.background = 'transparent';
                }}
              >
                <Text style={{ flex: 1, fontSize: 13 }}>#{ch.label}</Text>
                {isOpen && (
                  <CheckOutlined style={{ color: token.colorSuccess, fontSize: 12 }} />
                )}
              </div>
            );
          })}
        </div>
      </div>

      {/* ── FAB button ───────────────────────────────── */}
      <Badge count={panels.length} size="small" offset={[-4, 4]} style={{ position: 'fixed', bottom: FAB_BOTTOM, left: FAB_LEFT, zIndex: 1050 }}>
        <Button
          ref={fabRef}
          type="primary"
          shape="circle"
          icon={pickerOpen ? <CloseOutlined /> : <MessageOutlined />}
          onClick={togglePicker}
          style={{
            position: 'fixed',
            bottom: FAB_BOTTOM,
            left: FAB_LEFT,
            zIndex: 1050,
            width: FAB_SIZE,
            height: FAB_SIZE,
            fontSize: 20,
            boxShadow: '0 4px 12px rgba(0,0,0,0.4)',
            transition: 'transform 0.2s ease',
            transform: pickerOpen ? 'rotate(90deg)' : 'rotate(0deg)',
          }}
        />
      </Badge>
    </>
  );
}
