import styled from "@emotion/styled"
import type { Item } from "opvault.js"
import { useMemo, memo } from "react"
import { parseMonthYear } from "../utils"

const Container = styled.div`
  background: #cdc7b2;
  border-radius: 5px;
  padding: 15px;
  @media (prefers-color-scheme: dark) {
    background: #575345;
  }
`

export const ItemWarning = memo<{ item: Item }>(({ item }) => {
  const isExpired = useMemo(() => {
    const fields = item.details.sections?.flatMap(x => x.fields ?? [])
    if (!fields?.length) return false

    for (const field of fields) {
      if (field.k === "monthYear") {
        const { year, month } = parseMonthYear(field.v)
        const now = new Date()
        const currentYear = now.getFullYear()
        return currentYear > year || (currentYear === year && now.getMonth() + 1 > month)
      } else if (field.k === "date") {
        const now = Date.now()
        const fieldDate = new Date(field.v * 1000).valueOf()
        return now > fieldDate
      }
    }

    return false
  }, [item])

  if (isExpired) {
    return <Container>Expired</Container>
  }

  return null
})
