import { redirect } from "next/navigation";
import { connectDB } from "@/lib/db";
import { QmSubmission } from "@/models/QmSubmission";
import { isAdminSession } from "@/lib/adminAuth";
import { getSessionClientId } from "@/lib/auth";
import { NewQmSubmissionForm } from "@/components/account/NewQmSubmissionForm";
import { AccountPageHeader } from "@/components/account/AccountPageHeader";

export const dynamic = "force-dynamic";

const STATUS_LABELS = { pending: "In Prüfung", approved: "Freigegeben", rejected: "Abgelehnt" } as const;
const STATUS_STYLES = {
  pending: "border-amber-400/40 text-amber-400",
  approved: "border-emerald-400/40 text-emerald-400",
  rejected: "border-red-400/40 text-red-400",
} as const;
const TARGET_LABELS = { qm: "Qualitätsmanagement", hr: "Personalabteilung" } as const;

export default async function AccountQmPage({ params }: { params: Promise<{ locale: string }> }) {
  const { locale } = await params;
  if (!(await isAdminSession())) redirect(`/${locale}/account`);
  const clientId = await getSessionClientId();

  await connectDB();
  const submissions = await QmSubmission.find({ submittedBy: clientId }).sort({ createdAt: -1 }).lean();

  return (
    <div>
      <div className="flex max-w-2xl flex-col gap-8">
        <AccountPageHeader eyebrow="QM & Personal" title="Einreichen" />

        <NewQmSubmissionForm />

        <div>
          <h2 className="text-sm font-medium text-[var(--rk-ink)] mb-3">Meine Einreichungen</h2>
          <div className="flex flex-col gap-2">
            {submissions.map((s) => (
              <div key={String(s._id)} className="rounded-xl border border-white/10 bg-[var(--rk-surface)] p-4">
                <div className="flex items-center justify-between gap-3 mb-1">
                  <p className="text-sm">
                    {s.title} <span className="text-xs text-[var(--rk-ink-muted)]">· {TARGET_LABELS[s.target]}</span>
                    {s.anonymous && <span className="text-xs text-[var(--rk-ink-muted)]"> · anonym</span>}
                  </p>
                  <span className={`text-xs border rounded-full px-2.5 py-0.5 shrink-0 ${STATUS_STYLES[s.status]}`}>
                    {STATUS_LABELS[s.status]}
                  </span>
                </div>
                {s.description && <p className="text-xs text-[var(--rk-ink-muted)] whitespace-pre-line">{s.description}</p>}
                {s.attachmentStoredName && (
                  <a
                    href={`/api/qm/${s._id}/${s.attachmentStoredName}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-xs underline text-[var(--rk-ink-muted)] hover:text-[var(--rk-ink)] mt-1 inline-block"
                  >
                    Anhang öffnen
                  </a>
                )}
                {s.reviewNote && (
                  <p className="text-xs text-[var(--rk-ink-muted)] mt-2 border-t border-white/10 pt-2">
                    Rückmeldung: {s.reviewNote}
                  </p>
                )}
              </div>
            ))}
            {submissions.length === 0 && <p className="text-sm text-[var(--rk-ink-muted)]">Noch keine Einreichungen.</p>}
          </div>
        </div>
      </div>
    </div>
  );
}
