'use client';

import { useCallback } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useNotifications, useMarkAllNotificationsRead } from '@/lib/queries/use-notifications';
import {
  InboxCategoryTabs,
  type InboxCategory,
} from '@/components/seller/inbox-category-tabs';
import { NotificationRow } from '@/components/notifications/notification-row';
import { EmptyState } from '@/components/seller/empty-state';

const CATEGORY_KEYS: InboxCategory[] = ['all', 'orders', 'shipping', 'payouts', 'system'];

function categoryFromParams(value: string | null): InboxCategory {
  if (value && (CATEGORY_KEYS as string[]).includes(value)) {
    return value as InboxCategory;
  }
  return 'all';
}

export function InboxClient() {
  const router = useRouter();
  const params = useSearchParams();

  const category = categoryFromParams(params.get('category'));
  const readFilter = params.get('filter') === 'unread' ? 'unread' : 'all';

  const updateParam = useCallback(
    (key: string, value: string | null) => {
      const next = new URLSearchParams(params.toString());
      if (value === null || value === 'all') {
        next.delete(key);
      } else {
        next.set(key, value);
      }
      const qs = next.toString();
      router.replace(qs ? `/seller/inbox?${qs}` : '/seller/inbox');
    },
    [params, router],
  );

  const { data, fetchNextPage, hasNextPage, isLoading, isFetchingNextPage } =
    useNotifications(readFilter, category);
  const markAll = useMarkAllNotificationsRead();
  const rows = data?.pages.flatMap((p) => p.data) ?? [];

  return (
    <div className="rounded-md border border-forest/20 bg-white">
      <InboxCategoryTabs
        active={category}
        onChange={(cat) => updateParam('category', cat)}
      />

      <div className="flex items-center justify-between px-4 py-3 border-b border-forest/10">
        <div className="flex gap-2">
          <button
            type="button"
            onClick={() => updateParam('filter', null)}
            className={`text-xs px-3 py-1 rounded-full ${
              readFilter === 'all'
                ? 'bg-forest text-bone'
                : 'border border-forest/20 bg-bone text-forest'
            }`}
          >
            All
          </button>
          <button
            type="button"
            onClick={() => updateParam('filter', 'unread')}
            className={`text-xs px-3 py-1 rounded-full ${
              readFilter === 'unread'
                ? 'bg-forest text-bone'
                : 'border border-forest/20 bg-bone text-forest'
            }`}
          >
            Unread
          </button>
        </div>
        <button
          type="button"
          onClick={() => markAll.mutate()}
          className="text-xs text-terracotta hover:underline"
        >
          Mark all read
        </button>
      </div>

      <div>
        {isLoading ? (
          <div className="p-6 text-center text-sm text-forest/60">Loading…</div>
        ) : rows.length === 0 ? (
          <div className="p-6">
            <EmptyState
              title="Nothing here"
              description="When something happens, it'll show up in this category."
            />
          </div>
        ) : (
          rows.map((row) => <NotificationRow key={row.id} item={row} />)
        )}
      </div>

      {hasNextPage ? (
        <div className="border-t border-forest/10 p-4 text-center">
          <button
            type="button"
            disabled={isFetchingNextPage}
            onClick={() => fetchNextPage()}
            className="text-sm text-forest hover:text-terracotta disabled:opacity-50"
          >
            {isFetchingNextPage ? 'Loading…' : 'Load more'}
          </button>
        </div>
      ) : null}
    </div>
  );
}
