"use client"


import React from 'react'
import useSWR from 'swr'
import styles from './upcoming.module.css'
import { BsTriangleFill } from 'react-icons/bs'
import RecurringPayment from './RecurringPayment'

export default function Upcoming() {
  const fetcher = (...args) => fetch(...args).then((res) => res.json())
  const { data, error } = useSWR(`https://api.foldbank.codingcoffee.me/api/v1/recurringPayments/upcoming/`, fetcher)

  if (error) return <div>Error: Failed to load</div>
  if (!data) return <div></div>

  const recurringPayments = data.results
  // const recurringPayments = [
  //   {
  //     title: "2568 Rent",
  //     amount: "36,163",
  //     due_in_days: "7",
  //     icon_type: "rent",
  //   },
  //   {
  //     title: "YouTube Premium",
  //     amount: "130",
  //     due_in_days: "17",
  //     icon_type: "youtube",
  //   },
  // ]

  const recurringPaymentsDiv = []
  let sum_amount_upcoming = 0

  recurringPayments.forEach((payment) => {
    const today = new Date()
    const due_on = new Date(payment.due_on)
    const diff_time = Math.abs(due_on - today);
    const due_in_days = Math.ceil(diff_time / (1000 * 60 * 60 * 24));
    sum_amount_upcoming += payment.amount

    let freq = ""
    if (payment.frequency == "30 00:00:00") {
      freq = "monthly"
    }

    recurringPaymentsDiv.push(
      <RecurringPayment
        key={payment.id}
        title={payment.to_account.holders_name}
        amount={payment.amount.toLocaleString('en-IN')}
        due_in_days={due_in_days}
        icon_type={payment.tag.icon_type}
        frequency={freq}
      />
    )
  })

  return (
    <div className={styles.main}>
      <div className={styles.summary}>
        <div className={styles.left}>
          <BsTriangleFill
            size={10}
            className={styles.arrow}
          />
          <div className={styles.text}>Upcoming</div>
        </div>
        <div className={styles.right}>₹{sum_amount_upcoming.toLocaleString("en-IN")}</div>
      </div>
      {recurringPaymentsDiv}
    </div>
  )
}
