import Link from 'next/link';
import { Wrench } from 'lucide-react';
import { resolveUser } from '@/lib/auth';
import { api } from '@/lib/trpc/server';
import { SignOutButton } from './sign-out-button';
import { StatusBadge } from './status-badge';
import { SyncChip } from './sync-chip';

export default async function HomePage() {
  const user = await resolveUser();

  // myRecent is a protectedProcedure — fails gracefully when there is no session.
  type RecentItem = Awaited<ReturnType<typeof api.maintenanceRequest.myRecent>>[number];
  let recent: RecentItem[] = [];
  try {
    recent = await api.maintenanceRequest.myRecent({ limit: 5 });
  } catch {
    // No session or other error — show empty list without crashing.
  }

  return (
    <main className="mx-auto flex min-h-dvh max-w-lg flex-col bg-background">
      {/* ── Header ── */}
      <header className="flex items-center justify-between border-b border-border bg-card px-4 py-3">
        <div>
          <p className="text-xs text-muted-foreground">Operador</p>
          <p className="text-sm font-medium" data-testid="current-user">
            {user?.email ?? '—'}
          </p>
        </div>
        <SignOutButton />
      </header>

      <div className="flex flex-1 flex-col gap-6 p-4">
        {/* ── Sync status ── */}
        <SyncChip />

        {/* ── Primary CTA ── */}
        <Link
          href="/maintenance/new"
          data-testid="btn-request-maintenance"
          className="flex items-center justify-center gap-3 rounded-2xl bg-primary px-6 py-10 text-lg font-semibold text-primary-foreground shadow-sm transition-opacity hover:opacity-90 active:scale-[0.98]"
        >
          <Wrench className="h-6 w-6" />
          Pedir manutenção
        </Link>

        {/* ── Recent requests ── */}
        <section>
          <h2 className="mb-3 text-sm font-medium text-muted-foreground">Os meus pedidos</h2>

          {recent.length === 0 ? (
            <p className="text-sm text-muted-foreground">Nenhum pedido ainda.</p>
          ) : (
            <ul className="flex flex-col gap-2">
              {recent.map((req) => (
                <li
                  key={req.id}
                  className="flex items-center justify-between gap-3 rounded-lg border border-border bg-card px-4 py-3 text-sm"
                >
                  <div className="min-w-0 flex-1">
                    <p className="font-medium">
                      {req.workstation.code} — {req.workstation.name}
                    </p>
                    <p className="truncate text-xs text-muted-foreground">{req.description}</p>
                  </div>
                  <StatusBadge status={req.status} />
                </li>
              ))}
            </ul>
          )}
        </section>
      </div>
    </main>
  );
}
