'use client';

import { useEffect, useMemo, useRef, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';

const PRESETS = [
  { value: 'today', label: 'Today' },
  { value: 'yesterday', label: 'Yesterday' },
  { value: 'this-week', label: 'This week' },
  { value: 'last-week', label: 'Last week' },
  { value: 'this-month', label: 'This month' },
  { value: 'last-month', label: 'Last month' },
  { value: 'last-30-days', label: 'Last 30 days' },
  { value: 'last-3-months', label: 'Last 3 months' },
  { value: 'this-quarter', label: 'This quarter' },
  { value: 'last-quarter', label: 'Last quarter' },
  { value: 'this-year', label: 'This year' },
  { value: 'last-year', label: 'Last year' },
  { value: 'all-time', label: 'All time' },
] as const;

function pad(n: number) {
  return String(n).padStart(2, '0');
}

function toISO(date: Date) {
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
}

function fromISO(value: string) {
  if (!value) return null;
  const [y, m, d] = value.split('-').map(Number);
  if (!y || !m || !d) return null;
  return new Date(y, m - 1, d);
}

function toMDY(value: string) {
  return value ? `${value.slice(5, 7)}/${value.slice(8, 10)}/${value.slice(0, 4)}` : '';
}

function parseMDY(value: string) {
  const match = value.trim().match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
  if (!match) return '';
  const date = new Date(Number(match[3]), Number(match[1]) - 1, Number(match[2]));
  return date.getMonth() === Number(match[1]) - 1 && date.getDate() === Number(match[2])
    ? toISO(date)
    : '';
}

function resolvePreset(key: string): { start: string; end: string } {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const y = today.getFullYear();
  const m = today.getMonth();
  const q = Math.floor(m / 3);
  const d = (year: number, month: number, day: number) => new Date(year, month, day);
  const weekStart = new Date(today);
  weekStart.setDate(today.getDate() - today.getDay());
  let start = new Date(today);
  let end = new Date(today);
  switch (key) {
    case 'yesterday':
      start.setDate(start.getDate() - 1);
      end = new Date(start);
      break;
    case 'this-week':
      start = weekStart;
      end = new Date(weekStart);
      end.setDate(end.getDate() + 6);
      break;
    case 'last-week':
      start = new Date(weekStart);
      start.setDate(start.getDate() - 7);
      end = new Date(weekStart);
      end.setDate(end.getDate() - 1);
      break;
    case 'this-month':
      start = d(y, m, 1);
      end = d(y, m + 1, 0);
      break;
    case 'last-month':
      start = d(y, m - 1, 1);
      end = d(y, m, 0);
      break;
    case 'last-30-days':
      start.setDate(start.getDate() - 29);
      break;
    case 'last-3-months':
      start.setMonth(start.getMonth() - 3);
      break;
    case 'this-quarter':
      start = d(y, q * 3, 1);
      end = d(y, q * 3 + 3, 0);
      break;
    case 'last-quarter':
      start = d(y, q * 3 - 3, 1);
      end = d(y, q * 3, 0);
      break;
    case 'this-year':
      start = d(y, 0, 1);
      end = d(y, 11, 31);
      break;
    case 'last-year':
      start = d(y - 1, 0, 1);
      end = d(y - 1, 11, 31);
      break;
    case 'all-time':
      return { start: '', end: '' };
    default:
      break;
  }
  return { start: toISO(start), end: toISO(end) };
}

export interface BillingDateRange {
  from: string;
  to: string;
}

/** CRM date-range picker used on Account & Billing (transactions filter and export). */
export function BillingDateRangePicker({
  id,
  fromLabel,
  toLabel,
  value,
  onChange,
  calendarOpen,
  onCalendarOpenChange,
}: {
  id: string;
  fromLabel: string;
  toLabel: string;
  value: BillingDateRange;
  onChange: (next: BillingDateRange) => void;
  calendarOpen?: boolean;
  onCalendarOpenChange?: (open: boolean) => void;
}) {
  const root = useRef<HTMLDivElement>(null);
  const [active, setActive] = useState<'from' | 'to'>('from');
  const [preset, setPreset] = useState<string | null>(null);
  const [view, setView] = useState(() => {
    const now = new Date();
    return new Date(now.getFullYear(), now.getMonth(), 1);
  });
  const [fromText, setFromText] = useState(toMDY(value.from));
  const [toText, setToText] = useState(toMDY(value.to));
  const open = calendarOpen ?? false;

  useEffect(() => {
    setFromText(toMDY(value.from));
    setToText(toMDY(value.to));
  }, [value.from, value.to]);

  const days = useMemo(() => {
    const first = new Date(view.getFullYear(), view.getMonth(), 1);
    const start = new Date(first);
    start.setDate(1 - first.getDay());
    const today = toISO(new Date());
    const cells = [];
    for (let i = 0; i < 42; i++) {
      const date = new Date(start);
      date.setDate(start.getDate() + i);
      const key = toISO(date);
      cells.push({
        key,
        day: date.getDate(),
        out: date.getMonth() !== view.getMonth(),
        selected: key === value.from || key === value.to,
        inRange: Boolean(value.from && value.to && key > value.from && key < value.to),
        today: key === today,
        label: date.toDateString(),
      });
    }
    return cells;
  }, [view, value.from, value.to]);

  const title = view.toLocaleDateString('en-US', { month: 'long', year: 'numeric' });

  const pickDay = (key: string) => {
    let from = value.from;
    let to = value.to;
    let nextActive = active;
    if (active === 'from') {
      from = key;
      if (to && to < key) to = '';
      nextActive = 'to';
    } else if (from && key < from) {
      to = from;
      from = key;
      nextActive = 'from';
    } else {
      to = key;
      nextActive = 'from';
    }
    setActive(nextActive);
    setPreset(null);
    onChange({ from, to });
    if (from && to) onCalendarOpenChange?.(false);
  };

  return (
    <div className="seq-dp" data-dp id={id} ref={root}>
      <div className="seq-dp__inputs" data-dp-inputs-trigger>
        <label
          className={`seq-dp__input${active === 'from' ? 'is-active' : ''}`}
          data-dp-input-wrap="from"
        >
          <CrmIcon name="calendar" className="iconSize-14" />
          <input
            type="text"
            inputMode="numeric"
            placeholder="MM/DD/YYYY"
            aria-label={fromLabel}
            value={fromText}
            onChange={(e) => setFromText(e.target.value)}
            onFocus={() => {
              setActive('from');
              onCalendarOpenChange?.(true);
            }}
            onBlur={() => {
              const parsed = parseMDY(fromText);
              if (parsed || !fromText.trim()) onChange({ from: parsed, to: value.to });
              else setFromText(toMDY(value.from));
            }}
          />
        </label>
        <span className="cad-date-sep">to</span>
        <label
          className={`seq-dp__input${active === 'to' ? 'is-active' : ''}`}
          data-dp-input-wrap="to"
        >
          <CrmIcon name="calendar" className="iconSize-14" />
          <input
            type="text"
            inputMode="numeric"
            placeholder="MM/DD/YYYY"
            aria-label={toLabel}
            value={toText}
            onChange={(e) => setToText(e.target.value)}
            onFocus={() => {
              setActive('to');
              onCalendarOpenChange?.(true);
            }}
            onBlur={() => {
              const parsed = parseMDY(toText);
              if (parsed || !toText.trim()) onChange({ from: value.from, to: parsed });
              else setToText(toMDY(value.to));
            }}
          />
        </label>
      </div>
      <div className="seq-dp__body" data-dp-popover hidden={!open}>
        <div className="seq-dp__presets" data-dp-presets>
          {PRESETS.map((p) => (
            <button
              key={p.value}
              type="button"
              className={`seq-dp__preset${preset === p.value ? 'is-active' : ''}`}
              data-dp-preset={p.value}
              onClick={() => {
                const dates = resolvePreset(p.value);
                setPreset(p.value);
                onChange({ from: dates.start, to: dates.end });
                const d = fromISO(dates.start);
                if (d) setView(new Date(d.getFullYear(), d.getMonth(), 1));
                onCalendarOpenChange?.(false);
              }}
            >
              {p.label}
            </button>
          ))}
        </div>
        <div className="seq-dp__cal" data-dp-cal>
          <div className="seq-dp__head">
            <button
              type="button"
              className="seq-dp__nav"
              aria-label="Previous month"
              onClick={() => setView(new Date(view.getFullYear(), view.getMonth() - 1, 1))}
            >
              <svg
                viewBox="0 0 24 24"
                width="16"
                height="16"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <path d="m15 18-6-6 6-6" />
              </svg>
            </button>
            <strong aria-live="polite">{title}</strong>
            <button
              type="button"
              className="seq-dp__nav"
              aria-label="Next month"
              onClick={() => setView(new Date(view.getFullYear(), view.getMonth() + 1, 1))}
            >
              <svg
                viewBox="0 0 24 24"
                width="16"
                height="16"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <path d="m9 18 6-6-6-6" />
              </svg>
            </button>
          </div>
          <div className="seq-dp__grid" role="group" aria-label={title}>
            {['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'].map((day) => (
              <span key={day} className="seq-dp__wd">
                {day}
              </span>
            ))}
            {days.map((cell) => (
              <button
                key={cell.key}
                type="button"
                className={`seq-dp__day${cell.out ? 'is-out' : ''}${cell.selected ? 'is-sel' : ''}${cell.inRange ? 'is-range' : ''}${cell.today ? 'is-today' : ''}`}
                aria-pressed={cell.selected}
                aria-label={cell.label}
                onClick={() => pickDay(cell.key)}
              >
                {cell.day}
              </button>
            ))}
          </div>
          <button
            type="button"
            className="seq-dp__clear"
            onClick={() => {
              setPreset(null);
              onChange({ from: '', to: '' });
            }}
          >
            Clear
          </button>
        </div>
      </div>
    </div>
  );
}

export { resolvePreset as resolveBillingDatePreset };
