import { History, Pencil } from "lucide-react";
import Link from "next/link";
import { notFound } from "next/navigation";

import { ListPageCard } from "@/app/dashboard/_components";
import { ErrorBanner } from "@/components/shared/error-banner";
import { Button } from "@/components/ui/button";

import { fetchCorporateAction } from "../../bulk-edit/_lib/corporate-action-server-api";
import { CorporateActionStatusBadge } from "../_components/status-badge";
import { RevertActionButton } from "../_components/revert-action-button";
import { CorporateActionRowsTable } from "../_components/rows-table";

const LIST_HREF = "/dashboard/master-table/structure-master/corporate-actions";
const BULK_EDIT_HREF = "/dashboard/master-table/structure-master/bulk-edit";

type PageProps = {
  params: Promise<{ id: string }>;
};

export default async function CorporateActionDetailPage({ params }: PageProps) {
  const { id } = await params;
  const actionId = Number(id);

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

  const { result, errorMessage } = await fetchCorporateAction({ actionId });

  if (!result) {
    return (
      <ListPageCard
        icon={History}
        title="Corporate action"
        breadcrumb={[
          { label: "Master Table" },
          { label: "Corporate actions", href: LIST_HREF },
          { label: String(actionId) },
        ]}
      >
        <ErrorBanner message={errorMessage ?? "Could not load the corporate action."} />
      </ListPageCard>
    );
  }

  const { action, rows, counts } = result;
  const canRevert = action.appliedCount > 0 && action.status !== "reverted";

  return (
    <ListPageCard
      icon={History}
      title={`${action.underlyingIsin} — ${action.ratio}`}
      description={
        action.underlyingName
          ? `${action.underlyingName}. ${counts.total} record(s) staged.`
          : `${counts.total} record(s) staged.`
      }
      breadcrumb={[
        { label: "Master Table" },
        { label: "Corporate actions", href: LIST_HREF },
        { label: action.underlyingIsin },
      ]}
      actions={
        <div className="flex gap-2">
          {action.isEditable ? (
            <Button size="sm" variant="outline" asChild>
              <Link href={`${BULK_EDIT_HREF}?action=${action.id}`}>
                <Pencil className="size-4" />
                Edit
              </Link>
            </Button>
          ) : null}
          {canRevert ? (
            <RevertActionButton
              actionId={action.id}
              underlyingIsin={action.underlyingIsin}
              appliedCount={action.appliedCount}
            />
          ) : null}
        </div>
      }
    >
      <ErrorBanner message={errorMessage ?? undefined} className="mb-4" />

      <dl className="mb-6 grid gap-4 rounded-lg border bg-card p-4 sm:grid-cols-2 lg:grid-cols-4">
        <Detail label="Status">
          <CorporateActionStatusBadge status={action.status} />
        </Detail>
        <Detail label="Mode">
          {action.mode === "all" ? "Applied in full" : "Not applied"}
        </Detail>
        <Detail label="Split date">{action.effectiveDate ?? "—"}</Detail>
        <Detail label="Window">
          {action.startDate ?? "—"} → {action.endDate ?? "open"}
        </Detail>
        <Detail label="Affected">{action.affectedCount}</Detail>
        <Detail label="Applied">{action.appliedCount}</Detail>
        <Detail label="Failed">{action.failedCount}</Detail>
        <Detail label="Applied at">{action.appliedAt ?? "—"}</Detail>
        {action.notes ? (
          <div className="sm:col-span-2 lg:col-span-4">
            <dt className="text-muted-foreground text-xs">Notes</dt>
            <dd className="mt-0.5 text-sm">{action.notes}</dd>
          </div>
        ) : null}
      </dl>

      <CorporateActionRowsTable rows={rows} />
    </ListPageCard>
  );
}

function Detail({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div>
      <dt className="text-muted-foreground text-xs">{label}</dt>
      <dd className="mt-0.5 text-sm">{children}</dd>
    </div>
  );
}
