'use client';

import { useState } from 'react';
import { Calendar } from '@/components/ui/calendar';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Button } from '@/components/ui/button';
import { CalendarIcon, X } from 'lucide-react';
import { format } from 'date-fns';
import { cn } from '@/lib/utils';
import { Badge } from '@/components/ui/badge';

interface DateRangeFilterProps {
  dateFrom?: Date;
  dateTo?: Date;
  onDateChange: (dateFrom?: Date, dateTo?: Date) => void;
}

const datePresets = [
  { label: 'Today', getDates: () => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    return { from: today, to: new Date() };
  }},
  { label: 'This Week', getDates: () => {
    const today = new Date();
    const weekStart = new Date(today);
    weekStart.setDate(today.getDate() - today.getDay());
    weekStart.setHours(0, 0, 0, 0);
    return { from: weekStart, to: new Date() };
  }},
  { label: 'This Month', getDates: () => {
    const today = new Date();
    const monthStart = new Date(today.getFullYear(), today.getMonth(), 1);
    return { from: monthStart, to: new Date() };
  }},
  { label: 'This Year', getDates: () => {
    const today = new Date();
    const yearStart = new Date(today.getFullYear(), 0, 1);
    return { from: yearStart, to: new Date() };
  }},
];

export function DateRangeFilter({ dateFrom, dateTo, onDateChange }: DateRangeFilterProps) {
  const [open, setOpen] = useState(false);

  const applyPreset = (preset: typeof datePresets[0]) => {
    const { from, to } = preset.getDates();
    onDateChange(from, to);
    setOpen(false);
  };

  const clearDates = () => {
    onDateChange(undefined, undefined);
  };

  return (
    <div className="space-y-2">
      <label className="text-sm font-medium text-secondary">Date Range</label>
      <Popover open={open} onOpenChange={setOpen}>
        <PopoverTrigger asChild>
          <Button
            variant="outline"
            className={cn(
              'w-full justify-start text-left font-normal',
              !dateFrom && !dateTo && 'text-muted-foreground'
            )}
          >
            <CalendarIcon className="mr-2 h-4 w-4" />
            {dateFrom && dateTo ? (
              <>
                {format(dateFrom, 'MMM d, yyyy')} - {format(dateTo, 'MMM d, yyyy')}
              </>
            ) : (
              'Select date range...'
            )}
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-auto p-0" align="start">
          <div className="p-3 space-y-2">
            <div className="space-y-1">
              <p className="text-sm font-medium text-secondary">Quick Presets</p>
              <div className="flex flex-wrap gap-2">
                {datePresets.map((preset) => (
                  <Button
                    key={preset.label}
                    variant="outline"
                    size="sm"
                    onClick={() => applyPreset(preset)}
                    className="text-xs"
                  >
                    {preset.label}
                  </Button>
                ))}
              </div>
            </div>
            <div className="border-t pt-2">
              <p className="text-sm font-medium text-secondary mb-2">Custom Range</p>
              <Calendar
                mode="range"
                captionLayout="dropdown"
                fromYear={1900}
                toYear={new Date().getFullYear() + 10}
                selected={{
                  from: dateFrom,
                  to: dateTo,
                }}
                onSelect={(range: { from?: Date; to?: Date } | undefined) => {
                  if (!range) {
                    onDateChange(undefined, undefined);
                    return;
                  }
                  
                  // If both from and to are set, check if they're different dates
                  if (range.from && range.to) {
                    // Check if dates are on the same day
                    const fromDate = new Date(range.from);
                    fromDate.setHours(0, 0, 0, 0);
                    const toDate = new Date(range.to);
                    toDate.setHours(0, 0, 0, 0);
                    const sameDay = fromDate.getTime() === toDate.getTime();
                    
                    if (!sameDay) {
                      // Valid range with different dates - complete selection and close
                      onDateChange(range.from, range.to);
                      setOpen(false);
                    } else {
                      // Same day - treat as "from" only, keep popover open for "to" selection
                      onDateChange(range.from, undefined);
                    }
                  } else if (range.from) {
                    // Only "from" is selected - keep popover open for "to" selection
                    onDateChange(range.from, undefined);
                  } else if (range.to) {
                    // Only "to" is selected (shouldn't happen in range mode, but handle it)
                    onDateChange(undefined, range.to);
                  }
                }}
                numberOfMonths={2}
              />
            </div>
            {(dateFrom || dateTo) && (
              <div className="border-t pt-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    clearDates();
                    setOpen(false);
                  }}
                  className="w-full text-xs"
                >
                  <X className="mr-2 h-3 w-3" />
                  Clear Dates
                </Button>
              </div>
            )}
          </div>
        </PopoverContent>
      </Popover>
      {(dateFrom || dateTo) && (
        <Badge variant="secondary" className="flex items-center gap-1 w-fit">
          {dateFrom && dateTo ? (
            <>
              {format(dateFrom, 'MMM d')} - {format(dateTo, 'MMM d, yyyy')}
            </>
          ) : dateFrom ? (
            `From ${format(dateFrom, 'MMM d, yyyy')}`
          ) : (
            `Until ${format(dateTo!, 'MMM d, yyyy')}`
          )}
          <button
            onClick={clearDates}
            className="ml-1 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700"
          >
            <X className="h-3 w-3" />
          </button>
        </Badge>
      )}
    </div>
  );
}

