import { useEffect, useState } from 'react';
import { Button, Dropdown, message, Spin } from 'antd';
import {
  UserAddOutlined,
  UserDeleteOutlined,
  CheckOutlined,
  CloseOutlined,
  StopOutlined,
  EllipsisOutlined,
} from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { useSocialStore } from '@/stores/social.store';
import { api } from '@/lib/api';
import type { FriendshipStatusResponse } from '@/types/social';
import { getErrorMessage } from '@/utils/getErrorMessage';

interface FriendButtonProps {
  userId: string;
  status?: FriendshipStatusResponse;
  onStatusChange?: () => void;
  size?: 'small' | 'middle' | 'large';
}

export default function FriendButton({ userId, status: statusProp, onStatusChange, size = 'middle' }: FriendButtonProps) {
  const [loading, setLoading] = useState(false);
  const [fetchedStatus, setFetchedStatus] = useState<FriendshipStatusResponse | null>(null);
  const { sendFriendRequest, acceptRequest, declineRequest, cancelRequest, unfriend, blockUser } = useSocialStore();

  // Self-fetch status when not provided by parent
  useEffect(() => {
    if (statusProp) return;
    let cancelled = false;
    api.get(`/social/friends/status/${userId}`).then(({ data }) => {
      if (!cancelled) setFetchedStatus(data);
    }).catch(() => {
      if (!cancelled) setFetchedStatus({ status: 'none' } as FriendshipStatusResponse);
    });
    return () => { cancelled = true; };
  }, [userId, statusProp]);

  const status = statusProp ?? fetchedStatus;
  if (!status) return <Spin size="small" />;

  const handleAction = async (action: () => Promise<void>, successMsg: string) => {
    setLoading(true);
    try {
      await action();
      message.success(successMsg);
      onStatusChange?.();
      // Re-fetch status if self-managed
      if (!statusProp) {
        api.get(`/social/friends/status/${userId}`).then(({ data }) => setFetchedStatus(data)).catch(() => {});
      }
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Action failed'));
    } finally {
      setLoading(false);
    }
  };

  // No friendship
  if (status.status === 'none') {
    return (
      <Button
        type="primary"
        icon={<UserAddOutlined />}
        size={size}
        loading={loading}
        onClick={() => handleAction(() => sendFriendRequest(userId), 'Friend request sent')}
      >
        Add Friend
      </Button>
    );
  }

  // Pending — we sent the request
  if (status.status === 'pending' && status.direction === 'sent') {
    return (
      <Button
        icon={<CloseOutlined />}
        size={size}
        loading={loading}
        onClick={() => handleAction(() => cancelRequest(status.friendshipId!), 'Request cancelled')}
      >
        Cancel Request
      </Button>
    );
  }

  // Pending — they sent us a request
  if (status.status === 'pending' && status.direction === 'received') {
    return (
      <Button.Group>
        <Button
          type="primary"
          icon={<CheckOutlined />}
          size={size}
          loading={loading}
          onClick={() => handleAction(() => acceptRequest(status.friendshipId!), 'Friend request accepted')}
        >
          Accept
        </Button>
        <Button
          icon={<CloseOutlined />}
          size={size}
          loading={loading}
          onClick={() => handleAction(() => declineRequest(status.friendshipId!), 'Request declined')}
        >
          Decline
        </Button>
      </Button.Group>
    );
  }

  // Accepted — friends
  if (status.status === 'accepted') {
    const menuItems: MenuProps['items'] = [
      { key: 'unfriend', icon: <UserDeleteOutlined />, label: 'Unfriend', danger: true,
        onClick: () => handleAction(() => unfriend(userId), 'Unfriended') },
      { key: 'block', icon: <StopOutlined />, label: 'Block', danger: true,
        onClick: () => handleAction(() => blockUser(userId), 'User blocked') },
    ];

    return (
      <Dropdown menu={{ items: menuItems }} trigger={['click']}>
        <Button icon={<CheckOutlined />} size={size}>
          Friends <EllipsisOutlined />
        </Button>
      </Dropdown>
    );
  }

  // Blocked
  if (status.status === 'blocked') {
    return (
      <Button disabled size={size} icon={<StopOutlined />}>
        Blocked
      </Button>
    );
  }

  return null;
}
