"use client";

import Link from "next/link";
import { Building2, Layers3, ListOrdered, Wallet } from "lucide-react";

import { ReportLoadingPanel } from "@/app/customer/[tenant]/reports/_shared/components/report-loading-panel";
import { IsinAllocationSection } from "@/app/customer/[tenant]/reports/_shared/drift-allocation/isin-allocation-section";
import { RealAllocationSection } from "@/app/customer/[tenant]/reports/_shared/drift-allocation/real-allocation-section";
import { DriftKpiCard } from "@/app/customer/[tenant]/reports/_shared/drift-allocation/drift-ui-primitives";
import { formatDriftAmount } from "@/app/customer/[tenant]/reports/_shared/drift-allocation/format-drift";
import { cn } from "@/lib/utils";

import type { DriftAllocationData } from "../../_lib/drift-allocation-types";

type DriftAllocationPanelProps = {
  tenant: string;
  data: DriftAllocationData | null | undefined;
  isLoading: boolean;
  errorMessage: string | null;
};

export function DriftAllocationPanel({
  tenant,
  data,
  isLoading,
  errorMessage,
}: DriftAllocationPanelProps) {
  const comparison = data?.comparison ?? [];
  const isinComparison = data?.isinComparison ?? [];
  const hasRules = comparison.length > 0 || isinComparison.length > 0;
  const hasPositions = (data?.totalPortfolioValue ?? 0) > 0;

  return (
    <ReportLoadingPanel
      loading={isLoading}
      label="Loading Actual vs Ideal allocation…"
      className={cn(isLoading && "pointer-events-none")}
    >
      {!isLoading && errorMessage ? (
        <div className="rounded-2xl border border-destructive/30 bg-destructive/5 p-10 text-center text-destructive text-sm">
          {errorMessage}
        </div>
      ) : !isLoading && !hasRules ? (
        <div className="space-y-4 rounded-2xl border border-dashed border-border/80 p-10 text-center">
          <p className="text-muted-foreground text-sm">
            No target allocations defined. Define your portfolio targets in Drift Settings to see actual vs ideal
            allocation here.
          </p>
          <Link
            href={`/customer/${tenant}/settings?section=drift`}
            className="inline-flex items-center gap-2 font-medium text-primary text-sm underline-offset-4 hover:underline"
          >
            Open Drift Settings
          </Link>
        </div>
      ) : !isLoading && !hasPositions ? (
        <div className="rounded-2xl border border-dashed border-border/80 p-10 text-center text-muted-foreground text-sm">
          No portfolio data for the selected banks.
        </div>
      ) : !isLoading && data ? (
        <div className="space-y-6">
          <RealAllocationSection
            comparison={data.comparison}
            ruleConstituents={data.ruleConstituents}
            totalPortfolioValue={data.totalPortfolioValue}
            reportingCode={data.reportingCode}
            showTotalCard={false}
          />
          {isinComparison.length > 0 ? (
            <IsinAllocationSection
              comparison={isinComparison}
              ruleConstituents={data.isinConstituents}
              reportingCode={data.reportingCode}
            />
          ) : null}
        </div>
      ) : (
        <div className="h-full min-h-[calc(100vh-280px)]" aria-hidden />
      )}
    </ReportLoadingPanel>
  );
}

export function DriftGrandTotalStrip({
  data,
  isLoading,
}: {
  data: DriftAllocationData | null | undefined;
  isLoading: boolean;
}) {
  const comparison = data?.comparison ?? [];
  const positionCount = (data?.ruleConstituents ?? []).reduce((sum, group) => sum + group.length, 0);
  const reportingCode = data?.reportingCode ?? "USD";

  return (
    <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
      <DriftKpiCard
        label="Portfolio value"
        value={
          isLoading
            ? "—"
            : formatDriftAmount(data?.totalPortfolioValue ?? 0, reportingCode)
        }
        icon={Wallet}
        hint={reportingCode}
      />
      <DriftKpiCard
        label="Banks"
        value={isLoading ? "—" : String(data?.banks.length ?? 0)}
        icon={Building2}
        hint="Selected custodians"
      />
      <DriftKpiCard
        label="Allocation rules"
        value={isLoading ? "—" : String(comparison.length)}
        icon={Layers3}
        hint="Target segments defined"
      />
      <DriftKpiCard
        label="Positions"
        value={isLoading ? "—" : String(positionCount)}
        icon={ListOrdered}
        hint="Across all rules"
      />
    </div>
  );
}
