import { ChevronRightIcon, ChevronLeftIcon } from 'lucide-react'
import { subMonths, addMonths } from 'date-fns'

import { Button } from '@repo/ui/components/ui/button'
import { ButtonGroup } from '@repo/ui/components/ui/button-group'
import { Badge } from '@repo/ui/components/ui/badge'

import { formatDate, billingPeriod } from './util'
import { useSearchParams } from 'react-router'

type RangePeriodProps = {
  startDate: Date
  endDate: Date
  billingDay: number
}

export function RangePeriod({
  startDate,
  endDate,
  billingDay
}: RangePeriodProps) {
  const [, setSearchParams] = useSearchParams()
  const prevPeriod = billingPeriod(billingDay, subMonths(startDate, 1))
  const nextPeriod = billingPeriod(billingDay, addMonths(startDate, 1))
  const [nextDate] = nextPeriod

  return (
    <>
      <ButtonGroup>
        <Button
          variant="outline"
          className="border-dashed cursor-pointer"
          onClick={() => {
            setSearchParams((searchParams) => {
              const [start, end] = prevPeriod
              searchParams.set('start', formatDate(start))
              searchParams.set('end', formatDate(end))
              return searchParams
            })
          }}
        >
          <ChevronLeftIcon />
        </Button>
        <Button variant="outline" className="pointer-events-none border-dashed">
          <div className="gap-1 flex">
            <Badge variant="outline" className="rounded-sm px-1 font-mono">
              {datetime.format(startDate)}
            </Badge>
            <Badge variant="outline" className="rounded-sm px-1 font-mono">
              {datetime.format(endDate)}
            </Badge>
          </div>
        </Button>
        <Button
          variant="outline"
          className="border-dashed cursor-pointer"
          disabled={nextDate > new Date()}
          onClick={() => {
            setSearchParams((searchParams) => {
              const [start, end] = nextPeriod
              searchParams.set('start', formatDate(start))
              searchParams.set('end', formatDate(end))
              return searchParams
            })
          }}
        >
          <ChevronRightIcon />
        </Button>
      </ButtonGroup>
    </>
  )
}

const datetime = new Intl.DateTimeFormat('pt-BR', {
  day: '2-digit',
  month: '2-digit',
  year: 'numeric'
})
