import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { RotateCcw } from "lucide-react";

import { ReportDetailContent } from "@/components/reports/report-detail-content";
import { ShareReportActions } from "@/components/reports/share-report-actions";
import { Button } from "@/components/ui/button";
import { getServerAuthSession } from "@/lib/auth";
import { getCalculationById } from "@/services/calculation.service";

interface CaseDetailPageProps {
  params: Promise<{ id: string }>;
}

export default async function CaseDetailPage({ params }: CaseDetailPageProps) {
  const session = await getServerAuthSession();
  if (!session?.user?.id) {
    redirect("/login");
  }

  const { id } = await params;
  const calculation = await getCalculationById(id, session.user.id);

  if (!calculation) {
    notFound();
  }

  const appBaseUrl = process.env.NEXTAUTH_URL ?? "";

  return (
    <section className="mx-auto w-full max-w-6xl space-y-6 px-4 py-8 sm:px-6 lg:px-8">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <h1 className="text-2xl font-semibold text-emerald-950 sm:text-3xl">
            {calculation.title}
          </h1>
          <p className="mt-1 text-sm text-muted-foreground">
            Case ID: {calculation.id}
          </p>
        </div>
        <div className="flex flex-wrap gap-2">
          <Button asChild variant="outline">
            <Link href={`/calculator?reopen=${calculation.id}`}>
              <RotateCcw className="size-4" />
              Reopen Calculation
            </Link>
          </Button>
          <ShareReportActions
            reportId={calculation.id}
            reportToken={calculation.reportToken}
            appBaseUrl={appBaseUrl}
          />
        </div>
      </div>

      <ReportDetailContent calculation={calculation} />
    </section>
  );
}
