// Dashboard is a server component, so we call services directly
// instead of fetching our own API. This avoids an extra HTTP hop on
// the server and keeps the page render in a single round-trip.
//
// If a `q` query param is present, we render search results in place
// of the recent/popular sections.

import Link from 'next/link';
import { questionService } from '@/lib/services/question.service';
import { categoryService } from '@/lib/services/category.service';
import { Button } from '@/components/ui/Button';
import { QuestionCard } from '@/components/features/QuestionCard';
import { EmptyState } from '@/components/ui/EmptyState';

export const dynamic = 'force-dynamic';

export default async function DashboardPage({
  searchParams,
}: {
  searchParams: { q?: string };
}) {
  const term = searchParams.q?.trim();

  if (term) {
    const results = await questionService.search(term);
    return (
      <div className="mx-auto max-w-5xl space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-xl font-semibold text-gray-900">Search results</h1>
            <p className="mt-1 text-sm text-gray-500">
              {results.length} {results.length === 1 ? 'result' : 'results'} for &ldquo;{term}&rdquo;
            </p>
          </div>
          <Link href="/dashboard"><Button variant="secondary" size="sm">Clear</Button></Link>
        </div>
        {results.length === 0 ? (
          <EmptyState
            title="No matching questions"
            description="Try a different keyword, or post a new question."
            action={<Link href="/ask-question"><Button>Ask a question</Button></Link>}
          />
        ) : (
          <div className="space-y-3">
            {results.map((q) => <QuestionCard key={q.id} question={q as any} />)}
          </div>
        )}
      </div>
    );
  }

  const [categories, recent, popular, unanswered] = await Promise.all([
    categoryService.listActive(),
    questionService.recent(),
    questionService.mostViewed(),
    questionService.unanswered(),
  ]);

  return (
    <div className="mx-auto max-w-6xl space-y-8">
      <header className="flex items-start justify-between gap-4">
        <div>
          <h1 className="text-xl font-semibold text-gray-900">Dashboard</h1>
          <p className="mt-1 text-sm text-gray-500">
            Browse categories or jump into a recent question. Found nothing? Ask the team.
          </p>
        </div>
        <Link href="/ask-question"><Button>Ask a question</Button></Link>
      </header>

      <section>
        <h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-gray-500">
          Categories
        </h2>
        <div className="grid grid-cols-2 gap-3 md:grid-cols-3 lg:grid-cols-4">
          {categories.map((cat) => (
            <Link
              key={cat.id}
              href={`/categories/${cat.slug}`}
              className="card flex h-24 flex-col justify-between p-4 transition hover:border-brand-300 hover:shadow"
            >
              <span className="text-sm font-semibold text-gray-900">{cat.name}</span>
              <span className="text-xs text-gray-500">View questions →</span>
            </Link>
          ))}
        </div>
      </section>

      <div className="grid gap-6 lg:grid-cols-2">
        <DashboardList title="Recent questions" items={recent} />
        <DashboardList title="Most viewed" items={popular} />
      </div>

      <DashboardList title="Unanswered" items={unanswered} />
    </div>
  );
}

function DashboardList({ title, items }: { title: string; items: any[] }) {
  return (
    <section>
      <h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-gray-500">{title}</h2>
      {items.length === 0 ? (
        <div className="card p-6 text-center text-sm text-gray-500">No questions yet.</div>
      ) : (
        <div className="space-y-3">
          {items.map((q) => <QuestionCard key={q.id} question={q} />)}
        </div>
      )}
    </section>
  );
}
