import { useState } from 'react';
import { Button, App } from 'antd';
import { MessageOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import { useSettingsStore } from '@/stores/settings.store';
import { useChatWidgetStore } from '@/stores/chat-widget.store';
import { getErrorMessage } from '@/utils/getErrorMessage';

interface Props {
  friendId: string;
  isFriend: boolean;
  size?: 'small' | 'middle' | 'large';
}

/**
 * DM button that opens a Rocket.Chat direct message with a friend.
 * Only visible when: (1) RC enabled/online, (2) users are friends, (3) social enabled.
 */
export default function MessageButton({ friendId, isFriend, size = 'middle' }: Props) {
  const { message } = App.useApp();
  const { settings } = useSettingsStore();
  const rcEnabled = useChatWidgetStore((s) => s.rcEnabled);
  const rcOnline = useChatWidgetStore((s) => s.rcOnline);
  const openChannel = useChatWidgetStore((s) => s.openChannel);
  const [loading, setLoading] = useState(false);

  // Hide if RC not enabled/online or not friends or social not enabled
  if (!isFriend || !settings?.enableSocial) return null;
  if (!rcEnabled || !rcOnline) return null;

  const handleClick = async () => {
    setLoading(true);
    try {
      const { data } = await api.post(`/social/profile/${friendId}/dm`);
      // Open chat panel for the DM room
      openChannel(data.roomId);
      message.success('Opening direct message...');
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to open direct message'));
    } finally {
      setLoading(false);
    }
  };

  return (
    <Button
      icon={<MessageOutlined />}
      onClick={handleClick}
      loading={loading}
      size={size}
    >
      Message
    </Button>
  );
}
