"use client";

import * as React from "react";
import { ChevronDown, ChevronRight, List } from "lucide-react";

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

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 DetailedBreakdownTableProps = {
  comparison: DriftAllocationComparison[];
  ruleConstituents: DriftAllocationConstituent[][];
  reportingCode: string;
};

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

  return (
    <DriftSection
      title="Detailed breakdown & reallocation"
      description="Full rule-level view with position constituents and suggested actions."
      icon={List}
    >
      <div className="overflow-x-auto">
        <Table>
          <TableHeader>
            <TableRow className="hover:bg-transparent">
              <TableHead className="w-8" />
              <TableHead>Rule</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 ruleTotal = row.actual_value;
              const color = DRIFT_RULE_COLORS[index % DRIFT_RULE_COLORS.length];

              return (
                <React.Fragment key={`detail-${row.rule_label}-${index}`}>
                  <TableRow className="group">
                    <TableCell>
                      <span
                        className="inline-block size-2.5 rounded-full ring-2 ring-background"
                        style={{ background: color }}
                      />
                    </TableCell>
                    <TableCell className="min-w-[200px]">
                      <div className="flex flex-wrap items-center gap-2">
                        {constituents.length > 0 ? (
                          <button
                            type="button"
                            className="inline-flex items-center gap-1 rounded-md px-1 py-0.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
                            onClick={() => setExpanded((prev) => ({ ...prev, [index]: !prev[index] }))}
                          >
                            {isOpen ? <ChevronDown className="size-3.5" /> : <ChevronRight className="size-3.5" />}
                            <Badge variant="outline" className="font-mono text-[10px]">
                              {constituents.length} positions
                            </Badge>
                          </button>
                        ) : null}
                        <span className="font-medium">{row.rule_label}</span>
                      </div>
                    </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-emerald-500/40 px-4 py-4 sm:px-6">
                          <h4 className="mb-3 font-medium text-muted-foreground text-xs uppercase tracking-wide">
                            Positions in {row.rule_label}
                          </h4>
                          <Table>
                            <TableHeader>
                              <TableRow className="hover:bg-transparent">
                                <TableHead>Name</TableHead>
                                <TableHead>Ticker / ISIN</TableHead>
                                <TableHead>Bank</TableHead>
                                <TableHead className="text-right">Value</TableHead>
                                <TableHead className="text-right">% of rule</TableHead>
                              </TableRow>
                            </TableHeader>
                            <TableBody>
                              {constituents.map((item, cIndex) => {
                                const pctOfRule = ruleTotal > 0 ? (item.value / ruleTotal) * 100 : 0;
                                return (
                                  <TableRow key={`${item.isin}-${cIndex}`}>
                                    <TableCell>{item.name || "—"}</TableCell>
                                    <TableCell className="font-mono text-xs">
                                      {item.ticker || item.isin || "—"}
                                    </TableCell>
                                    <TableCell>{item.bank_name || "—"}</TableCell>
                                    <TableCell className="text-right tabular-nums">
                                      {formatDriftAmount(item.value, reportingCode)}
                                    </TableCell>
                                    <TableCell className="text-right tabular-nums">
                                      {formatDriftPct(pctOfRule, 1)}
                                    </TableCell>
                                  </TableRow>
                                );
                              })}
                            </TableBody>
                          </Table>
                        </div>
                      </TableCell>
                    </TableRow>
                  ) : null}
                </React.Fragment>
              );
            })}
          </TableBody>
        </Table>
      </div>
    </DriftSection>
  );
}
