import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft } from "lucide-react";

import { buttonVariants } from "@/components/ui/button";
import { getMaestroDetail } from "@/lib/maestros";
import {
  formatDate,
  formatDateTime,
  getAccountTypeLabel,
  getActivateStatusLabel,
} from "@/lib/utils";
import { MaestroEditForm } from "./MaestroEditForm";
import { StudentsSection } from "./StudentsSection";
import { ExtensionRequestsSection } from "./ExtensionRequestsSection";
import { UpgradeRequestsSection } from "./UpgradeRequestsSection";

type MaestroDetailPageProps = {
  params: Promise<{
    maestroId: string;
  }>;
};

export default async function MaestroDetailPage({
  params,
}: MaestroDetailPageProps) {
  const { maestroId } = await params;
  const maestroID = Number(maestroId);

  if (!Number.isInteger(maestroID) || maestroID <= 0) {
    notFound();
  }

  const detail = await getMaestroDetail(maestroID);

  if (!detail) {
    notFound();
  }

  const { maestro } = detail;

  return (
    <section className="space-y-5">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <Link
            className={buttonVariants({
              variant: "ghost",
              size: "sm",
              className: "mb-2 -ml-2",
            })}
            href="/maestros"
          >
            <ArrowLeft className="size-4" aria-hidden="true" />
            목록
          </Link>
          <h1 className="text-2xl font-semibold tracking-normal">
            {maestro.name}
          </h1>
          <p className="mt-1 text-sm text-muted-foreground">
            MaestroID {maestro.maestroID} · {maestro.email}
          </p>
        </div>
      </div>

      <div className="grid gap-4 lg:grid-cols-4">
        <SummaryCard
          label="상태"
          value={getActivateStatusLabel(maestro.activateStatus)}
        />
        <SummaryCard
          label="계정 유형"
          value={getAccountTypeLabel(maestro.accountType)}
        />
        <SummaryCard
          label="학생 수"
          value={detail.counts.players.toLocaleString()}
        />
        <SummaryCard
          label="사용 가능일"
          value={formatDate(maestro.availableActivateDateTime)}
        />
      </div>

      <section className="rounded-lg border bg-background p-5">
        <h2 className="text-base font-semibold">기본 정보</h2>
        <MaestroEditForm
          maestro={detail.maestro}
          playerCount={detail.counts.players}
        />
      </section>

      <StudentsSection maestroID={maestroID} />

      <div className="grid gap-4 xl:grid-cols-2">
        <ExtensionRequestsSection
          accountType={maestro.accountType}
          extensionRequests={detail.extensionRequests}
          maestroID={maestroID}
          totalCount={detail.counts.extensionRequests}
        />

        <UpgradeRequestsSection
          accountType={maestro.accountType}
          maestroID={maestroID}
          totalCount={detail.counts.upgradeRequests}
          upgradeRequests={detail.upgradeRequests}
        />
      </div>

      <section className="rounded-lg border bg-background p-5">
        <h2 className="text-base font-semibold">처리 로그</h2>
        <p className="mt-1 text-sm text-muted-foreground">
          전체 {detail.counts.logs.toLocaleString()}건 중 최근 30건
        </p>
        <SimpleTable
          emptyText="처리 로그가 없습니다."
          headers={["LogID", "유형", "처리일시", "내용"]}
          rows={detail.logs.map((log) => [
            log.maestroLogID,
            log.type,
            formatDateTime(log.logDateTime),
            log.remark,
          ])}
        />
      </section>
    </section>
  );
}

function SummaryCard({ label, value }: { label: string; value: string }) {
  return (
    <article className="rounded-lg border bg-background p-4">
      <p className="text-xs font-medium text-muted-foreground">{label}</p>
      <p className="mt-2 text-lg font-semibold">{value}</p>
    </article>
  );
}

function SimpleTable({
  headers,
  rows,
  emptyText,
}: {
  headers: string[];
  rows: Array<Array<string | number>>;
  emptyText: string;
}) {
  return (
    <div className="mt-4 overflow-hidden rounded-lg border">
      <div className="overflow-x-auto">
        <table className="w-full min-w-[560px] border-collapse text-sm">
          <thead className="bg-muted/60">
            <tr className="border-b">
              {headers.map((header) => (
                <th
                  className="h-10 px-3 text-left text-xs font-medium text-muted-foreground"
                  key={header}
                >
                  {header}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.length > 0 ? (
              rows.map((row, index) => (
                <tr className="border-b last:border-b-0" key={index}>
                  {row.map((cell, cellIndex) => (
                    <td
                      className="h-11 max-w-[360px] break-words px-3 align-middle"
                      key={cellIndex}
                    >
                      {cell}
                    </td>
                  ))}
                </tr>
              ))
            ) : (
              <tr>
                <td
                  className="h-24 px-3 text-center text-sm text-muted-foreground"
                  colSpan={headers.length}
                >
                  {emptyText}
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
