import { AlertTriangle, Ban, CircleDollarSign, Link2Off } from "lucide-react";
import { redirect } from "next/navigation";

import { ErrorBanner } from "@/components/shared/error-banner";
import { ExcludedFromTotalValueHeaderActions } from "@/app/dashboard/master-table/excluded-from-total-value/_components/list-header-actions";
import { ExcludedFromTotalValueTable } from "@/app/dashboard/master-table/excluded-from-total-value/_components/excluded-from-total-value-table";
import { fetchBackendExcludedFromTotalValue } from "@/app/dashboard/master-table/excluded-from-total-value/_lib/excluded-from-total-value-server-api";
import { MissingAssetMarketDataHeaderActions } from "@/app/dashboard/master-table/missing-asset-market-data/_components/list-header-actions";
import { fetchBackendMissingAssetMarketData } from "@/app/dashboard/master-table/missing-asset-market-data/_lib/missing-asset-market-data-server-api";
import { MissingMarketPriceIsinHeaderActions } from "@/app/dashboard/master-table/missing-market-price-isin/_components/list-header-actions";
import { MissingMarketPriceIsinTable } from "@/app/dashboard/master-table/missing-market-price-isin/_components/missing-market-price-isin-table";
import { fetchBackendMissingMarketPriceIsins } from "@/app/dashboard/master-table/missing-market-price-isin/_lib/missing-market-price-isin-server-api";
import { OptionsInvalidIsinHeaderActions } from "@/app/dashboard/master-table/options-invalid-isin/_components/list-header-actions";
import { OptionsInvalidIsinTable } from "@/app/dashboard/master-table/options-invalid-isin/_components/options-invalid-isin-table";
import { fetchBackendOptionsInvalidIsins } from "@/app/dashboard/master-table/options-invalid-isin/_lib/options-invalid-isin-server-api";

import { HubMissingDetailsTable } from "../_components/hub-missing-details-bindings";
import { HubShell } from "../_components/hub-shell";
import { ValuationGapsEmptyHint } from "../_components/valuation-gaps-empty-hint";
import {
  buildValuationGapsHref,
  formatTabLabel,
  hasExplicitValuationGapsTab,
  parseValuationGapsMissingDetailsState,
  parseValuationGapsTab,
  pickDefaultValuationGapsTab,
  VALUATION_GAPS_HELPER,
  VALUATION_GAPS_TABS,
  type ValuationGapsTab,
} from "../_lib/tab-params";

export const dynamic = "force-dynamic";

const BREADCRUMB = [
  { label: "Market data", href: "/dashboard/isin-ops" },
  { label: "Data gaps" },
] as const;

type PageProps = {
  searchParams: Promise<{
    tab?: string;
    isin?: string;
    base_asset_class?: string;
    page?: string;
    page_size?: string;
  }>;
};

export default async function ValuationGapsHubPage({ searchParams }: PageProps) {
  const params = await searchParams;
  const explicitTab = hasExplicitValuationGapsTab(params.tab);
  const requestedTab = parseValuationGapsTab(params.tab);
  const missingDetailsState = parseValuationGapsMissingDetailsState(params);

  const [missingPrice, excluded, missingDetails, optionsIsin] = await Promise.all([
    fetchBackendMissingMarketPriceIsins(),
    fetchBackendExcludedFromTotalValue(),
    fetchBackendMissingAssetMarketData(
      explicitTab && requestedTab === "missing-details"
        ? {
            isin: missingDetailsState.isin,
            baseAssetClass: missingDetailsState.baseAssetClass,
            page: missingDetailsState.page,
            pageSize: missingDetailsState.pageSize,
          }
        : {
            page: 1,
            pageSize: 1,
            isin: "",
            baseAssetClass: "all",
          },
    ),
    fetchBackendOptionsInvalidIsins(),
  ]);

  const missingPriceCount = missingPrice.totalCount || missingPrice.rows.length;
  const excludedCount = excluded.totalCount || excluded.rows.length;
  const missingDetailsCount = missingDetails.totalCount;
  const optionsIsinCount = optionsIsin.totalCount || optionsIsin.rows.length;

  const tab = explicitTab
    ? requestedTab
    : pickDefaultValuationGapsTab({
        missingPrice: missingPriceCount,
        excluded: excludedCount,
        missingDetails: missingDetailsCount,
        optionsIsin: optionsIsinCount,
      });

  if (!explicitTab && tab !== "missing-price") {
    redirect(buildValuationGapsHref(tab));
  }

  const tabs = VALUATION_GAPS_TABS.map((entry) => {
    const count =
      entry.value === "missing-price"
        ? missingPriceCount
        : entry.value === "excluded"
          ? excludedCount
          : entry.value === "options-isin"
            ? optionsIsinCount
            : missingDetailsCount;

    return {
      value: entry.value,
      label: formatTabLabel(entry.label, count),
      href: buildValuationGapsHref(entry.value),
    };
  });

  const crossLinks = [
    {
      tab: "missing-price" as const,
      label: "Missing price",
      count: missingPriceCount,
    },
    {
      tab: "excluded" as const,
      label: "Excluded",
      count: excludedCount,
    },
    {
      tab: "missing-details" as const,
      label: "Missing details",
      count: missingDetailsCount,
    },
    {
      tab: "options-isin" as const,
      label: "Options ISIN",
      count: optionsIsinCount,
    },
  ];

  if (tab === "excluded") {
    const countLabel =
      excludedCount > 0
        ? `${excludedCount} holding${excludedCount === 1 ? "" : "s"} omitted from Total Value`
        : "Nothing is currently excluded from Total Value.";

    return (
      <HubShell
        icon={Ban}
        title="Excluded"
        description={countLabel}
        breadcrumb={[...BREADCRUMB]}
        actions={<ExcludedFromTotalValueHeaderActions />}
        activeTab={"excluded" satisfies ValuationGapsTab}
        tabs={tabs}
        helperText={VALUATION_GAPS_HELPER}
      >
        <ErrorBanner message={excluded.errorMessage} className="mb-4" />
        {excluded.rows.length === 0 ? (
          <ValuationGapsEmptyHint
            message="No holdings excluded from Total Value right now."
            links={crossLinks.filter((link) => link.tab !== "excluded")}
          />
        ) : (
          <ExcludedFromTotalValueTable data={excluded.rows} />
        )}
      </HubShell>
    );
  }

  if (tab === "missing-details") {
    return (
      <HubShell
        icon={AlertTriangle}
        title="Missing details"
        description="ISINs with incomplete asset detail records or missing required fields in master tables."
        breadcrumb={[...BREADCRUMB]}
        actions={<MissingAssetMarketDataHeaderActions />}
        activeTab={"missing-details" satisfies ValuationGapsTab}
        tabs={tabs}
        helperText={VALUATION_GAPS_HELPER}
      >
        <ErrorBanner message={missingDetails.errorMessage} className="mb-4" />
        {missingDetails.totalCount === 0 ? (
          <ValuationGapsEmptyHint
            message="No missing master-data rows right now."
            links={crossLinks.filter((link) => link.tab !== "missing-details")}
          />
        ) : (
          <HubMissingDetailsTable
            data={missingDetails.rows}
            filters={{
              isin: missingDetailsState.isin,
              baseAssetClass: missingDetailsState.baseAssetClass,
            }}
            totalCount={missingDetails.totalCount}
            page={missingDetails.page}
            pageSize={missingDetails.pageSize}
            pageCount={missingDetails.pageCount}
          />
        )}
      </HubShell>
    );
  }

  if (tab === "options-isin") {
    return (
      <HubShell
        icon={Link2Off}
        title="Options ISIN"
        description="Options whose underlier is not a valid 12-character ISO ISIN. Override to regenerate parent_isin and rewrite temp, transactions, and market rows."
        breadcrumb={[...BREADCRUMB]}
        actions={<OptionsInvalidIsinHeaderActions />}
        activeTab={"options-isin" satisfies ValuationGapsTab}
        tabs={tabs}
        helperText={VALUATION_GAPS_HELPER}
      >
        <ErrorBanner message={optionsIsin.errorMessage} className="mb-4" />
        {optionsIsin.rows.length === 0 ? (
          <ValuationGapsEmptyHint
            message="Every listed option underlier is already a valid ISO ISIN."
            links={crossLinks.filter((link) => link.tab !== "options-isin")}
          />
        ) : (
          <OptionsInvalidIsinTable data={optionsIsin.rows} />
        )}
      </HubShell>
    );
  }

  return (
    <HubShell
      icon={CircleDollarSign}
      title="Missing price"
      description="Tickers with no usable market price. Skips Interest/Dividend, Call Deposit, Cash Withdrawal, and Fx Accumulator — those are not priced on this list."
      breadcrumb={[...BREADCRUMB]}
      actions={<MissingMarketPriceIsinHeaderActions />}
      activeTab={"missing-price" satisfies ValuationGapsTab}
      tabs={tabs}
      helperText={VALUATION_GAPS_HELPER}
    >
      <ErrorBanner message={missingPrice.errorMessage} className="mb-4" />
      {missingPrice.rows.length === 0 ? (
        <ValuationGapsEmptyHint
          message="Every listed ticker already has a usable market price."
          links={crossLinks.filter((link) => link.tab !== "missing-price")}
        />
      ) : (
        <MissingMarketPriceIsinTable data={missingPrice.rows} />
      )}
    </HubShell>
  );
}
