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

import { ListPageCard } from "@/app/dashboard/_components";
import { ErrorBanner } from "@/components/shared/error-banner";
import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

import { fetchCorporateActionList } from "../bulk-edit/_lib/corporate-action-server-api";
import { CorporateActionStatusBadge } from "./_components/status-badge";

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

type PageProps = {
  searchParams: Promise<{ isin?: string; status?: string; page?: string }>;
};

export default async function CorporateActionsPage({ searchParams }: PageProps) {
  const params = await searchParams;
  const page = Number(params.page ?? 1);

  const { items, totalCount, pageCount, errorMessage } = await fetchCorporateActionList({
    underlyingIsin: params.isin?.trim() || undefined,
    status: params.status?.trim() || undefined,
    page: Number.isInteger(page) && page > 0 ? page : 1,
  });

  return (
    <ListPageCard
      icon={History}
      title="Structure corporate actions"
      description="Every split applied to a structure underlying, with the records it touched and an undo for each."
      breadcrumb={[
        { label: "Master Table" },
        { label: "Structure master", href: "/dashboard/master-table/structure-master" },
        { label: "Corporate actions" },
      ]}
      actions={
        <Button size="sm" asChild>
          <Link href={BULK_EDIT_HREF}>New bulk edit</Link>
        </Button>
      }
    >
      <ErrorBanner message={errorMessage ?? undefined} className="mb-4" />

      <div className="overflow-x-auto rounded-lg border bg-card">
        <Table>
          <TableHeader className="bg-muted/15">
            <TableRow>
              <TableHead className="px-3">Underlying</TableHead>
              <TableHead className="px-3">Ratio</TableHead>
              <TableHead className="px-3">Window</TableHead>
              <TableHead className="px-3">Mode</TableHead>
              <TableHead className="px-3">Status</TableHead>
              <TableHead className="px-3 text-right">Affected</TableHead>
              <TableHead className="px-3 text-right">Applied</TableHead>
              <TableHead className="px-3">Created</TableHead>
              <TableHead className="px-3" />
            </TableRow>
          </TableHeader>
          <TableBody>
            {items.length === 0 ? (
              <TableRow>
                <TableCell colSpan={9} className="px-3 py-8 text-center text-muted-foreground">
                  No corporate actions recorded yet.
                </TableCell>
              </TableRow>
            ) : (
              items.map((action) => (
                <TableRow key={action.id} className="hover:bg-muted/30">
                  <TableCell className="px-3 text-sm">
                    <div className="flex flex-col">
                      <span className="font-medium">{action.underlyingIsin}</span>
                      {action.underlyingName ? (
                        <span className="text-muted-foreground text-xs">
                          {action.underlyingName}
                        </span>
                      ) : null}
                    </div>
                  </TableCell>
                  <TableCell className="px-3 font-mono text-sm">{action.ratio}</TableCell>
                  <TableCell className="px-3 text-sm whitespace-nowrap">
                    {action.startDate ?? "—"} → {action.endDate ?? "open"}
                  </TableCell>
                  <TableCell className="px-3 text-sm">
                    {action.mode === "all" ? "Applied in full" : "—"}
                  </TableCell>
                  <TableCell className="px-3">
                    <CorporateActionStatusBadge status={action.status} />
                  </TableCell>
                  <TableCell className="px-3 text-right text-sm tabular-nums">
                    {action.affectedCount}
                  </TableCell>
                  <TableCell className="px-3 text-right text-sm tabular-nums">
                    {action.appliedCount}
                    {action.failedCount > 0 ? (
                      <span className="text-destructive"> / {action.failedCount} failed</span>
                    ) : null}
                  </TableCell>
                  <TableCell className="px-3 text-muted-foreground text-xs whitespace-nowrap">
                    {action.createdAt ?? "—"}
                  </TableCell>
                  <TableCell className="px-3">
                    <div className="flex justify-end gap-1">
                      {action.isEditable ? (
                        <Button size="sm" variant="ghost" asChild>
                          <Link href={`${BULK_EDIT_HREF}?action=${action.id}`}>
                            <Pencil className="size-4" />
                            Edit
                          </Link>
                        </Button>
                      ) : null}
                      <Button size="sm" variant="ghost" asChild>
                        <Link href={`${LIST_HREF}/${action.id}`}>View</Link>
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      <p className="mt-3 text-muted-foreground text-sm">
        {totalCount} corporate action(s){pageCount > 1 ? ` · page ${page} of ${pageCount}` : ""}.
      </p>
    </ListPageCard>
  );
}
