import { getSevenDaysSignList, signIn } from '@/services/editor';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useCurrentUser } from '../auth';
import { toast } from 'sonner';
import { useTranslations } from 'next-intl';
import { useMemo } from 'react';

export function useSignIn() {
  const { data: user } = useCurrentUser();
  const t = useTranslations('crushcoin');
  const queryClient = useQueryClient();
  const { data: signInListData, isLoading: fetchSignInListLoading } = useQuery({
    queryKey: ['signInList'],
    enabled: !!user?.userId,
    queryFn: () => getSevenDaysSignList({ userId: user?.userId }),
  });

  const { mutate: handleSignIn, isPending: signInLoading } = useMutation({
    mutationFn: () => signIn({ userId: user?.userId }),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ['signInList'],
      });
      toast.success(t('checked_success'));
    },
  });

  const isTodaySigned = useMemo(() => {
    if (!signInListData?.list?.length) return false;
    const today = new Date();
    const todayStr = today.toISOString().split('T')[0];
    return signInListData.list.find((item) => item.dayStr === todayStr)?.signIn;
  }, [signInListData]);

  return {
    signInListData,
    isTodaySigned,
    fetchSignInListLoading,
    signInLoading,
    handleSignIn,
  };
}
