'use client';

import { useRouter, useSearchParams } from 'next/navigation';
import { useSellerReturns } from '@/lib/queries/use-returns';
import { ReturnStateBadge } from '@/components/returns/return-state-badge';
import type { ReturnState } from '@alqove/api-client';

const STATE_CHIPS: { value: ReturnState | 'all'; label: string }[] = [
  { value: 'requested', label: 'Awaiting' },
  { value: 'approved', label: 'Approved' },
  { value: 'rejected', label: 'Declined' },
  { value: 'refunded', label: 'Refunded' },
  { value: 'closed', label: 'Closed' },
  { value: 'cancelled', label: 'Cancelled' },
  { value: 'all', label: 'All' },
];

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

export function SellerReturnsClient() {
  const router = useRouter();
  const params = useSearchParams();
  const stateParam = (params.get('state') ?? 'requested') as ReturnState | 'all';

  const { data, isLoading, isError } = useSellerReturns(
    stateParam === 'all' ? {} : { state: stateParam as ReturnState },
  );

  const returns = data?.data ?? [];

  const setState = (s: ReturnState | 'all') => {
    const u = new URLSearchParams(params.toString());
    if (s === 'all') u.delete('state');
    else u.set('state', s);
    router.push(`/seller/returns?${u.toString()}`);
  };

  return (
    <div>
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-ink">Returns</h1>
          <p className="mt-1 text-sm text-ink/60">
            Review and respond to buyer return requests across your stores.
          </p>
        </div>
      </div>

      <div className="mt-6 flex flex-wrap items-center gap-2">
        {STATE_CHIPS.map((c) => (
          <button
            key={c.value}
            type="button"
            onClick={() => setState(c.value)}
            data-testid={`returns-filter-${c.value}`}
            className={`rounded-full px-3 py-1 text-sm ${
              stateParam === c.value
                ? 'bg-forest text-white'
                : 'bg-bone text-ink hover:bg-forest/10'
            }`}
          >
            {c.label}
          </button>
        ))}
      </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 returns…</div>
        )}
        {isError && (
          <div className="p-8 text-center text-sm text-terracotta">
            Failed to load returns.
          </div>
        )}
        {!isLoading && !isError && returns.length === 0 && (
          <div className="p-8 text-center text-sm text-ink/60" data-testid="returns-empty">
            No returns match this filter.
          </div>
        )}
        {!isLoading && !isError && returns.length > 0 && (
          <table className="w-full text-sm">
            <thead className="bg-bone/60">
              <tr>
                <Th>State</Th>
                <Th>Order</Th>
                <Th>Buyer</Th>
                <Th>Reason</Th>
                <Th>Refund</Th>
                <Th>Updated</Th>
              </tr>
            </thead>
            <tbody>
              {returns.map((r) => (
                <tr
                  key={r.id}
                  role="link"
                  tabIndex={0}
                  onClick={() => router.push(`/seller/orders/${r.order_id}`)}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter' || e.key === ' ') {
                      e.preventDefault();
                      router.push(`/seller/orders/${r.order_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">
                    <ReturnStateBadge state={r.state} />
                  </td>
                  <td className="px-4 py-3 font-mono text-xs text-ink">
                    {r.order_id.slice(0, 8)}…
                  </td>
                  <td className="px-4 py-3 text-ink">{r.counterparty_name ?? '—'}</td>
                  <td className="px-4 py-3 text-ink/70">
                    {r.reason.replace(/_/g, ' ')}
                  </td>
                  <td className="px-4 py-3 text-ink">
                    {r.refund_amount_cents !== null
                      ? `$${(r.refund_amount_cents / 100).toFixed(2)}`
                      : '—'}
                  </td>
                  <td className="px-4 py-3 text-xs text-ink/60">
                    {formatDate(r.updated_at)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </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>
  );
}
