/**
 * DateRangePicker component - Date range selection with calendar.
 *
 * @package GetMD
 * @since   1.0.0
 */

import * as React from 'react';
import { format } from 'date-fns';
import { Calendar as CalendarIcon, X } from 'lucide-react';
import { DateRange } from 'react-day-picker';
import { cn } from '@/lib/utils';
import { Button } from './button';
import { Calendar } from './calendar';
import { Popover, PopoverContent, PopoverTrigger } from './popover';

interface DateRangePickerProps {
  value?: DateRange;
  onChange: (range: DateRange | undefined) => void;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
}

/**
 * Render a button-triggered popover containing a two-month calendar for selecting a date range.
 *
 * The trigger button displays a calendar icon and either a placeholder, a single selected date,
 * or a formatted date range. When a start date is present an inline clear (X) icon appears
 * which clears the selection. Opening the popover shows a calendar in range-selection mode.
 *
 * @param value - The currently selected date range (`{ from?: Date; to?: Date }`) or `undefined`.
 * @param onChange - Callback invoked with the new `DateRange` when the selection changes or `undefined` when cleared.
 * @param placeholder - Text shown when no date range is selected.
 * @param disabled - If `true`, disables the trigger button.
 * @param className - Additional class names applied to the trigger button.
 * @returns The DateRangePicker component as a JSX element.
 */
export function DateRangePicker({
  value,
  onChange,
  placeholder,
  disabled = false,
  className,
}: DateRangePickerProps) {
  const { i18n } = window.summixGetmdData || {};
  const [open, setOpen] = React.useState(false);
  const defaultPlaceholder = i18n?.selectDates || 'Select dates';

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

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          className={cn(
            'smx-w-full smx-justify-start smx-text-left smx-font-normal',
            !value && 'smx-text-muted-foreground',
            className
          )}
          disabled={disabled}
        >
          <CalendarIcon className="smx-mr-2 smx-h-4 smx-w-4" />
          {value?.from ? (
            value.to ? (
              <>
                {format(value.from, 'LLL dd, y')} -{' '}
                {format(value.to, 'LLL dd, y')}
              </>
            ) : (
              format(value.from, 'LLL dd, y')
            )
          ) : (
            <span>{placeholder || defaultPlaceholder}</span>
          )}
          {value?.from && (
            <X
              className="smx-ml-auto smx-h-4 smx-w-4 smx-shrink-0 smx-opacity-50 hover:smx-opacity-100"
              onClick={handleClear}
            />
          )}
        </Button>
      </PopoverTrigger>
      <PopoverContent className="smx-w-auto smx-p-0" align="start">
        <Calendar
          initialFocus
          mode="range"
          defaultMonth={value?.from}
          selected={value}
          onSelect={onChange}
          numberOfMonths={2}
        />
      </PopoverContent>
    </Popover>
  );
}