'use client';

import { useQuery } from '@tanstack/react-query';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react';
import { api } from '@/lib/api';
import { useSelectedStoreId } from '@/lib/stores/store-context';
import { ItemStatusBadge } from '@/components/seller/item-status-badge';
import { EmptyState } from '@/components/seller/empty-state';

interface ItemSummary {
  id: string;
  title: string;
  price: number;
  status: string;
  image_url: string | null;
  view_count?: number;
  created_at: string;
  published_at?: string | null;
}

const STATUS_CHIPS = [
  { value: 'all', label: 'All' },
  { value: 'active', label: 'Published' },
  { value: 'draft', label: 'Draft' },
  { value: 'sold', label: 'Sold' },
  { value: 'removed', label: 'Removed' },
] as const;

function formatDollars(c: number) { return `$${(c / 100).toFixed(2)}`; }
function formatDate(iso: string | null | undefined) { return iso ? new Date(iso).toLocaleDateString() : '—'; }

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

  const status = params.get('status') ?? 'all';
  const filter = params.get('filter') ?? '';
  const sort = params.get('sort') ?? 'listed_desc';
  const page = Number(params.get('page') ?? '1');
  const urlView = params.get('view');

  const [view, setView] = useState<'table' | 'grid'>(() => {
    if (urlView === 'grid' || urlView === 'table') return urlView;
    if (typeof window !== 'undefined') {
      const stored = window.localStorage.getItem('seller.listings.view');
      if (stored === 'grid' || stored === 'table') return stored;
    }
    return 'table';
  });

  useEffect(() => {
    if (!urlView && typeof window !== 'undefined') {
      window.localStorage.setItem('seller.listings.view', view);
    }
  }, [view, urlView]);

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

  const queryKey = useMemo(
    () => ['seller-items', storeId, status, filter, qDebounced, sort, page],
    [storeId, status, filter, qDebounced, sort, 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 (filter) p.filter = filter;
      if (qDebounced) p.q = qDebounced;
      return api.items.list(storeId!, p);
    },
  });

  const items: ItemSummary[] = (data?.data ?? []) as unknown as ItemSummary[];
  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/listings?${u.toString()}`);
  };

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

  const setViewSticky = (next: 'table' | 'grid') => {
    setView(next);
    if (typeof window !== 'undefined') {
      window.localStorage.setItem('seller.listings.view', next);
    }
    const u = new URLSearchParams(params.toString());
    u.delete('view');
    router.push(`/seller/listings?${u.toString()}`);
  };

  return (
    <div>
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-ink">Listings</h1>
          <p className="mt-1 text-sm text-ink/60">Manage your items.</p>
        </div>
        <Link href="/seller/listings/new" className="rounded bg-forest px-4 py-2 text-sm font-semibold text-white hover:bg-forest/90">
          + New item
        </Link>
      </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, filter: null })}
            className={`rounded-full px-3 py-1 text-sm ${
              status === c.value && !filter
                ? 'bg-forest text-white'
                : 'bg-bone text-ink hover:bg-forest/10'
            }`}
          >
            {c.label}
          </button>
        ))}
        <button
          onClick={() => pushParams({ filter: filter === 'needs-attention' ? null : 'needs-attention', status: null })}
          className={`rounded-full px-3 py-1 text-sm ${
            filter === 'needs-attention' ? 'bg-terracotta text-white' : 'bg-bone text-ink hover:bg-forest/10'
          }`}
        >
          Needs attention
        </button>

        <div className="ml-auto flex items-center gap-2">
          <input
            value={qInput}
            onChange={(e) => setQInput(e.target.value)}
            placeholder="Search title or brand…"
            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="listed_desc">Newest</option>
            <option value="listed_asc">Oldest</option>
            <option value="price_desc">Price high→low</option>
            <option value="price_asc">Price low→high</option>
            <option value="views_desc">Most views</option>
          </select>
          <div className="flex overflow-hidden rounded border border-forest/20">
            <button
              onClick={() => setViewSticky('table')}
              className={`px-2 py-1.5 text-sm ${view === 'table' ? 'bg-forest text-white' : 'bg-white text-ink'}`}
            >
              Table
            </button>
            <button
              onClick={() => setViewSticky('grid')}
              className={`px-2 py-1.5 text-sm ${view === 'grid' ? 'bg-forest text-white' : 'bg-white text-ink'}`}
            >
              Grid
            </button>
          </div>
        </div>
      </div>

      <div className="mt-4">
        {isLoading && <div className="p-8 text-center text-sm text-ink/60">Loading items…</div>}
        {isError && <div className="p-8 text-center text-sm text-terracotta">Failed to load items.</div>}
        {!isLoading && !isError && items.length === 0 && (
          <EmptyState title="No items" description="Create your first item to get started." />
        )}

        {!isLoading && !isError && items.length > 0 && view === 'table' && (
          <div className="overflow-hidden rounded-md border border-forest/20 bg-white">
            <table className="w-full text-sm">
              <thead className="bg-bone/60">
                <tr>
                  <Th>Image</Th><Th>Title</Th><Th>Status</Th><Th>Price</Th><Th>Views</Th><Th>Listed</Th>
                </tr>
              </thead>
              <tbody>
                {items.map((it) => (
                  <tr
                    key={it.id}
                    role="link"
                    tabIndex={0}
                    onClick={() => router.push(`/seller/listings/${it.id}`)}
                    onKeyDown={(e: KeyboardEvent<HTMLTableRowElement>) => {
                      if (e.key === 'Enter' || e.key === ' ') {
                        e.preventDefault();
                        router.push(`/seller/listings/${it.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">
                      <ItemThumb src={it.image_url} size="sm" />
                    </td>
                    <td className="px-4 py-3 text-ink">{it.title}</td>
                    <td className="px-4 py-3"><ItemStatusBadge status={it.status} /></td>
                    <td className="px-4 py-3 text-ink">{formatDollars(it.price)}</td>
                    <td className="px-4 py-3 text-ink/70">{it.view_count ?? 0}</td>
                    <td className="px-4 py-3 text-xs text-ink/60">{formatDate(it.published_at ?? it.created_at)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {!isLoading && !isError && items.length > 0 && view === 'grid' && (
          <ul className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
            {items.map((it) => (
              <li key={it.id}>
                <Link href={`/seller/listings/${it.id}`} className="block overflow-hidden rounded-md border border-forest/20 bg-white hover:border-forest">
                  <div className="aspect-square bg-bone">
                    <ItemThumb src={it.image_url} size="full" />
                  </div>
                  <div className="p-3">
                    <div className="truncate text-sm font-medium text-ink">{it.title}</div>
                    <div className="mt-1 flex items-center justify-between text-xs">
                      <span className="text-ink/70">{formatDollars(it.price)}</span>
                      <ItemStatusBadge status={it.status} />
                    </div>
                  </div>
                </Link>
              </li>
            ))}
          </ul>
        )}
      </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={() => goToPage(router, 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={() => goToPage(router, 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 ItemThumb({ src, size }: { src: string | null; size: 'sm' | 'full' }) {
  const [broken, setBroken] = useState(false);
  const cls = size === 'sm' ? 'h-10 w-10 rounded' : 'h-full w-full';
  if (!src || broken) return <div className={`${cls} bg-bone`} />;
  // eslint-disable-next-line @next/next/no-img-element
  return <img src={src} alt="" onError={() => setBroken(true)} className={`${cls} object-cover`} />;
}

function goToPage(router: ReturnType<typeof useRouter>, params: URLSearchParams | ReturnType<typeof useSearchParams>, page: number) {
  const u = new URLSearchParams(params.toString());
  u.set('page', String(page));
  router.push(`/seller/listings?${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;
}
