'use client';

import Link from 'next/link';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { useAdminDisputes } from '@/lib/queries/use-admin';
import type { AdminDisputesQueryInput } from '@alqove/api-client';

const STATUS_LABEL: Record<string, string> = {
  needs_response: 'Needs response',
  under_review: 'Under review',
  won: 'Won',
  lost: 'Lost',
  warning_needs_response: 'Warning · needs response',
  warning_under_review: 'Warning · under review',
  warning_closed: 'Warning · closed',
  charge_refunded: 'Charge refunded',
};

// Each chip has a URL key. The default chip ('Open' / needs_response) is
// represented by an empty URL — bookmarking /admin/disputes lands on Open.
// 'All' uses the explicit ?status=all sentinel because it semantically differs
// from the default.
type ChipKey = 'open' | 'under_review' | 'won' | 'lost' | 'all';

const FILTERS: {
  label: string;
  key: ChipKey;
  status: AdminDisputesQueryInput['status'] | undefined;
}[] = [
  { label: 'Open', key: 'open', status: 'needs_response' },
  { label: 'Under review', key: 'under_review', status: 'under_review' },
  { label: 'Won', key: 'won', status: 'won' },
  { label: 'Lost', key: 'lost', status: 'lost' },
  { label: 'All', key: 'all', status: undefined },
];

const KEYS = FILTERS.map((f) => f.key);

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

export function DisputesClient() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const raw = searchParams.get('status') ?? 'open';
  const activeKey: ChipKey = (KEYS as readonly string[]).includes(raw) ? (raw as ChipKey) : 'open';
  const status = FILTERS.find((f) => f.key === activeKey)!.status;

  const setKey = (next: ChipKey) => {
    const params = new URLSearchParams(searchParams.toString());
    if (next === 'open') params.delete('status');
    else params.set('status', next);
    const qs = params.toString();
    router.replace(qs ? `${pathname}?${qs}` : pathname);
  };

  const { data, isLoading, isError } = useAdminDisputes({ status });
  const rows = data?.data ?? [];

  return (
    <div>
      <h1 className="text-2xl font-bold text-slate-900">Disputes</h1>
      <p className="mt-1 text-sm text-slate-500">Stripe dispute queue.</p>

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

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

      <div className="mt-4 bg-white rounded border border-slate-200">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-slate-200">
              <th className="text-left px-4 py-3 font-medium text-slate-500">Purchase</th>
              <th className="text-left px-4 py-3 font-medium text-slate-500">Buyer</th>
              <th className="text-left px-4 py-3 font-medium text-slate-500">Amount</th>
              <th className="text-left px-4 py-3 font-medium text-slate-500">State</th>
              <th className="text-left px-4 py-3 font-medium text-slate-500">Filed</th>
            </tr>
          </thead>
          <tbody>
            {isLoading && (
              <tr><td colSpan={5} className="px-4 py-6 text-center text-sm text-slate-400">Loading…</td></tr>
            )}
            {!isLoading && rows.length === 0 && (
              <tr><td colSpan={5} className="px-4 py-6 text-center text-sm text-slate-400">No disputes.</td></tr>
            )}
            {rows.map((r) => {
              const name = [r.buyer_first_name, r.buyer_last_name].filter(Boolean).join(' ') || '—';
              return (
                <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">
                    <Link href={`/admin/disputes/${r.purchase_id}`} className="text-forest-700 hover:underline">
                      {r.purchase_id.slice(0, 8)}
                    </Link>
                  </td>
                  <td className="px-4 py-3 text-slate-500">{name}</td>
                  <td className="px-4 py-3 text-slate-900">{formatPrice(r.amount_cents)}</td>
                  <td className="px-4 py-3 text-slate-500">{STATUS_LABEL[r.status] ?? r.status}</td>
                  <td className="px-4 py-3 text-slate-500 text-xs">
                    {new Date(r.created_at).toLocaleString()}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}
