'use client'

import { EllipsisIcon } from 'lucide-react'
import { useState } from 'react'
import { type DateRange } from 'react-day-picker'
import { ptBR } from 'react-day-picker/locale'

import { Badge } from '@repo/ui/components/ui/badge'
import { Button } from '@repo/ui/components/ui/button'
import { Calendar } from '@repo/ui/components/ui/calendar'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuTrigger
} from '@repo/ui/components/ui/dropdown-menu'
import {
  Popover,
  PopoverContent,
  PopoverTrigger
} from '@repo/ui/components/ui/popover'
import { Separator } from '@repo/ui/components/ui/separator'
import { cn } from '@repo/ui/lib/utils'

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

type FilterProps = {
  rangeField?: string
  dateRange?: DateRange
}

type RangeCalendarFilterProps = {
  title: string
  icon: React.ComponentType
  value?: FilterProps
  options: { value: string; label: string }[]
  className?: string
  onChange?: (values: FilterProps | undefined) => void
}

export function RangeCalendarFilter({
  title,
  icon: Icon,
  value = undefined,
  options = [],
  className,
  onChange
}: RangeCalendarFilterProps) {
  const [rangeField, setRangeField] = useState<string | undefined>(
    value?.rangeField || options?.[0]?.value
  )
  const [dateRange, setDateRange] = useState<DateRange | undefined>(
    value?.dateRange
  )

  const handleReset = () => {
    onChange?.(undefined)
    setRangeField(options?.[0]?.value)
    setDateRange(undefined)
  }

  return (
    <Popover>
      <div
        className={cn(
          'h-9 border rounded-md dark:bg-input/30 border-dashed flex items-center justify-center',
          className
        )}
      >
        <PopoverTrigger asChild>
          <Button variant="ghost" size="sm" className="cursor-pointer h-full">
            <Icon /> {title}
            {dateRange && (
              <>
                <Separator orientation="vertical" className="mx-0.5 h-4" />
                <div className="gap-1 flex">
                  <Badge
                    variant="outline"
                    className="rounded-sm px-1 font-mono"
                  >
                    {formatted.format(dateRange.from)}
                  </Badge>
                  <Badge
                    variant="outline"
                    className="rounded-sm px-1 font-mono"
                  >
                    {formatted.format(dateRange.to)}
                  </Badge>
                </div>
              </>
            )}
          </Button>
        </PopoverTrigger>

        {dateRange && (
          <>
            <Separator orientation="vertical" className="h-4" />
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="sm" className="cursor-pointer">
                  <EllipsisIcon />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent className="w-46" align="end">
                <DropdownMenuRadioGroup
                  value={rangeField}
                  onValueChange={(rangeField) => {
                    setRangeField(rangeField)
                    onChange?.({ rangeField, dateRange })
                  }}
                  className="*:cursor-pointer"
                >
                  {options.map(({ label, value }, idx) => (
                    <DropdownMenuRadioItem
                      value={value}
                      key={idx}
                      onSelect={(e) => e.preventDefault()}
                    >
                      {label}
                    </DropdownMenuRadioItem>
                  ))}
                </DropdownMenuRadioGroup>
              </DropdownMenuContent>
            </DropdownMenu>
          </>
        )}
      </div>

      <PopoverContent className="w-full p-0" align="start">
        <Calendar
          mode="range"
          locale={ptBR}
          captionLayout="dropdown"
          defaultMonth={dateRange?.from}
          selected={dateRange}
          numberOfMonths={1}
          startMonth={new Date(2012, 0)}
          endMonth={new Date(new Date().getFullYear() + 1, 0)}
          onSelect={(dateRange: DateRange | undefined) => {
            if (!dateRange) {
              onChange?.(undefined)
              return setDateRange(undefined)
            }

            if (dateRange.from?.getTime() === dateRange.to?.getTime()) {
              const nextDay = new Date(String(dateRange.from))
              nextDay.setDate(nextDay.getDate() + 6)
              dateRange.to = nextDay
            }

            onChange?.({ rangeField, dateRange })
            setDateRange(dateRange)
          }}
        />

        {dateRange && (
          <>
            <Separator />
            <div className="p-1">
              <Button
                variant="ghost"
                className="w-full cursor-pointer font-normal"
                onClick={handleReset}
              >
                Limpar
              </Button>
            </div>
          </>
        )}
      </PopoverContent>
    </Popover>
  )
}
