import { createClient } from "@/lib/supabase/server";
import { ReportTable } from "@/components/reports/report-table";
import type { ReportColumn } from "@/lib/types";

export const dynamic = "force-dynamic";

/** Supabase embeds can come back as an object or a single-element array. */
function first<T>(value: T | T[] | null | undefined): T | null {
  if (Array.isArray(value)) return value[0] ?? null;
  return value ?? null;
}

function formatDate(value: string | null): string {
  if (!value) return "—";
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return "—";
  return d.toLocaleDateString();
}

interface VisaTrackingRow {
  id: string;
  applied_date: string | null;
  interview_date: string | null;
  decision: string | null;
  decision_date: string | null;
  created_at: string | null;
  status: { name: string | null } | { name: string | null }[] | null;
  application:
    | { applicant_name: string | null }
    | { applicant_name: string | null }[]
    | null;
}

const columns: ReportColumn[] = [
  { key: "applicant", label: "Applicant" },
  { key: "visaStatus", label: "Visa Status" },
  { key: "appliedDate", label: "Applied Date" },
  { key: "interviewDate", label: "Interview Date" },
  { key: "decision", label: "Decision" },
  { key: "decisionDate", label: "Decision Date" },
];

export default async function VisaProcessReportPage() {
  const supabase = await createClient();

  const { data } = await supabase
    .from("visa_tracking")
    .select(
      "id, applied_date, interview_date, decision, decision_date, created_at, status:visa_statuses(name), application:student_applications(applicant_name)",
    )
    .order("created_at", { ascending: false });

  const tracking = (data as unknown as VisaTrackingRow[]) ?? [];

  const rows = tracking.map((t) => ({
    applicant: first(t.application)?.applicant_name ?? "—",
    visaStatus: first(t.status)?.name ?? "—",
    appliedDate: formatDate(t.applied_date),
    interviewDate: formatDate(t.interview_date),
    decision: t.decision ?? "—",
    decisionDate: formatDate(t.decision_date),
  }));

  return (
    <ReportTable
      title="Visa Process"
      breadcrumb="Home / Reports / Visa Process"
      columns={columns}
      rows={rows}
    />
  );
}
