import { useSearchParams } from 'react-router'
import { ChevronRightIcon, ChevronLeftIcon } from 'lucide-react'
import { subMonths, addMonths } from 'date-fns'
import { DateTime } from 'luxon'

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 { tz } from './data'

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

export function RangePeriod({
  startDate,
  endDate,
  billingDay
}: RangePeriodProps) {
  const today = DateTime.now().setZone(tz).toJSDate()
  const [, setSearchParams] = useSearchParams()
  const prevPeriod = billingPeriod(billingDay, subMonths(startDate, 1))
  const nextPeriod = billingPeriod(billingDay, addMonths(startDate, 1))
  const [nextDate] = nextPeriod

  return (
    <>
      <ButtonGroup className="max-lg:w-full">
        <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 flex-1"
        >
          <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 > today}
          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: '2-digit'
})
