import Link from "next/link";
import { notFound } from "next/navigation";
import { requireUser } from "@/lib/auth/session";
import { requireCompleteStudentProfile } from "@/lib/auth/student-onboarding";
import { createClient } from "@/lib/supabase/server";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  APPLICATION_STATUSES,
  APPLICATION_STATUS_STYLES,
} from "@/lib/applications/constants";
import { cn } from "@/lib/utils";

function fmtDate(d: string | null): string {
  if (!d) return "—";
  return new Date(d).toLocaleDateString("en-IN", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  });
}

function oneField(
  rel: { [k: string]: unknown } | { [k: string]: unknown }[] | null | undefined,
  key: string,
): string {
  if (!rel) return "";
  const r = Array.isArray(rel) ? rel[0] : rel;
  const v = r?.[key];
  return v != null ? String(v) : "";
}

function fmtMoney(amount: number | null, currency: string | null): string {
  if (amount == null) return "—";
  const cur = currency || "";
  return `${cur} ${Number(amount).toLocaleString("en-IN")}`.trim();
}

function InfoRow({
  label,
  value,
}: {
  label: string;
  value: React.ReactNode;
}) {
  return (
    <div className="flex items-start justify-between gap-4 py-1.5 text-sm">
      <span className="text-muted-foreground">{label}</span>
      <span className="text-right font-medium">{value || "—"}</span>
    </div>
  );
}

// Statuses that represent a terminal/negative outcome, kept out of the linear
// happy-path pipeline so the stepper reads cleanly.
const PIPELINE_STATUSES = APPLICATION_STATUSES.filter(
  (s) => s !== "Visa Rejected" && s !== "Rejected",
);

type FeePayment = {
  amount: number | null;
  currency: string | null;
  payment_date: string | null;
  mode: string | null;
};

export default async function PortalApplicationStatusPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const user = await requireUser();
  if (user.role?.slug === "student") {
    await requireCompleteStudentProfile(user.id);
  }
  const supabase = await createClient();

  // RLS ensures the student can only read their own application.
  const { data: app } = await supabase
    .from("student_applications")
    .select("*, institute:institutes(name), course:courses(title)")
    .eq("id", id)
    .single();

  if (!app) notFound();

  const { data: visa } = await supabase
    .from("visa_tracking")
    .select("*, status:visa_statuses(name)")
    .eq("student_application_id", id)
    .maybeSingle();

  const { data: feeData } = await supabase
    .from("fee_payments")
    .select("amount, currency, payment_date, mode")
    .eq("student_application_id", id)
    .order("payment_date", { ascending: false });

  const payments = (feeData as FeePayment[] | null) ?? [];

  const institute = oneField(app.institute, "name");
  const course = oneField(app.course, "title");
  const statusStyle =
    APPLICATION_STATUS_STYLES[app.status] ?? "bg-gray-100 text-gray-800";

  const currentIndex = PIPELINE_STATUSES.indexOf(
    app.status as (typeof PIPELINE_STATUSES)[number],
  );
  const isNegative = app.status === "Visa Rejected" || app.status === "Rejected";

  const visaStatusName = oneField(visa?.status, "name");
  const paymentsCurrency = payments.find((p) => p.currency)?.currency ?? null;
  const totalPaid = payments.reduce((sum, p) => sum + (p.amount ?? 0), 0);

  return (
    <div className="space-y-6">
      <div>
        <Link
          href="/portal"
          className="text-sm text-muted-foreground hover:text-brand-navy"
        >
          &larr; Back to my applications
        </Link>
      </div>

      {/* Header */}
      <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="font-heading text-2xl font-bold text-brand-navy">
            {app.applicant_name}
          </h1>
          <p className="mt-1 text-sm text-muted-foreground">
            {[institute, course].filter(Boolean).join(" · ") ||
              "Application status"}
          </p>
        </div>
        <Badge className={cn("text-sm", statusStyle)}>{app.status}</Badge>
      </div>

      {/* Status pipeline / timeline */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base text-brand-navy">
            Application progress
          </CardTitle>
        </CardHeader>
        <CardContent>
          <ol className="relative space-y-0">
            {PIPELINE_STATUSES.map((step, i) => {
              const reached = currentIndex >= 0 && i <= currentIndex;
              const isCurrent = i === currentIndex;
              const isLast = i === PIPELINE_STATUSES.length - 1;
              return (
                <li key={step} className="relative flex gap-4 pb-6 last:pb-0">
                  {/* connector line */}
                  {!isLast ? (
                    <span
                      aria-hidden
                      className={cn(
                        "absolute left-[11px] top-6 h-full w-0.5",
                        reached && i < currentIndex
                          ? "bg-brand-orange"
                          : "bg-border",
                      )}
                    />
                  ) : null}
                  {/* node */}
                  <span
                    className={cn(
                      "relative z-10 mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-full border-2 text-[10px] font-bold",
                      isCurrent
                        ? "border-brand-orange bg-brand-orange text-white"
                        : reached
                          ? "border-brand-orange bg-brand-orange/15 text-brand-orange"
                          : "border-border bg-background text-muted-foreground",
                    )}
                  >
                    {reached ? "✓" : i + 1}
                  </span>
                  <div className="pt-0.5">
                    <p
                      className={cn(
                        "text-sm font-medium",
                        isCurrent
                          ? "text-brand-navy"
                          : reached
                            ? "text-foreground"
                            : "text-muted-foreground",
                      )}
                    >
                      {step}
                    </p>
                    {isCurrent ? (
                      <p className="text-xs text-brand-orange">Current stage</p>
                    ) : null}
                  </div>
                </li>
              );
            })}
          </ol>
          {isNegative ? (
            <div className="mt-4 rounded-md bg-red-50 px-4 py-3 text-sm text-red-800">
              Current status:{" "}
              <span className="font-semibold">{app.status}</span>. Please reach
              out to your counsellor for next steps.
            </div>
          ) : null}
        </CardContent>
      </Card>

      <div className="grid gap-6 sm:grid-cols-2">
        {/* Offer */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base text-brand-navy">Offer</CardTitle>
          </CardHeader>
          <CardContent>
            <InfoRow
              label="Offer received"
              value={app.offer_received ? "Yes" : "No"}
            />
            <InfoRow label="Offer date" value={fmtDate(app.offer_date)} />
            <InfoRow
              label="Tuition fee"
              value={fmtMoney(app.tuition_fee, app.currency)}
            />
          </CardContent>
        </Card>

        {/* Visa */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base text-brand-navy">Visa</CardTitle>
          </CardHeader>
          <CardContent>
            {visa ? (
              <>
                <InfoRow label="Status" value={visaStatusName} />
                <InfoRow label="Applied" value={fmtDate(visa.applied_date)} />
                <InfoRow
                  label="Interview"
                  value={fmtDate(visa.interview_date)}
                />
                <InfoRow label="Decision" value={visa.decision || "—"} />
                <InfoRow
                  label="Decision date"
                  value={fmtDate(visa.decision_date)}
                />
              </>
            ) : (
              <p className="py-2 text-sm text-muted-foreground">
                Visa stage not started.
              </p>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Fees paid */}
      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle className="text-base text-brand-navy">Fees paid</CardTitle>
          {payments.length > 0 ? (
            <span className="text-sm font-semibold text-brand-navy">
              Total: {fmtMoney(totalPaid, paymentsCurrency)}
            </span>
          ) : null}
        </CardHeader>
        <CardContent>
          {payments.length === 0 ? (
            <p className="py-2 text-sm text-muted-foreground">
              No payments recorded yet.
            </p>
          ) : (
            <ul className="divide-y">
              {payments.map((p, i) => (
                <li
                  key={i}
                  className="flex items-center justify-between gap-4 py-2.5 text-sm"
                >
                  <div>
                    <p className="font-medium">
                      {fmtMoney(p.amount, p.currency)}
                    </p>
                    <p className="text-xs text-muted-foreground">
                      {fmtDate(p.payment_date)}
                      {p.mode ? ` · ${p.mode}` : ""}
                    </p>
                  </div>
                </li>
              ))}
            </ul>
          )}
        </CardContent>
      </Card>

      {/* Actions to sibling routes (built by other agents) */}
      <div className="flex flex-wrap gap-3">
        <Button asChild variant="outline">
          <Link href={`/portal/applications/${id}/documents`}>
            My Documents
          </Link>
        </Button>
        <Button asChild className="bg-brand-orange hover:bg-brand-orange/90">
          <Link href={`/portal/applications/${id}/messages`}>
            Message my counsellor
          </Link>
        </Button>
      </div>
    </div>
  );
}
