import { Button } from '@/components/ui/button';
import { formatTimeAgo } from '@/utils/helper';
import { m } from '@paraglide/messages';
import { acceptInvitation, rejectInvitation } from '@service/house.api';
import { notificationQueries } from '@service/queries';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { ItemActions, ItemContent, ItemDescription, ItemTitle } from '@ui/item';
import { Spinner } from '@ui/spinner';
import { toast } from 'sonner';

type NotifyProps = {
  notify: NotificationWithUser;
};

const NotificationInvitation = ({ notify }: NotifyProps) => {
  const { house } = JSON.parse(notify.metadata || '');

  const queryClient = useQueryClient();

  const { mutate: acceptInvitationMutation, isPending: isAcceptPending } =
    useMutation({
      mutationFn: acceptInvitation,
      onSuccess: () => {
        queryClient.invalidateQueries({
          queryKey: [...notificationQueries.all, 'list'],
        });
        toast.success(m.notification_page_message_invitation_success(), {
          richColors: true,
        });
      },
      onError: (error: ReturnError) => {
        console.error(error);
        const code = error.code as Parameters<
          typeof m.backend_message
        >[0]['code'];
        toast.error(m.backend_message({ code }), {
          richColors: true,
        });
      },
    });

  const { mutate: rejectInvitationMutation, isPending: isRejectPending } =
    useMutation({
      mutationFn: rejectInvitation,
      onSuccess: () => {
        queryClient.invalidateQueries({
          queryKey: [...notificationQueries.all, 'list'],
        });
        toast.success(m.notification_page_message_invitation_rejected(), {
          richColors: true,
        });
      },
      onError: (error: ReturnError) => {
        console.error(error);
        const code = error.code as Parameters<
          typeof m.backend_message
        >[0]['code'];
        toast.error(m.backend_message({ code }), {
          richColors: true,
        });
      },
    });

  const handleAgreeAction = async () => {
    if (notify.link) {
      acceptInvitationMutation({
        data: { id: notify.link, notificationId: notify.id },
      });
    }
  };

  const handleRejectAction = () => {
    if (notify.link) {
      rejectInvitationMutation({
        data: { id: notify.link, notificationId: notify.id },
      });
    }
  };

  return (
    <>
      <ItemContent>
        <ItemTitle>
          {`${notify.user.name} (${notify.user.email})`}{' '}
          {m.templates_message_notification({
            message: notify.message as Parameters<
              typeof m.templates_message_notification
            >[0]['message'],
            name: house.name,
          })}
        </ItemTitle>
        <ItemDescription>{formatTimeAgo(notify.createdAt)}</ItemDescription>
      </ItemContent>
      {notify.link && (
        <ItemActions>
          <Button
            onClick={() => handleAgreeAction()}
            disabled={isAcceptPending}
          >
            {isAcceptPending && <Spinner data-icon="inline-start" />}
            {m.ui_agree_btn()}
          </Button>
          <Button
            variant="outline"
            onClick={() => handleRejectAction()}
            disabled={isRejectPending}
          >
            {isRejectPending && <Spinner data-icon="inline-start" />}
            {m.ui_reject_btn()}
          </Button>
        </ItemActions>
      )}
    </>
  );
};

export default NotificationInvitation;
