"use client";

import * as React from "react";
import { ArrowDown, ArrowUp, ChevronDown, ChevronRight, Hash } from "lucide-react";

import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { cn } from "@/lib/utils";
import type { DriftAllocationComparison } from "@/app/customer/[tenant]/settings/_lib/tenant-settings-server-api";

import { AllocationCharts } from "./allocation-charts";
import { DRIFT_RULE_COLORS } from "./drift-rule-colors";
import { DriftSection, ReallocationAction } from "./drift-ui-primitives";
import {
  formatDriftAmount,
  formatDriftPct,
  formatSignedAmount,
  formatSignedPct,
} from "./format-drift";
import type { DriftAllocationConstituent } from "./map-drift-payload";

type IsinAllocationSectionProps = {
  comparison: DriftAllocationComparison[];
  ruleConstituents: DriftAllocationConstituent[][];
  reportingCode: string;
};

export function IsinAllocationSection({
  comparison,
  ruleConstituents,
  reportingCode,
}: IsinAllocationSectionProps) {
  const [expanded, setExpanded] = React.useState<Record<number, boolean>>({});

  const sellRows = comparison.filter((row) => row.reallocate_action === "reduce" && row.value_gap < 0);
  const buyRows = comparison.filter((row) => row.reallocate_action === "add" && row.value_gap > 0);

  if (!comparison.length) {
    return null;
  }

  return (
    <div className="space-y-6">
      <div className="flex items-start gap-3">
        <div className="flex size-10 shrink-0 items-center justify-center rounded-2xl border border-border/60 bg-violet-500/10 text-violet-600 dark:text-violet-400">
          <Hash className="size-4" />
        </div>
        <div>
          <h2 className="font-semibold text-lg tracking-tight">ISIN actual vs ideal</h2>
          <p className="mt-1 text-muted-foreground text-sm">
            Compare ISIN-level holdings against your ISIN target rules.
          </p>
        </div>
      </div>

      {(sellRows.length > 0 || buyRows.length > 0) && (
        <DriftSection
          title="ISIN suggested reallocation"
          description="Actions to align ISIN holdings with ideal targets."
        >
          <div className="grid gap-4 p-4 sm:grid-cols-2 sm:p-5">
            <IsinPlanBlock title="Reduce / sell" tone="sell" rows={sellRows} reportingCode={reportingCode} />
            <IsinPlanBlock title="Add / buy" tone="buy" rows={buyRows} reportingCode={reportingCode} />
          </div>
        </DriftSection>
      )}

      <DriftSection title="ISIN — actual vs ideal" icon={Hash}>
        <div className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow className="hover:bg-transparent">
                <TableHead className="w-8" />
                <TableHead>ISIN</TableHead>
                <TableHead className="text-right">Ideal</TableHead>
                <TableHead className="text-right">Actual</TableHead>
                <TableHead className="text-right">Drift</TableHead>
                <TableHead className="text-right">Actual value</TableHead>
                <TableHead className="text-right">Target value</TableHead>
                <TableHead className="text-right">Gap</TableHead>
                <TableHead>Action</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {comparison.map((row, index) => {
                const constituents = ruleConstituents[index] ?? [];
                const isOpen = Boolean(expanded[index]);
                const isinLabel = row.isin || row.rule_label;
                const color = DRIFT_RULE_COLORS[index % DRIFT_RULE_COLORS.length];

                return (
                  <React.Fragment key={`${isinLabel}-${index}`}>
                    <TableRow>
                      <TableCell>
                        <span
                          className="inline-block size-2.5 rounded-full ring-2 ring-background"
                          style={{ background: color }}
                        />
                      </TableCell>
                      <TableCell>
                        <button
                          type="button"
                          className="inline-flex items-center gap-1.5 font-mono text-xs font-medium text-left transition-colors hover:text-primary disabled:pointer-events-none disabled:opacity-50"
                          onClick={() => setExpanded((prev) => ({ ...prev, [index]: !prev[index] }))}
                          disabled={!constituents.length}
                        >
                          {constituents.length ? (
                            isOpen ? (
                              <ChevronDown className="size-3.5 shrink-0" />
                            ) : (
                              <ChevronRight className="size-3.5 shrink-0" />
                            )
                          ) : null}
                          {isinLabel}
                        </button>
                      </TableCell>
                      <TableCell className="text-right tabular-nums">{formatDriftPct(row.ideal_pct)}</TableCell>
                      <TableCell className="text-right tabular-nums">{formatDriftPct(row.actual_pct)}</TableCell>
                      <TableCell
                        className={cn(
                          "text-right font-medium tabular-nums",
                          row.drift > 0 && "text-amber-600 dark:text-amber-400",
                          row.drift < 0 && "text-sky-600 dark:text-sky-400",
                          row.drift === 0 && "text-muted-foreground",
                        )}
                      >
                        {formatSignedPct(row.drift)}
                      </TableCell>
                      <TableCell className="text-right tabular-nums">
                        {formatDriftAmount(row.actual_value, reportingCode)}
                      </TableCell>
                      <TableCell className="text-right tabular-nums">
                        {formatDriftAmount(row.target_value, reportingCode)}
                      </TableCell>
                      <TableCell
                        className={cn(
                          "text-right tabular-nums",
                          row.value_gap > 0 && "text-emerald-600 dark:text-emerald-400",
                          row.value_gap < 0 && "text-red-600 dark:text-red-400",
                        )}
                      >
                        {formatSignedAmount(row.value_gap, reportingCode)}
                      </TableCell>
                      <TableCell>
                        <ReallocationAction
                          action={row.reallocate_action}
                          amount={row.value_gap}
                          reportingCode={reportingCode}
                        />
                      </TableCell>
                    </TableRow>
                    {isOpen && constituents.length > 0 ? (
                      <TableRow className="bg-muted/20 hover:bg-muted/20">
                        <TableCell colSpan={9} className="p-0">
                          <div className="border-l-2 border-violet-500/40 px-4 py-4 sm:px-6">
                            <Table>
                              <TableHeader>
                                <TableRow className="hover:bg-transparent">
                                  <TableHead>Name</TableHead>
                                  <TableHead>ISIN / Ticker</TableHead>
                                  <TableHead>Bank</TableHead>
                                  <TableHead className="text-right">Value</TableHead>
                                </TableRow>
                              </TableHeader>
                              <TableBody>
                                {constituents.map((item, cIndex) => (
                                  <TableRow key={`${item.isin}-${cIndex}`}>
                                    <TableCell>{item.name || "—"}</TableCell>
                                    <TableCell className="font-mono text-xs">
                                      {item.isin || item.ticker || "—"}
                                    </TableCell>
                                    <TableCell>{item.bank_name || "—"}</TableCell>
                                    <TableCell className="text-right tabular-nums">
                                      {formatDriftAmount(item.value, reportingCode)}
                                    </TableCell>
                                  </TableRow>
                                ))}
                              </TableBody>
                            </Table>
                          </div>
                        </TableCell>
                      </TableRow>
                    ) : null}
                  </React.Fragment>
                );
              })}
            </TableBody>
          </Table>
        </div>
      </DriftSection>

      <AllocationCharts comparison={comparison} mode="real" layout="compact" />
    </div>
  );
}

function IsinPlanBlock({
  title,
  tone,
  rows,
  reportingCode,
}: {
  title: string;
  tone: "sell" | "buy";
  rows: DriftAllocationComparison[];
  reportingCode: string;
}) {
  const isSell = tone === "sell";
  const total = rows.reduce((sum, row) => sum + Math.abs(row.value_gap), 0);

  return (
    <div
      className={cn(
        "overflow-hidden rounded-xl border",
        isSell
          ? "border-red-200/80 bg-red-50/30 dark:border-red-900/50 dark:bg-red-950/20"
          : "border-emerald-200/80 bg-emerald-50/30 dark:border-emerald-900/50 dark:bg-emerald-950/20",
      )}
    >
      <div
        className={cn(
          "flex items-center justify-between gap-2 border-b px-4 py-3",
          isSell ? "border-red-200/60 dark:border-red-900/40" : "border-emerald-200/60 dark:border-emerald-900/40",
        )}
      >
        <div className="flex items-center gap-2">
          {isSell ? (
            <ArrowDown className="size-4 text-red-600 dark:text-red-400" />
          ) : (
            <ArrowUp className="size-4 text-emerald-600 dark:text-emerald-400" />
          )}
          <span
            className={cn(
              "font-semibold text-sm",
              isSell ? "text-red-900 dark:text-red-200" : "text-emerald-900 dark:text-emerald-200",
            )}
          >
            {title}
          </span>
        </div>
        {rows.length > 0 ? (
          <span
            className={cn(
              "font-bold text-sm tabular-nums",
              isSell ? "text-red-700 dark:text-red-400" : "text-emerald-700 dark:text-emerald-400",
            )}
          >
            {formatDriftAmount(total, reportingCode)}
          </span>
        ) : null}
      </div>

      {!rows.length ? (
        <p className="px-4 py-6 text-center text-muted-foreground text-sm">None</p>
      ) : (
        <ul className="divide-y divide-border/40">
          {rows.map((row) => (
            <li
              key={row.isin || row.rule_label}
              className="flex items-center justify-between gap-3 px-4 py-3 transition-colors hover:bg-background/50"
            >
              <span className="font-mono text-xs">{row.isin || row.rule_label}</span>
              <span
                className={cn(
                  "shrink-0 font-semibold text-sm tabular-nums",
                  isSell ? "text-red-700 dark:text-red-400" : "text-emerald-700 dark:text-emerald-400",
                )}
              >
                {formatDriftAmount(Math.abs(row.value_gap), reportingCode)}
              </span>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
