import Link from "next/link";
import { notFound } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { PageHeader } from "@/components/layout/page-header";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Card,
  CardHeader,
  CardTitle,
  CardContent,
} from "@/components/ui/card";

interface CourseDetail {
  id: string;
  title: string;
  country: string | null;
  state: string | null;
  level: string | null;
  application_fee: number | null;
  yearly_tuition_fee: number | null;
  currency: string | null;
  duration_months: number | null;
  duration_label: string | null;
  intake_months: string | null;
  intake_year: number | null;
  requirements: string | null;
  tags: string[] | null;
  is_active: boolean;
  institute: { name: string; logo_url: string | null } | null;
  campus: { name: string } | null;
}

function fmtMoney(amount: number | null, currency: string | null): string {
  if (amount == null) return "—";
  return `${currency ?? "GBP"} ${amount.toLocaleString()}`;
}

function Field({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <div className="space-y-1">
      <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
        {label}
      </p>
      <p className="text-sm">{value ?? "—"}</p>
    </div>
  );
}

export default async function CourseDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const supabase = await createClient();

  const { data: course } = await supabase
    .from("courses")
    .select(
      "*, institute:institutes(name, logo_url), campus:campuses(name)",
    )
    .eq("id", id)
    .single();

  if (!course) notFound();

  const c = course as unknown as CourseDetail;
  const duration =
    c.duration_label ??
    (c.duration_months != null ? `${c.duration_months} months` : null);
  const intake = [c.intake_months, c.intake_year]
    .filter((v) => v != null && v !== "")
    .join(" ");

  return (
    <div>
      <PageHeader
        title={c.title}
        breadcrumb="Course Finder / View Course"
        action={
          <div className="flex gap-2">
            <Button asChild variant="outline">
              <Link href={`/course-finder/${id}/edit`}>Edit</Link>
            </Button>
            <Button asChild>
              <Link href={`/course-finder/${id}/apply`}>Apply Now</Link>
            </Button>
          </div>
        }
      />

      <div className="space-y-6">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-3">
              <span>{c.institute?.name ?? "Unknown institute"}</span>
              {!c.is_active && <Badge variant="secondary">Inactive</Badge>}
            </CardTitle>
          </CardHeader>
          <CardContent className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
            <Field label="Level" value={c.level} />
            <Field label="Campus" value={c.campus?.name} />
            <Field
              label="Location"
              value={[c.state, c.country].filter(Boolean).join(", ") || null}
            />
            <Field
              label="Application fee"
              value={fmtMoney(c.application_fee, c.currency)}
            />
            <Field
              label="Yearly tuition fee"
              value={fmtMoney(c.yearly_tuition_fee, c.currency)}
            />
            <Field label="Duration" value={duration} />
            <Field label="Intake" value={intake || null} />
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Requirements</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="whitespace-pre-wrap text-sm">
              {c.requirements ?? "—"}
            </p>
          </CardContent>
        </Card>

        {c.tags && c.tags.length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle>Tags</CardTitle>
            </CardHeader>
            <CardContent className="flex flex-wrap gap-2">
              {c.tags.map((t) => (
                <Badge key={t} variant="secondary">
                  {t}
                </Badge>
              ))}
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  );
}
