import { CalendarIcon, XIcon } from 'lucide-react'

import { useState } from 'react'
import { useToggle } from 'ahooks'
import { format } from 'date-fns'
import { ptBR } from 'react-day-picker/locale'

import { Button } from '@repo/ui/components/ui/button'
import { Calendar } from '@repo/ui/components/ui/calendar'
import {
  InputGroup,
  InputGroupAddon,
  InputGroupInput
} from '@repo/ui/components/ui/input-group'
import {
  Popover,
  PopoverContent,
  PopoverTrigger
} from '@repo/ui/components/ui/popover'

interface ScheduledForInputProps {
  value?: Date
  onChange?: (value: Date | undefined) => void
}

export function ScheduledForInput({ value, onChange }: ScheduledForInputProps) {
  const today = new Date()
  const tomorrow = new Date()
  tomorrow.setDate(today.getDate() + 1)
  const [open, { set }] = useToggle()
  const [selected, setDate] = useState<Date | undefined>(value)
  const display = selected ? format(selected, 'dd/MM/yyyy') : ''

  return (
    <Popover open={open} onOpenChange={set}>
      <PopoverTrigger asChild>
        <InputGroup>
          <InputGroupInput
            readOnly
            placeholder="Imediatamente"
            value={display}
          />

          <InputGroupAddon>
            <CalendarIcon />
          </InputGroupAddon>

          {selected && (
            <InputGroupAddon align="inline-end" className="mr-0">
              <Button
                variant="link"
                size="icon-sm"
                className="cursor-pointer text-muted-foreground"
                onClick={(e) => {
                  e.preventDefault()
                  setDate(undefined)
                  onChange?.(undefined)
                  set(false)
                }}
              >
                <XIcon />
              </Button>
            </InputGroupAddon>
          )}
        </InputGroup>
      </PopoverTrigger>

      <PopoverContent className="w-full p-0" align="start">
        <Calendar
          mode="single"
          selected={selected}
          onSelect={(date: Date | undefined) => {
            setDate(date)
            onChange?.(date)
            set(false)
          }}
          disabled={{ before: tomorrow }}
          startMonth={new Date(today.getFullYear(), 0)}
          endMonth={new Date(today.getFullYear() + 3, 11)}
          captionLayout="dropdown"
          locale={ptBR}
        />
      </PopoverContent>
    </Popover>
  )
}
