/**
 * F-147 — DateRangePicker component.
 * Preset date ranges + custom from/to inputs.
 */

import { useCallback } from 'react';

export interface DatePreset {
  label: string;
  getValue: () => { from: string; to: string };
}

const toInputValue = (iso: string) => iso.slice(0, 16); // YYYY-MM-DDTHH:MM

function todayAt(hour: number, minute = 0) {
  const d = new Date();
  d.setUTCHours(hour, minute, 0, 0);
  return d.toISOString();
}

function startOfDay(daysAgo: number) {
  const d = new Date();
  d.setDate(d.getDate() - daysAgo);
  d.setUTCHours(0, 0, 0, 0);
  return d.toISOString();
}

function startOfMonth() {
  const d = new Date();
  d.setDate(1);
  d.setUTCHours(0, 0, 0, 0);
  return d.toISOString();
}

function startOfPrevMonth() {
  const d = new Date();
  d.setDate(0); // last day of prev month
  d.setDate(1);
  d.setUTCHours(0, 0, 0, 0);
  return d.toISOString();
}

function endOfPrevMonth() {
  const d = new Date();
  d.setDate(0); // last day of prev month
  d.setUTCHours(23, 59, 59, 999);
  return d.toISOString();
}

export const DATE_PRESETS: DatePreset[] = [
  {
    label: 'Últimos 7 días',
    getValue: () => ({ from: startOfDay(7), to: todayAt(23) }),
  },
  {
    label: 'Últimos 30 días',
    getValue: () => ({ from: startOfDay(30), to: todayAt(23) }),
  },
  {
    label: 'Últimos 90 días',
    getValue: () => ({ from: startOfDay(90), to: todayAt(23) }),
  },
  {
    label: 'Mes actual',
    getValue: () => ({ from: startOfMonth(), to: todayAt(23) }),
  },
  {
    label: 'Mes anterior',
    getValue: () => ({ from: startOfPrevMonth(), to: endOfPrevMonth() }),
  },
];

interface DateRangePickerProps {
  from: string;
  to: string;
  onChange: (from: string, to: string) => void;
}

export function DateRangePicker({ from, to, onChange }: DateRangePickerProps) {
  const handlePreset = useCallback(
    (preset: DatePreset) => {
      const { from: f, to: t } = preset.getValue();
      onChange(f, t);
    },
    [onChange],
  );

  const handleFrom = (e: React.ChangeEvent<HTMLInputElement>) => onChange(e.target.value, to);
  const handleTo = (e: React.ChangeEvent<HTMLInputElement>) => onChange(from, e.target.value);

  return (
    <div className="flex flex-col gap-2">
      <div className="flex flex-wrap gap-1">
        {DATE_PRESETS.map((preset) => (
          <button
            key={preset.label}
            type="button"
            onClick={() => handlePreset(preset)}
            className="px-2.5 py-1 text-xs font-medium rounded-lg border border-gray-300 bg-white text-gray-700 hover:bg-gray-50 hover:border-gray-400 transition-colors"
          >
            {preset.label}
          </button>
        ))}
      </div>
      <div className="flex gap-2 items-center">
        <div className="flex flex-col gap-1">
          <label htmlFor="date-from" className="text-xs text-gray-500">Desde</label>
          <input
            id="date-from"
            type="datetime-local"
            value={toInputValue(from)}
            onChange={handleFrom}
            className="px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#2D6A4F] focus:border-transparent outline-none"
          />
        </div>
        <div className="flex flex-col gap-1">
          <label htmlFor="date-to" className="text-xs text-gray-500">Hasta</label>
          <input
            id="date-to"
            type="datetime-local"
            value={toInputValue(to)}
            onChange={handleTo}
            className="px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#2D6A4F] focus:border-transparent outline-none"
          />
        </div>
      </div>
    </div>
  );
}
