'use client';

import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
import { CalendarDays, Check, ChevronDown, ChevronLeft, ChevronRight } from 'lucide-react';
import { useState } from 'react';

import { usePopover } from '@/components/layout/use-popover';
import { Input } from '@/components/ui/input';
import { endOfUtcDay, startOfUtcDay } from '@/lib/shipments';
import { cn } from '@/lib/utils';

type Preset = 'today' | '7' | '30' | 'month';
type Range = { dateFrom: string; dateTo: string };

const PRESETS: ReadonlyArray<{ id: Preset; label: string }> = [
  { id: 'today', label: 'Today' },
  { id: '7', label: 'Last 7 days' },
  { id: '30', label: 'Last 30 days' },
  { id: 'month', label: 'This month' },
];

/** Same date maths as the original picker: UTC day boundaries as ISO strings. */
const presetRange = (preset: Preset): Range => {
  const now = new Date();
  if (preset === 'today') return { dateFrom: startOfUtcDay(now), dateTo: endOfUtcDay(now) };
  if (preset === 'month') return { dateFrom: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString(), dateTo: endOfUtcDay(now) };
  const start = new Date(now);
  start.setUTCDate(start.getUTCDate() - (preset === '7' ? 6 : 29));
  return { dateFrom: startOfUtcDay(start), dateTo: endOfUtcDay(now) };
};

const dayKey = (iso: string): string => iso.slice(0, 10);
const fromDay = (day: string): string => startOfUtcDay(new Date(`${day}T00:00:00.000Z`));
const toDay = (day: string): string => endOfUtcDay(new Date(`${day}T00:00:00.000Z`));

const activePreset = (range: Range): Preset | null => {
  if (range.dateFrom.length === 0 || range.dateTo.length === 0) return null;
  return PRESETS.find((preset) => {
    const candidate = presetRange(preset.id);
    return dayKey(candidate.dateFrom) === dayKey(range.dateFrom) && dayKey(candidate.dateTo) === dayKey(range.dateTo);
  })?.id ?? null;
};

const shortDay = (iso: string): string => new Date(iso).toLocaleDateString(undefined, { month: 'short', day: 'numeric', timeZone: 'UTC' });

export const rangeLabel = (range: Range): string | null => {
  if (range.dateFrom.length === 0 && range.dateTo.length === 0) return null;
  const preset = activePreset(range);
  if (preset !== null) return PRESETS.find((item) => item.id === preset)?.label ?? null;
  return `${range.dateFrom.length === 0 ? '…' : shortDay(range.dateFrom)} – ${range.dateTo.length === 0 ? '…' : shortDay(range.dateTo)}`;
};

function Month({ year, month, from, to, hover, onPick, onHover }: { year: number; month: number; from: string; to: string; hover: string | null; onPick: (day: string) => void; onHover: (day: string | null) => void }) {
  const first = new Date(Date.UTC(year, month, 1));
  const days = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
  const offset = (first.getUTCDay() + 6) % 7; // Monday first
  const today = new Date().toISOString().slice(0, 10);
  const end = to.length > 0 ? to : hover ?? '';
  const cells = [...Array.from({ length: offset }, () => null), ...Array.from({ length: days }, (_, index) => index + 1)];
  return (
    <div className="w-[248px]">
      <p className="mb-2 text-center text-small font-semibold">{first.toLocaleDateString(undefined, { month: 'long', year: 'numeric', timeZone: 'UTC' })}</p>
      <div className="grid grid-cols-7 text-center text-[11px] font-semibold text-subtle-foreground">
        {['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'].map((day) => (
          <span key={day} className="py-1">
            {day}
          </span>
        ))}
      </div>
      <div className="grid grid-cols-7">
        {cells.map((day, index) => {
          if (day === null) return <span key={`blank-${index}`} />;
          const key = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
          const isStart = key === from;
          const isEnd = key === end;
          const inRange = from.length > 0 && end.length > 0 && key > from && key < end;
          return (
            <button
              key={key}
              type="button"
              aria-label={new Date(`${key}T00:00:00Z`).toLocaleDateString(undefined, { dateStyle: 'full', timeZone: 'UTC' })}
              aria-pressed={isStart || isEnd}
              onClick={() => onPick(key)}
              onMouseEnter={() => onHover(key)}
              className={cn(
                'relative h-9 text-small tabular-nums transition-colors',
                inRange && 'bg-primary-soft text-foreground',
                (isStart || isEnd) && 'rounded-md bg-primary font-semibold text-primary-foreground',
                !isStart && !isEnd && !inRange && 'rounded-md hover:bg-surface-muted',
                key === today && !isStart && !isEnd && 'font-bold text-primary',
              )}
            >
              {day}
            </button>
          );
        })}
      </div>
    </div>
  );
}

/** Two-month range calendar. Picks a start day, then an end day. */
function RangeCalendar({ range, onChange }: { range: Range; onChange: (range: Range) => void }) {
  const anchor = range.dateFrom.length > 0 ? new Date(range.dateFrom) : new Date();
  const [view, setView] = useState({ year: anchor.getUTCFullYear(), month: anchor.getUTCMonth() - (range.dateFrom.length > 0 ? 0 : 1) });
  const [pendingStart, setPendingStart] = useState<string | null>(null);
  const [hover, setHover] = useState<string | null>(null);
  const normalized = new Date(Date.UTC(view.year, view.month, 1));
  const left = { year: normalized.getUTCFullYear(), month: normalized.getUTCMonth() };
  const rightDate = new Date(Date.UTC(left.year, left.month + 1, 1));
  const right = { year: rightDate.getUTCFullYear(), month: rightDate.getUTCMonth() };
  const from = pendingStart ?? (range.dateFrom.length > 0 ? dayKey(range.dateFrom) : '');
  const to = pendingStart !== null ? '' : range.dateTo.length > 0 ? dayKey(range.dateTo) : '';

  const pick = (day: string) => {
    if (pendingStart === null) {
      setPendingStart(day);
      return;
    }
    const [start, end] = day < pendingStart ? [day, pendingStart] : [pendingStart, day];
    setPendingStart(null);
    onChange({ dateFrom: fromDay(start), dateTo: toDay(end) });
  };

  return (
    <div onMouseLeave={() => setHover(null)}>
      <div className="mb-1 flex justify-between">
        <button type="button" aria-label="Previous month" className="grid h-8 w-8 place-items-center rounded-md hover:bg-surface-muted" onClick={() => setView({ year: left.year, month: left.month - 1 })}>
          <ChevronLeft className="h-4 w-4" aria-hidden="true" />
        </button>
        <button type="button" aria-label="Next month" className="grid h-8 w-8 place-items-center rounded-md hover:bg-surface-muted" onClick={() => setView({ year: left.year, month: left.month + 1 })}>
          <ChevronRight className="h-4 w-4" aria-hidden="true" />
        </button>
      </div>
      <div className="-mt-9 flex gap-6">
        <Month {...left} from={from} to={to} hover={pendingStart === null ? null : hover} onPick={pick} onHover={setHover} />
        <Month {...right} from={from} to={to} hover={pendingStart === null ? null : hover} onPick={pick} onHover={setHover} />
      </div>
      <p className="mt-2 text-caption text-muted-foreground" aria-live="polite">
        {pendingStart === null ? 'Pick a start date, then an end date.' : 'Now pick the end date.'}
      </p>
    </div>
  );
}

function CustomInputs({ range, onChange }: { range: Range; onChange: (range: Range) => void }) {
  return (
    <div className="grid grid-cols-2 gap-2">
      <label className="grid gap-1 text-caption font-semibold">
        From
        <Input type="date" value={dayKey(range.dateFrom)} onChange={(event) => onChange({ dateFrom: event.target.value ? fromDay(event.target.value) : '', dateTo: range.dateTo })} />
      </label>
      <label className="grid gap-1 text-caption font-semibold">
        To
        <Input type="date" value={dayKey(range.dateTo)} onChange={(event) => onChange({ dateFrom: range.dateFrom, dateTo: event.target.value ? toDay(event.target.value) : '' })} />
      </label>
    </div>
  );
}

function PresetList({ range, custom, onPreset, onCustom }: { range: Range; custom: boolean; onPreset: (preset: Preset) => void; onCustom: () => void }) {
  const active = activePreset(range);
  const item = (selected: boolean) =>
    cn('flex h-9 w-full items-center justify-between gap-3 rounded-md px-2.5 text-left text-small font-medium transition-colors', selected ? 'bg-primary-soft text-primary' : 'text-foreground hover:bg-surface-muted');
  return (
    <div className="grid content-start gap-0.5">
      {PRESETS.map((preset) => (
        <button key={preset.id} type="button" className={item(active === preset.id && !custom)} onClick={() => onPreset(preset.id)}>
          {preset.label}
          {active === preset.id && !custom ? <Check className="h-4 w-4" aria-hidden="true" /> : null}
        </button>
      ))}
      <button type="button" className={item(custom || (active === null && range.dateFrom.length > 0))} onClick={onCustom}>
        Custom
      </button>
    </div>
  );
}

/** Inline variant (mobile filter sheet): presets, plus date inputs for Custom. */
export function DateRangePicker({ dateFrom, dateTo, onChange }: { dateFrom: string; dateTo: string; onChange: (next: Range) => void }) {
  const range = { dateFrom, dateTo };
  const [custom, setCustom] = useState(false);
  return (
    <div className="grid gap-3">
      <div className="flex flex-wrap gap-2">
        {PRESETS.map((preset) => {
          const selected = activePreset(range) === preset.id && !custom;
          return (
            <button
              key={preset.id}
              type="button"
              aria-pressed={selected}
              onClick={() => {
                setCustom(false);
                onChange(presetRange(preset.id));
              }}
              className={cn('h-8 rounded-pill border px-3 text-caption font-semibold transition-colors', selected ? 'border-primary bg-primary-soft text-primary' : 'border-border bg-surface text-muted-foreground')}
            >
              {preset.label}
            </button>
          );
        })}
        <button
          type="button"
          aria-pressed={custom}
          onClick={() => setCustom(true)}
          className={cn('h-8 rounded-pill border px-3 text-caption font-semibold transition-colors', custom ? 'border-primary bg-primary-soft text-primary' : 'border-border bg-surface text-muted-foreground')}
        >
          Custom
        </button>
      </div>
      {custom ? <CustomInputs range={range} onChange={onChange} /> : null}
    </div>
  );
}

/** Popover variant (desktop filter bar): preset list on the left, two-month calendar on the right. */
export function DateRangePopover({ dateFrom, dateTo, onChange }: { dateFrom: string; dateTo: string; onChange: (next: Range) => void }) {
  const reduce = useReducedMotion();
  const { open, toggle, close, rootRef, triggerRef } = usePopover();
  const [custom, setCustom] = useState(false);
  const range = { dateFrom, dateTo };
  const label = rangeLabel(range);
  return (
    <div ref={rootRef} className="relative">
      <button
        ref={triggerRef}
        type="button"
        aria-haspopup="dialog"
        aria-expanded={open}
        onClick={toggle}
        className={cn(
          'inline-flex h-10 items-center gap-2 rounded-md border px-3 text-small font-medium transition-colors',
          label === null ? 'border-border bg-surface text-foreground hover:border-border-strong' : 'border-primary/40 bg-primary-soft text-primary',
        )}
      >
        <CalendarDays className="h-4 w-4" aria-hidden="true" />
        {label ?? 'Date range'}
        <ChevronDown className="h-3.5 w-3.5 opacity-60" aria-hidden="true" />
      </button>
      <AnimatePresence>
        {open ? (
          <motion.div
            role="dialog"
            aria-label="Choose a date range"
            initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.98, y: -4 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.98 }}
            transition={{ duration: 0.12 }}
            className="absolute right-0 top-full z-40 mt-1.5 flex origin-top-right gap-4 rounded-lg border border-border bg-surface p-3 shadow-md"
          >
            <div className="w-36 border-r border-border pr-3">
              <PresetList
                range={range}
                custom={custom}
                onPreset={(preset) => {
                  setCustom(false);
                  onChange(presetRange(preset));
                  close();
                }}
                onCustom={() => setCustom(true)}
              />
              {label === null ? null : (
                <button
                  type="button"
                  className="mt-2 h-8 w-full rounded-md text-caption font-semibold text-muted-foreground hover:bg-surface-muted hover:text-foreground"
                  onClick={() => {
                    onChange({ dateFrom: '', dateTo: '' });
                    close();
                  }}
                >
                  Clear dates
                </button>
              )}
            </div>
            <RangeCalendar
              range={range}
              onChange={(next) => {
                onChange(next);
                setCustom(false);
                close();
              }}
            />
          </motion.div>
        ) : null}
      </AnimatePresence>
    </div>
  );
}
