'use client';

import { useQuery } from '@tanstack/react-query';
import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react';
import type { OrderDetail } from '@alqove/api-client';
import { api } from '@/lib/api';
import { useSelectedStoreId } from '@/lib/stores/store-context';
import { OrderStatusBadge } from '@/components/seller/order-status-badge';
import { ShipByCell } from '@/components/seller/ship-by-cell';
import { EmptyState } from '@/components/seller/empty-state';

const STATUS_CHIPS = [
  { value: 'all', label: 'All' },
  { value: 'paid', label: 'Paid' },
  { value: 'shipped', label: 'Shipped' },
  { value: 'delivered', label: 'Delivered' },
  { value: 'cancelled', label: 'Cancelled' },
] as const;

function formatDollars(cents: number) {
  return `$${(cents / 100).toFixed(2)}`;
}

function formatDate(iso: string) {
  return new Date(iso).toLocaleDateString();
}

export function OrdersListClient() {
  const storeId = useSelectedStoreId();
  const router = useRouter();
  const params = useSearchParams();

  const status = params.get('status') ?? 'all';
  const bucket = params.get('bucket') ?? '';
  const sort = params.get('sort') ?? 'placed_desc';
  const page = Number(params.get('page') ?? '1');

  const [qInput, setQInput] = useState(params.get('q') ?? '');
  const qDebounced = useDebouncedValue(qInput, 300);

  const queryKey = useMemo(
    () => ['seller-orders', storeId, status, qDebounced, sort, bucket, page],
    [storeId, status, qDebounced, sort, bucket, page],
  );

  const { data, isLoading, isError } = useQuery({
    queryKey,
    enabled: !!storeId,
    queryFn: () => {
      const p: Record<string, string> = { sort, page: String(page) };
      if (status !== 'all') p.status = status;
      if (qDebounced) p.q = qDebounced;
      if (bucket) p.bucket = bucket;
      return api.orders.list(storeId!, p);
    },
  });

  const orders: OrderDetail[] = data?.data ?? [];
  const meta = data?.meta;

  const pushParams = (next: Record<string, string | null>) => {
    const u = new URLSearchParams(params.toString());
    Object.entries(next).forEach(([k, v]) => {
      if (v === null || v === '') u.delete(k);
      else u.set(k, v);
    });
    u.delete('page');
    router.push(`/seller/orders?${u.toString()}`);
  };

  useEffect(() => {
    pushParams({ q: qDebounced || null });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [qDebounced]);

  return (
    <div>
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-ink">Orders</h1>
          <p className="mt-1 text-sm text-ink/60">
            Manage and fulfill incoming orders.
          </p>
        </div>
      </div>

      <div className="mt-6 flex flex-wrap items-center gap-2">
        {STATUS_CHIPS.map((c) => (
          <button
            key={c.value}
            onClick={() =>
              pushParams({
                status: c.value === 'all' ? null : c.value,
                bucket: null,
              })
            }
            className={`rounded-full px-3 py-1 text-sm ${
              status === c.value || (c.value === 'all' && status === 'all')
                ? 'bg-forest text-white'
                : 'bg-bone text-ink hover:bg-forest/10'
            }`}
          >
            {c.label}
          </button>
        ))}
        <div className="ml-auto flex items-center gap-2">
          <input
            value={qInput}
            onChange={(e) => setQInput(e.target.value)}
            placeholder="Search order ID or buyer…"
            className="rounded border border-forest/20 px-3 py-1.5 text-sm outline-none focus:border-forest"
          />
          <select
            value={sort}
            onChange={(e) => pushParams({ sort: e.target.value })}
            className="rounded border border-forest/20 bg-white px-2 py-1.5 text-sm"
          >
            <option value="placed_desc">Newest first</option>
            <option value="placed_asc">Oldest first</option>
            <option value="ship_by_asc">Ship-by soonest</option>
            <option value="ship_by_desc">Ship-by latest</option>
            <option value="total_desc">Total high→low</option>
            <option value="total_asc">Total low→high</option>
          </select>
        </div>
      </div>

      <div className="mt-4 overflow-hidden rounded-md border border-forest/20 bg-white">
        {isLoading && (
          <div className="p-8 text-center text-sm text-ink/60">
            Loading orders…
          </div>
        )}
        {isError && (
          <div className="p-8 text-center text-sm text-terracotta">
            Failed to load orders.
          </div>
        )}
        {!isLoading && !isError && orders.length === 0 && (
          <EmptyState
            title="No orders"
            description="No orders match the current filters."
          />
        )}
        {!isLoading && !isError && orders.length > 0 && (
          <table className="w-full text-sm">
            <thead className="bg-bone/60">
              <tr>
                <Th>Order</Th>
                <Th>Buyer</Th>
                <Th>Items</Th>
                <Th>Total</Th>
                <Th>Status</Th>
                <Th>Ship-by</Th>
                <Th>Placed</Th>
              </tr>
            </thead>
            <tbody>
              {orders.map((o) => {
                const total = o.subtotal + o.shipping_cost;
                const buyer =
                  [o.buyer?.first_name, o.buyer?.last_name]
                    .filter(Boolean)
                    .join(' ') || '—';
                return (
                  <tr
                    key={o.id}
                    role="link"
                    tabIndex={0}
                    onClick={() => router.push(`/seller/orders/${o.id}`)}
                    onKeyDown={(e: KeyboardEvent<HTMLTableRowElement>) => {
                      if (e.key === 'Enter' || e.key === ' ') {
                        e.preventDefault();
                        router.push(`/seller/orders/${o.id}`);
                      }
                    }}
                    className="cursor-pointer border-t border-forest/10 hover:bg-bone/40 focus:outline-none focus:ring-2 focus:ring-forest/30"
                  >
                    <td className="px-4 py-3 font-mono text-xs text-ink">
                      {o.id.slice(0, 8)}…
                    </td>
                    <td className="px-4 py-3 text-ink">{buyer}</td>
                    <td className="px-4 py-3 text-ink/70">{o.items.length}</td>
                    <td className="px-4 py-3 text-ink">
                      {formatDollars(total)}
                    </td>
                    <td className="px-4 py-3">
                      <OrderStatusBadge status={o.status} />
                    </td>
                    <td className="px-4 py-3">
                      <ShipByCell shipBy={o.ship_by} status={o.status} />
                    </td>
                    <td className="px-4 py-3 text-xs text-ink/60">
                      {formatDate(o.created_at)}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>

      {meta && meta.last_page && meta.last_page > 1 && (
        <div className="mt-4 flex items-center justify-between text-sm">
          <span className="text-ink/60">
            Page {meta.current_page} of {meta.last_page}
          </span>
          <div className="flex gap-2">
            <button
              disabled={page <= 1}
              onClick={() => router.push(pageHref(params, page - 1))}
              className="rounded border border-forest/20 px-3 py-1 disabled:opacity-40"
            >
              Prev
            </button>
            <button
              disabled={page >= (meta.last_page ?? 1)}
              onClick={() => router.push(pageHref(params, page + 1))}
              className="rounded border border-forest/20 px-3 py-1 disabled:opacity-40"
            >
              Next
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

function Th({ children }: { children: React.ReactNode }) {
  return (
    <th className="px-4 py-2 text-left text-xs font-semibold uppercase tracking-wide text-ink/60">
      {children}
    </th>
  );
}

function pageHref(
  params: URLSearchParams | { toString(): string },
  page: number,
) {
  const u = new URLSearchParams(params.toString());
  u.set('page', String(page));
  return `/seller/orders?${u.toString()}`;
}

function useDebouncedValue<T>(value: T, delayMs: number): T {
  const [v, setV] = useState(value);
  const ref = useRef<ReturnType<typeof setTimeout> | null>(null);
  useEffect(() => {
    if (ref.current) clearTimeout(ref.current);
    ref.current = setTimeout(() => setV(value), delayMs);
    return () => {
      if (ref.current) clearTimeout(ref.current);
    };
  }, [value, delayMs]);
  return v;
}
