'use client';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import type React from 'react';
import { useAsyncFn } from '@/hooks/tools';
import { useStreamChatStore } from '@/app/(main)/chat/[id]/stream-chat';
import { toast } from 'sonner';

export default function ChatButton({
  id,
  ...props
}: { id: string } & React.ComponentProps<'button'>) {
  const router = useRouter();
  const createChannel = useStreamChatStore((s) => s.createChannel);

  const { loading, run: createChannelAndPush } = useAsyncFn(async () => {
    const res = await createChannel(id);
    if (res.result === 'error') {
      if (res.error === 'need_auth') {
        router.push(`/login?redirect=${encodeURIComponent(`/character/${id}`)}`);
      } else {
        toast.error(res.error);
      }
      return;
    }
    router.push(`/chat/${res.channelId}`);
  });

  return (
    <Button loading={loading} onClick={() => createChannelAndPush()} variant="primary" {...props}>
      Chat
    </Button>
  );
}
