import {
  useState,
  useEffect,
  useCallback,
} from 'react'

import { useAuthStore } from 'features/AuthStore'

import format from 'date-fns/format'

import { getUserListPayments, PaymentsList } from 'requests/getUserListPayments'

export const usePaymentHistory = () => {
  const [payments, setPayments] = useState<PaymentsList>([])
  const timezoneOffset = new Date().getTimezoneOffset()
  const { user } = useAuthStore()

  const formattedDate = useCallback(
    (date: string) => format(new Date(date), 'd MMM yyyy'),
    [],
  )

  useEffect(() => {
    (async () => {
      const allPayments = await getUserListPayments(
        timezoneOffset,
        user?.profile?.email || '',
      )
      setPayments(allPayments)
    })()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  return { formattedDate, payments }
}
