import { redirect } from "next/navigation";
import { db } from "@/lib/db";
import { getPublicConference } from "@/lib/conference";
import { requireUser } from "@/lib/auth";
import { Card, btn } from "@/components/ui";
import { fmtDay, fmtTime } from "@/lib/utils";
import { submitFeedbackAction } from "./actions";

export const metadata = { title: "Feedback" };

function Stars({ name, current }: { name: string; current?: number }) {
  return (
    <div className="star-group flex flex-row-reverse justify-end gap-1" role="radiogroup">
      {[5, 4, 3, 2, 1].map((n) => (
        <label key={n} className="cursor-pointer text-2xl text-zinc-700 transition hover:scale-110">
          <input type="radio" name={name} value={n} defaultChecked={current === n} className="sr-only" />
          ★
        </label>
      ))}
    </div>
  );
}

export default async function FeedbackPage({
  params,
  searchParams,
}: {
  params: Promise<{ slug: string }>;
  searchParams: Promise<{ thanks?: string }>;
}) {
  const { slug } = await params;
  const { thanks } = await searchParams;
  const conf = await getPublicConference(slug);
  const user = await requireUser();

  const registration = await db.registration.findFirst({
    where: { conferenceId: conf.id, status: { not: "CANCELLED" }, OR: [{ userId: user.id }, { email: user.email }] },
  });
  if (!registration) redirect(`/c/${slug}/register`);

  const [sessions, existing] = await Promise.all([
    db.session.findMany({
      where: { conferenceId: conf.id, type: { notIn: ["BREAK", "NETWORKING"] } },
      orderBy: { startAt: "asc" },
      include: { speakers: { include: { speaker: true } } },
    }),
    db.feedback.findMany({ where: { conferenceId: conf.id, registrationId: registration.id } }),
  ]);
  const overall = existing.find((f) => !f.sessionId);
  const bySession = new Map(existing.filter((f) => f.sessionId).map((f) => [f.sessionId!, f.rating]));

  return (
    <main className="mx-auto max-w-2xl px-4 py-10">
      <h1 className="text-2xl font-bold text-zinc-100">Your feedback</h1>
      <p className="mt-1 text-sm text-zinc-500">
        Help {conf.org.name} make the next edition better — takes under a minute. You can update your answers any time.
      </p>
      {thanks && (
        <div className="fx-pop-in mt-4 rounded-lg border border-emerald-500/30 bg-emerald-500/10 px-4 py-3 text-sm text-emerald-600">
          🙏 Thank you! Your feedback has been recorded{overall ? "" : ""} — feel free to revise it below.
        </div>
      )}

      <form action={submitFeedbackAction.bind(null, slug)} className="mt-6 space-y-5">
        <Card className="p-5">
          <h2 className="font-bold text-zinc-100">Overall, how was {conf.name}?</h2>
          <div className="mt-3"><Stars name="overall" current={overall?.rating} /></div>
          <textarea
            name="comments"
            rows={3}
            defaultValue={overall?.comments ?? ""}
            placeholder="What worked well? What should improve next year?"
            className="mt-4 w-full rounded-xl border border-white/80 bg-white/70 px-3 py-2 text-sm text-zinc-100 placeholder-zinc-600 shadow-sm backdrop-blur outline-none focus:border-indigo-400"
          />
        </Card>

        {sessions.length > 0 && (
          <Card className="p-5">
            <h2 className="font-bold text-zinc-100">Rate the sessions you attended</h2>
            <p className="mt-0.5 text-xs text-zinc-500">Skip any you missed.</p>
            <div className="mt-4 space-y-4">
              {sessions.map((s) => (
                <div key={s.id} className="flex flex-wrap items-center justify-between gap-2 border-b border-zinc-800/50 pb-3 last:border-0 last:pb-0">
                  <div className="min-w-0">
                    <div className="text-sm font-semibold text-zinc-200">{s.title}</div>
                    <div className="text-xs text-zinc-500">
                      {fmtDay(s.startAt).split(",")[0]} {fmtTime(s.startAt)}
                      {s.speakers.length > 0 && ` · ${s.speakers.map((x) => x.speaker.name).join(", ")}`}
                    </div>
                  </div>
                  <Stars name={`session-${s.id}`} current={bySession.get(s.id)} />
                </div>
              ))}
            </div>
          </Card>
        )}

        <button className={`${btn.primary} w-full py-3`}>Submit feedback</button>
      </form>
    </main>
  );
}
