'use client';

import * as React from 'react';
import { format, parse, isValid, startOfDay } from 'date-fns';
import { Calendar as CalendarIcon, X } from 'lucide-react';
import { motion, useReducedMotion } from 'motion/react';

import { cn } from '@/lib/utils';
import { easeOutExpo } from '@/lib/motion';
import { Button } from '@/components/ui/button';
import { Calendar } from '@/components/ui/calendar';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';

function parseIsoDate(value?: string): Date | undefined {
  if (!value) return undefined;
  const parsed = parse(value, 'yyyy-MM-dd', new Date());
  return isValid(parsed) ? startOfDay(parsed) : undefined;
}

function toIsoDate(date: Date): string {
  return format(date, 'yyyy-MM-dd');
}

export interface DatePickerProps {
  value?: string;
  onChange: (value: string) => void;
  placeholder?: string;
  disabled?: boolean;
  id?: string;
  className?: string;
  /** Applied to the trigger button */
  buttonClassName?: string;
  min?: string;
  max?: string;
  clearable?: boolean;
  align?: 'start' | 'center' | 'end';
  title?: string;
}

export function DatePicker({
  value,
  onChange,
  placeholder = 'Select date',
  disabled = false,
  id,
  className,
  buttonClassName,
  min,
  max,
  clearable = false,
  align = 'start',
  title,
}: DatePickerProps) {
  const [open, setOpen] = React.useState(false);
  const reduceMotion = useReducedMotion();
  const selected = parseIsoDate(value);
  const minDate = parseIsoDate(min);
  const maxDate = parseIsoDate(max);

  const displayLabel = selected ? format(selected, 'dd MMM yyyy') : placeholder;

  const handleSelect = (date?: Date) => {
    if (!date) return;
    onChange(toIsoDate(date));
    setOpen(false);
  };

  const handleClear = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    onChange('');
  };

  const handleToday = () => {
    const today = startOfDay(new Date());
    if (minDate && today < minDate) return;
    if (maxDate && today > maxDate) return;
    onChange(toIsoDate(today));
    setOpen(false);
  };

  return (
    <div className={cn('relative', className)}>
      <Popover open={open} onOpenChange={setOpen}>
        <PopoverTrigger asChild>
          <Button
            id={id}
            type="button"
            variant="outline"
            disabled={disabled}
            title={title}
            aria-label={title || placeholder}
            className={cn(
              'h-10 w-full justify-start gap-2 rounded-lg border-border bg-card px-3 text-left font-normal shadow-sm',
              'hover:border-primary/30 hover:bg-card',
              'focus-visible:ring-ring/40 data-[state=open]:border-primary/40 data-[state=open]:ring-2 data-[state=open]:ring-ring/40',
              !selected && 'text-muted-foreground',
              selected && 'text-foreground',
              buttonClassName
            )}
          >
            <CalendarIcon className="h-4 w-4 shrink-0 text-primary" />
            <span className="min-w-0 flex-1 truncate tabular-nums">{displayLabel}</span>
            {clearable && selected && !disabled ? (
              <span
                role="button"
                tabIndex={0}
                aria-label="Clear date"
                className="rounded-md p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground"
                onClick={handleClear}
                onKeyDown={(e) => {
                  if (e.key === 'Enter' || e.key === ' ') {
                    handleClear(e as unknown as React.MouseEvent);
                  }
                }}
              >
                <X className="h-3.5 w-3.5" />
              </span>
            ) : null}
          </Button>
        </PopoverTrigger>
        <PopoverContent
          align={align}
          sideOffset={8}
          className="w-auto p-0 overflow-hidden"
          onOpenAutoFocus={(e) => e.preventDefault()}
        >
          <motion.div
            initial={reduceMotion ? false : { opacity: 0, y: 4 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.18, ease: easeOutExpo }}
          >
            <div className="border-b border-border px-3 py-2.5">
              <p className="text-[10px] font-semibold uppercase tracking-[0.14em] text-muted-foreground">
                Select date
              </p>
              <p className="mt-0.5 text-sm font-medium text-foreground tabular-nums">
                {selected ? format(selected, 'EEEE, d MMMM yyyy') : 'No date selected'}
              </p>
            </div>

            <Calendar
              mode="single"
              selected={selected}
              onSelect={handleSelect}
              disabled={(date) => {
                const d = startOfDay(date);
                if (minDate && d < minDate) return true;
                if (maxDate && d > maxDate) return true;
                return false;
              }}
              defaultMonth={selected}
              autoFocus
              startMonth={new Date(1970, 0)}
              endMonth={new Date(new Date().getFullYear() + 10, 11)}
              captionLayout="dropdown"
            />

            <div className="flex items-center justify-between gap-2 border-t border-border px-3 py-2">
              <Button
                type="button"
                variant="ghost"
                size="sm"
                className="h-8 text-xs"
                onClick={handleToday}
              >
                Today
              </Button>
              {clearable ? (
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  className="h-8 text-xs text-muted-foreground"
                  onClick={() => {
                    onChange('');
                    setOpen(false);
                  }}
                  disabled={!selected}
                >
                  Clear
                </Button>
              ) : (
                <span />
              )}
            </div>
          </motion.div>
        </PopoverContent>
      </Popover>
    </div>
  );
}
