'use client';

import { useEffect, useRef, useState } from 'react';
import { Check, ChevronDown, RotateCcw } from 'lucide-react';
import DashboardDateFilter, {
  resolveDashboardDateRange,
  type DashboardDateFilterValue,
} from '@/components/admin/dashboard/DashboardDateFilter';

// ─── Filter state ────────────────────────────────────────────────────────────
// Mirrors src/lib/validations/report.validation.ts (the server validates it
// again — this is only the UI's shape).

export const STATUS_OPTIONS = ['pending', 'confirmed', 'shipped', 'delivered', 'cancelled', 'returned', 'refunded'];
export const METHOD_OPTIONS = ['cod', 'bank_transfer', 'paypal', 'stripe'];
export const PAYMENT_STATUS_OPTIONS = ['pending', 'paid', 'failed', 'refunded', 'partially_refunded'];

export const SECTION_OPTIONS: { id: string; label: string }[] = [
  { id: 'summary', label: 'Sales Summary' },
  { id: 'trend', label: 'Sales Trend' },
  { id: 'status', label: 'Order Status' },
  { id: 'payments', label: 'Payments' },
  { id: 'products', label: 'Products' },
  { id: 'categories', label: 'Categories' },
  { id: 'customers', label: 'Customers' },
  { id: 'geography', label: 'Cities' },
  { id: 'coupons', label: 'Coupons' },
  { id: 'returns', label: 'Returns & Refunds' },
  { id: 'inventory', label: 'Inventory' },
  { id: 'reviews', label: 'Reviews' },
  { id: 'carts', label: 'Carts & Wishlists' },
];

export interface ReportFilterState {
  date: DashboardDateFilterValue;
  statuses: string[];
  paymentMethods: string[];
  paymentStatuses: string[];
  customerType: 'all' | 'registered' | 'guest';
  categoryId: string;
  city: string;
  coupon: string; // 'all' | 'with' | 'without' | 'code:<CODE>'
  groupBy: 'day' | 'week' | 'month';
  topN: number;
  sections: string[];
}

export const DEFAULT_REPORT_FILTERS: ReportFilterState = {
  date: { preset: 'all', customStart: '', customEnd: '' },
  statuses: [],
  paymentMethods: [],
  paymentStatuses: [],
  customerType: 'all',
  categoryId: '',
  city: '',
  coupon: 'all',
  groupBy: 'day',
  topN: 10,
  sections: SECTION_OPTIONS.map((s) => s.id),
};

export function filtersToQuery(f: ReportFilterState): string {
  const q = new URLSearchParams();
  const { startDate, endDate } = resolveDashboardDateRange(f.date);
  if (startDate && endDate) {
    q.set('startDate', startDate);
    q.set('endDate', endDate);
  }
  if (f.statuses.length) q.set('statuses', f.statuses.join(','));
  if (f.paymentMethods.length) q.set('paymentMethods', f.paymentMethods.join(','));
  if (f.paymentStatuses.length) q.set('paymentStatuses', f.paymentStatuses.join(','));
  if (f.customerType !== 'all') q.set('customerType', f.customerType);
  if (f.categoryId) q.set('categoryId', f.categoryId);
  if (f.city) q.set('city', f.city);
  if (f.coupon.startsWith('code:')) q.set('couponCode', f.coupon.slice(5));
  else if (f.coupon !== 'all') q.set('coupon', f.coupon);
  q.set('groupBy', f.groupBy);
  q.set('topN', String(f.topN));
  // All sections = omit (server default); keeps the URL short.
  if (f.sections.length && f.sections.length < SECTION_OPTIONS.length) q.set('sections', f.sections.join(','));
  return q.toString();
}

export const human = (s: string) => s.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());

export interface FilterOptions {
  categories: { id: string; name: string; depth: number }[];
  cities: { city: string; orders: number }[];
  coupons: string[];
}

// ─── Small controls ──────────────────────────────────────────────────────────

const CONTROL_STYLE: React.CSSProperties = {
  background: 'var(--color-surface)',
  border: '1px solid var(--color-border)',
  color: 'var(--color-text)',
};

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <label className="flex flex-col gap-1 min-w-0">
      <span className="text-[11px] font-medium uppercase tracking-wide" style={{ color: 'var(--color-text-secondary)' }}>
        {label}
      </span>
      {children}
    </label>
  );
}

function Select({ value, onChange, children }: { value: string; onChange: (v: string) => void; children: React.ReactNode }) {
  return (
    <select
      value={value}
      onChange={(e) => onChange(e.target.value)}
      className="w-full px-2.5 py-2 rounded-lg text-sm outline-none focus:ring-2"
      style={CONTROL_STYLE}
    >
      {children}
    </select>
  );
}

function MultiSelect({
  options,
  value,
  onChange,
  placeholder,
  renderLabel = human,
}: {
  options: string[];
  value: string[];
  onChange: (v: string[]) => void;
  placeholder: string;
  renderLabel?: (v: string) => string;
}) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    const onDown = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('keydown', onKey);
    };
  }, [open]);

  const toggle = (opt: string) => onChange(value.includes(opt) ? value.filter((v) => v !== opt) : [...value, opt]);
  const summary =
    value.length === 0 ? placeholder : value.length <= 2 ? value.map(renderLabel).join(', ') : `${value.length} selected`;

  return (
    <div className="relative" ref={ref}>
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        className="w-full flex items-center justify-between gap-2 px-2.5 py-2 rounded-lg text-sm text-left"
        style={CONTROL_STYLE}
        aria-haspopup="listbox"
        aria-expanded={open}
      >
        <span className="truncate" style={{ color: value.length ? 'var(--color-text)' : 'var(--color-text-secondary)' }}>
          {summary}
        </span>
        <ChevronDown size={14} className="shrink-0" style={{ color: 'var(--color-text-secondary)' }} />
      </button>
      {open && (
        <div
          className="absolute z-30 mt-1 w-full min-w-[12rem] max-h-72 overflow-auto rounded-lg shadow-lg p-1"
          style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)' }}
          role="listbox"
          aria-multiselectable="true"
        >
          {options.map((opt) => {
            const on = value.includes(opt);
            return (
              <button
                key={opt}
                type="button"
                role="option"
                aria-selected={on}
                onClick={() => toggle(opt)}
                className="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-sm text-left hover:opacity-80"
                style={{ color: 'var(--color-text)', background: on ? 'var(--color-surface-alt)' : 'transparent' }}
              >
                <span
                  className="w-4 h-4 rounded flex items-center justify-center shrink-0"
                  style={{ border: '1px solid var(--color-border)', background: on ? 'var(--color-cta)' : 'transparent' }}
                >
                  {on && <Check size={12} color="white" />}
                </span>
                {renderLabel(opt)}
              </button>
            );
          })}
          {value.length > 0 && (
            <button
              type="button"
              onClick={() => onChange([])}
              className="w-full text-xs px-2 py-1.5 mt-1 rounded-md text-left"
              style={{ color: 'var(--color-cta)', borderTop: '1px solid var(--color-border)' }}
            >
              Clear selection
            </button>
          )}
        </div>
      )}
    </div>
  );
}

// ─── Filter bar ──────────────────────────────────────────────────────────────

export default function ReportFilters({
  value,
  onChange,
  options,
  loading,
}: {
  value: ReportFilterState;
  onChange: (next: ReportFilterState) => void;
  options: FilterOptions | null;
  loading: boolean;
}) {
  const set = <K extends keyof ReportFilterState>(key: K, v: ReportFilterState[K]) => onChange({ ...value, [key]: v });
  const sectionLabel = (id: string) => SECTION_OPTIONS.find((s) => s.id === id)?.label ?? id;
  const isDefault = filtersToQuery(value) === filtersToQuery(DEFAULT_REPORT_FILTERS);

  return (
    <div className="p-4 rounded-xl space-y-4" style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)' }}>
      <DashboardDateFilter value={value.date} onChange={(d) => set('date', d)} loading={loading} />

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-5 gap-3">
        <Field label="Order status">
          <MultiSelect
            options={STATUS_OPTIONS}
            value={value.statuses}
            onChange={(v) => set('statuses', v)}
            placeholder="Delivered only (revenue)"
          />
        </Field>
        <Field label="Payment method">
          <MultiSelect options={METHOD_OPTIONS} value={value.paymentMethods} onChange={(v) => set('paymentMethods', v)} placeholder="All methods" />
        </Field>
        <Field label="Payment status">
          <MultiSelect options={PAYMENT_STATUS_OPTIONS} value={value.paymentStatuses} onChange={(v) => set('paymentStatuses', v)} placeholder="All payment statuses" />
        </Field>
        <Field label="Customer type">
          <Select value={value.customerType} onChange={(v) => set('customerType', v as ReportFilterState['customerType'])}>
            <option value="all">All customers</option>
            <option value="registered">Registered only</option>
            <option value="guest">Guest checkout only</option>
          </Select>
        </Field>
        <Field label="Category">
          <Select value={value.categoryId} onChange={(v) => set('categoryId', v)}>
            <option value="">All categories</option>
            {options?.categories.map((c) => (
              <option key={c.id} value={c.id}>
                {`${'   '.repeat(c.depth)}${c.depth ? '└ ' : ''}${c.name}`}
              </option>
            ))}
          </Select>
        </Field>
        <Field label="City">
          <Select value={value.city} onChange={(v) => set('city', v)}>
            <option value="">All cities</option>
            {options?.cities.map((c) => (
              <option key={c.city} value={c.city}>
                {c.city} ({c.orders})
              </option>
            ))}
          </Select>
        </Field>
        <Field label="Coupon">
          <Select value={value.coupon} onChange={(v) => set('coupon', v)}>
            <option value="all">All orders</option>
            <option value="with">With any coupon</option>
            <option value="without">Without coupon</option>
            {options && options.coupons.length > 0 && (
              <optgroup label="Specific coupon">
                {options.coupons.map((c) => (
                  <option key={c} value={`code:${c}`}>{c}</option>
                ))}
              </optgroup>
            )}
          </Select>
        </Field>
        <Field label="Trend by">
          <Select value={value.groupBy} onChange={(v) => set('groupBy', v as ReportFilterState['groupBy'])}>
            <option value="day">Day</option>
            <option value="week">Week</option>
            <option value="month">Month</option>
          </Select>
        </Field>
        <Field label="Rows per table">
          <Select value={String(value.topN)} onChange={(v) => set('topN', Number(v))}>
            {[10, 25, 50, 100].map((n) => (
              <option key={n} value={n}>Top {n}</option>
            ))}
          </Select>
        </Field>
        <Field label="Sections">
          <MultiSelect
            options={SECTION_OPTIONS.map((s) => s.id)}
            value={value.sections}
            onChange={(v) => set('sections', v.length ? SECTION_OPTIONS.map((s) => s.id).filter((id) => v.includes(id)) : [])}
            placeholder="Pick at least one"
            renderLabel={sectionLabel}
          />
        </Field>
      </div>

      <div className="flex flex-wrap items-center justify-between gap-2 text-xs" style={{ color: 'var(--color-text-secondary)' }}>
        <span>
          {value.categoryId
            ? 'Category filter: order totals include the whole order; product, category and profit figures count only this category’s items.'
            : 'Status breakdown always shows every status. Inventory is a live snapshot and ignores the date filter.'}
        </span>
        <button
          type="button"
          onClick={() => onChange(DEFAULT_REPORT_FILTERS)}
          disabled={isDefault}
          className="flex items-center gap-1 px-2.5 py-1.5 rounded-lg font-medium disabled:opacity-40"
          style={{ border: '1px solid var(--color-border)', color: 'var(--color-text)' }}
        >
          <RotateCcw size={12} /> Reset filters
        </button>
      </div>
    </div>
  );
}
