import { auth } from "@/lib/auth";
import prisma from "@/lib/prisma";
import Link from "next/link";

// D.2: a top-of-dashboard nudge for escorts who started onboarding but
// haven't finished all 6 steps. Renders nothing if every step is done or
// the user has no step row at all (clients, admins). Returning users see
// a clear progress bar + deep-link to resume right where they left off.
const STEPS: { key: keyof Omit<StepRow, "user_id" | "id">; label: string; href: string }[] = [
  { key: "step_1", label: "Personal Info", href: "/onboarding/personal" },
  { key: "step_2", label: "Characteristics", href: "/onboarding/characteristics" },
  { key: "step_3", label: "Services", href: "/onboarding/services" },
  { key: "step_4", label: "Rates", href: "/onboarding/rates" },
  { key: "step_5", label: "Working Times", href: "/onboarding/working-times" },
  { key: "step_6", label: "Photos", href: "/onboarding/photos" },
];

type StepRow = {
  id: number;
  user_id: number;
  step_1: boolean | null;
  step_2: boolean | null;
  step_3: boolean | null;
  step_4: boolean | null;
  step_5: boolean | null;
  step_6: boolean | null;
};

export default async function OnboardingResumeBanner() {
  const session = await auth();
  const userId = session?.user?.id ? Number(session.user.id) : null;
  if (!userId) return null;

  let step: StepRow | null = null;
  try {
    step = await prisma.step.findUnique({ where: { user_id: userId } });
  } catch {
    return null;
  }
  if (!step) return null;

  const completed = STEPS.filter((s) => !!step![s.key]).length;
  if (completed === STEPS.length) return null;

  const next = STEPS.find((s) => !step![s.key]);
  const percent = Math.round((completed / STEPS.length) * 100);

  return (
    <div className="bg-gold/10 border border-gold/30 rounded-xl p-5 mb-6">
      <div className="flex flex-col sm:flex-row sm:items-center gap-4">
        <div className="flex-1">
          <p className="text-text font-semibold">
            Resume setup — {completed} of {STEPS.length} sections complete ({percent}%)
          </p>
          <p className="text-text-muted text-sm mt-1">
            Finish your profile so clients can find and book you.
          </p>
          <div className="mt-3 h-2 rounded-full bg-surface-light overflow-hidden">
            <div
              className="h-full bg-gold transition-all duration-500"
              style={{ width: `${percent}%` }}
              aria-hidden="true"
            />
          </div>
        </div>
        {next && (
          <Link
            href={next.href}
            className="bg-gold hover:bg-gold-light text-black px-5 py-2.5 rounded-lg font-semibold transition-colors shrink-0"
          >
            Continue: {next.label}
          </Link>
        )}
      </div>
    </div>
  );
}
