import { Link, useParams } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { ArrowLeft } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import PlanReader from "@/components/coursePlan/PlanReader";
import { coursePlanService } from "@/services/coursePlan.service";
import { describeApiError } from "@/lib/api-client";
import type { CoursePlan } from "@/types";

/**
 * Student detail view for an assigned AI course plan.
 *
 * Server-side authorisation: the `/api/student/course-plans/:id` endpoint
 * returns 403 unless the current user is in the plan's assignment list,
 * so we can render unconditionally as soon as the query resolves.
 *
 * Rendering is delegated to the shared `<PlanReader>` so the admin
 * "View as Student" preview matches the real student experience byte-for-byte.
 */
export default function StudentCoursePlanDetail() {
  const { t } = useTranslation();
  const { planId: planIdRaw } = useParams<{ planId: string }>();
  const planId = Number(planIdRaw);

  const { data, isLoading, isError, error } = useQuery({
    queryKey: ["student-course-plan", planId],
    queryFn: () => coursePlanService.studentGet(planId),
    enabled: Number.isFinite(planId) && planId > 0,
  });

  const plan = data?.data as CoursePlan | undefined;

  return (
    <div className="space-y-6">
      <Button
        variant="ghost"
        size="sm"
        asChild
        className="-ml-2 text-muted-foreground"
      >
        <Link to="/student/course-plans" className="flex items-center gap-1">
          <ArrowLeft className="h-4 w-4" />
          {t("coursePlan.student.backToList")}
        </Link>
      </Button>

      {isLoading && (
        <div className="space-y-3">
          <Skeleton className="h-20" />
          <Skeleton className="h-40" />
          <Skeleton className="h-40" />
        </div>
      )}

      {isError && (
        <div className="rounded-md border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive">
          {describeApiError(error, t("coursePlan.loadFailed"))}
        </div>
      )}

      {plan && <PlanReader plan={plan} mode="student" />}
    </div>
  );
}
