'use client';

import { useState } from 'react';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { useAdminReturnsList } from '@/lib/queries/use-returns';
import { AdminResolveReturnDialog } from '@/components/admin/admin-resolve-return-dialog';
import { ReturnStateBadge } from '@/components/returns/return-state-badge';
import type { OrderReturnSummary } from '@alqove/api-client';

type ScopeKey = 'open' | 'resolved' | 'all';

const SCOPES: { key: ScopeKey; label: string; includeResolved: boolean }[] = [
  { key: 'open', label: 'Open', includeResolved: false },
  { key: 'resolved', label: 'Resolved', includeResolved: true },
  { key: 'all', label: 'All', includeResolved: true },
];

const SCOPE_KEYS = SCOPES.map((s) => s.key);
const PER_PAGE = 20;

export function AdminReturnsClient() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const raw = searchParams.get('scope') ?? 'open';
  const activeKey: ScopeKey = (SCOPE_KEYS as readonly string[]).includes(raw)
    ? (raw as ScopeKey)
    : 'open';
  const scope = SCOPES.find((s) => s.key === activeKey)!;
  const page = Math.max(1, Number(searchParams.get('page') ?? '1'));

  const writeParams = (mut: (p: URLSearchParams) => void) => {
    const params = new URLSearchParams(searchParams.toString());
    mut(params);
    const qs = params.toString();
    router.replace(qs ? `${pathname}?${qs}` : pathname);
  };

  const setScope = (next: ScopeKey) => {
    writeParams((p) => {
      if (next === 'open') p.delete('scope');
      else p.set('scope', next);
      p.delete('page');
    });
  };

  const setPage = (next: number) => {
    writeParams((p) => {
      if (next <= 1) p.delete('page');
      else p.set('page', String(next));
    });
  };

  const { data, isLoading, isError } = useAdminReturnsList({
    include_resolved: scope.includeResolved,
    page,
    per_page: PER_PAGE,
  });
  const rows = data?.data ?? [];
  const meta = data?.meta;

  const [reviewing, setReviewing] = useState<OrderReturnSummary | null>(null);

  return (
    <div>
      <h1 className="text-2xl font-bold text-slate-900">Returns</h1>
      <p className="mt-1 text-sm text-slate-500">
        Returns escalated to Alqove support.
      </p>

      <div className="mt-4 flex gap-2">
        {SCOPES.map((s) => (
          <button
            key={s.key}
            onClick={() => setScope(s.key)}
            className={`rounded-md px-3 py-1 text-xs font-medium ${
              activeKey === s.key
                ? 'bg-slate-900 text-white'
                : 'border border-slate-300 text-slate-600 hover:bg-slate-50'
            }`}
          >
            {s.label}
          </button>
        ))}
      </div>

      {isError && (
        <p className="mt-4 rounded bg-red-50 p-3 text-sm text-red-700">
          Couldn&apos;t load returns. You may need admin access.
        </p>
      )}

      <div className="mt-4 overflow-hidden rounded border border-slate-200 bg-white">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-slate-200">
              <th className="px-4 py-3 text-left font-medium text-slate-500">Order</th>
              <th className="px-4 py-3 text-left font-medium text-slate-500">Buyer</th>
              <th className="px-4 py-3 text-left font-medium text-slate-500">State</th>
              <th className="px-4 py-3 text-left font-medium text-slate-500">Escalation</th>
              <th className="px-4 py-3 text-left font-medium text-slate-500">Updated</th>
              <th className="px-4 py-3 text-left font-medium text-slate-500" />
            </tr>
          </thead>
          <tbody>
            {isLoading && (
              <tr>
                <td colSpan={6} className="px-4 py-6 text-center text-sm text-slate-400">
                  Loading…
                </td>
              </tr>
            )}
            {!isLoading && rows.length === 0 && (
              <tr>
                <td colSpan={6} className="px-4 py-6 text-center text-sm text-slate-400">
                  No escalated returns.
                </td>
              </tr>
            )}
            {rows.map((r) => (
              <tr key={r.id} className="border-b border-slate-100 last:border-0 hover:bg-slate-50">
                <td className="px-4 py-3 font-mono text-xs text-slate-700">
                  {r.order_id.slice(0, 8)}
                </td>
                <td className="px-4 py-3 text-slate-700">{r.counterparty_name ?? '—'}</td>
                <td className="px-4 py-3">
                  <ReturnStateBadge state={r.state} />
                </td>
                <td className="px-4 py-3 text-slate-600">
                  {r.escalation ? (
                    <span
                      className="line-clamp-2 text-xs"
                      title={r.escalation.reason}
                    >
                      {r.escalation.reason}
                    </span>
                  ) : (
                    <span className="text-slate-400">—</span>
                  )}
                </td>
                <td className="px-4 py-3 text-xs text-slate-500">
                  {new Date(r.updated_at).toLocaleString()}
                </td>
                <td className="px-4 py-3">
                  <button
                    type="button"
                    onClick={() => setReviewing(r)}
                    className="rounded-md border border-slate-300 px-3 py-1 text-xs text-slate-700 hover:bg-slate-50"
                  >
                    Review
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {meta && meta.last_page > 1 && (
        <div className="mt-4 flex items-center justify-between text-xs text-slate-600">
          <span>
            Page {meta.current_page} of {meta.last_page} · {meta.total} total
          </span>
          <div className="flex gap-2">
            <button
              type="button"
              onClick={() => setPage(page - 1)}
              disabled={page <= 1}
              className="rounded border border-slate-300 px-3 py-1 disabled:cursor-not-allowed disabled:opacity-50 hover:bg-slate-50"
            >
              Previous
            </button>
            <button
              type="button"
              onClick={() => setPage(page + 1)}
              disabled={page >= meta.last_page}
              className="rounded border border-slate-300 px-3 py-1 disabled:cursor-not-allowed disabled:opacity-50 hover:bg-slate-50"
            >
              Next
            </button>
          </div>
        </div>
      )}

      {reviewing && (
        <AdminResolveReturnDialog
          return={reviewing}
          open
          onClose={() => setReviewing(null)}
        />
      )}
    </div>
  );
}
