import { useState, useEffect } from 'react';
import { Button, message, Tooltip } from 'antd';
import { ThunderboltOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import { getErrorMessage } from '@/utils/getErrorMessage';

interface PokeButtonProps {
  userId: string;
  isFriend: boolean;
  size?: 'small' | 'middle' | 'large';
}

export default function PokeButton({ userId, isFriend, size = 'small' }: PokeButtonProps) {
  const [loading, setLoading] = useState(false);
  const [cooldownSeconds, setCooldownSeconds] = useState<number | null>(null);

  useEffect(() => {
    if (isFriend) {
      checkCooldown();
    }
  }, [userId, isFriend]);

  // Tick down cooldown every minute
  useEffect(() => {
    if (cooldownSeconds === null || cooldownSeconds <= 0) return;
    const timer = setInterval(() => {
      setCooldownSeconds((prev) => {
        if (prev === null || prev <= 60) return null;
        return prev - 60;
      });
    }, 60_000);
    return () => clearInterval(timer);
  }, [cooldownSeconds]);

  const checkCooldown = async () => {
    try {
      const { data } = await api.get(`/social/pokes/cooldown/${userId}`);
      setCooldownSeconds(data.onCooldown ? data.ttlSeconds : null);
    } catch {}
  };

  const handlePoke = async () => {
    setLoading(true);
    try {
      await api.post('/social/pokes', { userId });
      message.success('Poke sent!');
      setCooldownSeconds(24 * 60 * 60);
    } catch (err: unknown) {
      message.error(getErrorMessage(err, 'Failed to send poke'));
    } finally {
      setLoading(false);
    }
  };

  if (!isFriend) return null;

  const onCooldown = cooldownSeconds !== null && cooldownSeconds > 0;
  const hoursLeft = onCooldown ? Math.ceil(cooldownSeconds! / 3600) : 0;

  return (
    <Tooltip title={onCooldown ? `Can poke again in ~${hoursLeft}h` : 'Send a poke!'}>
      <Button
        type="default"
        size={size}
        icon={<ThunderboltOutlined />}
        loading={loading}
        disabled={onCooldown}
        onClick={handlePoke}
      >
        {onCooldown ? `${hoursLeft}h` : 'Poke'}
      </Button>
    </Tooltip>
  );
}
