"use client";

import { PieChart, Scale } from "lucide-react";
import * as React from "react";

import { Table, TableBody, TableCell, TableFooter, 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 { AllocationCompareBar, DriftSection, DriftStatusBadge, NestedRuleLabel } from "./drift-ui-primitives";
import { orderByNest } from "./exclusive-rule-gaps";
import { formatDriftAmount, formatDriftPct, formatSignedPct } from "./format-drift";

type GapSummaryTablesProps = {
  comparison: DriftAllocationComparison[];
  totalPortfolioValue: number;
  reportingCode: string;
  gapTitle?: string;
  gapDescription?: string;
  allocationTitle?: string;
  allocationDescription?: string;
};

export function GapSummaryTables({
  comparison,
  totalPortfolioValue,
  reportingCode,
  gapTitle = "Actual vs Ideal (The Gap)",
  gapDescription = "Compare your target allocation with where you are today. Difference shows over or under target.",
  allocationTitle = "Actual allocation (current state)",
  allocationDescription = "What you currently hold — changes with market movements, investments, withdrawals and rebalancing.",
}: GapSummaryTablesProps) {
  const nestedRows = React.useMemo(
    () =>
      orderByNest(
        comparison.map((row) => ({
          rule_label: row.rule_label,
          dimensions: row.dimensions,
          row,
        })),
      ),
    [comparison],
  );

  return (
    <div className="grid gap-4 xl:grid-cols-2">
      <DriftSection title={gapTitle} description={gapDescription} icon={Scale}>
        <div className="overflow-x-auto p-4 sm:p-5">
          <Table>
            <TableHeader>
              <TableRow className="hover:bg-transparent">
                <TableHead className="w-8" />
                <TableHead>Asset type</TableHead>
                <TableHead>Comparison</TableHead>
                <TableHead className="text-right">Ideal</TableHead>
                <TableHead className="text-right">Actual</TableHead>
                <TableHead className="text-right">Drift</TableHead>
                <TableHead>Status</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {nestedRows.map(({ item, depth, sourceIndex }) => {
                const row = item.row;
                const color = DRIFT_RULE_COLORS[sourceIndex % DRIFT_RULE_COLORS.length];
                return (
                  <TableRow key={`gap-${row.rule_label}-${sourceIndex}`} className="group">
                    <TableCell>
                      <span className="inline-block size-2.5 rounded-full ring-2 ring-background" style={{ background: color }} />
                    </TableCell>
                    <TableCell>
                      <NestedRuleLabel label={row.rule_label} depth={depth} />
                    </TableCell>
                    <TableCell>
                      <AllocationCompareBar idealPct={row.ideal_pct} actualPct={row.actual_pct} color={color} />
                    </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-semibold 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>
                      <DriftStatusBadge drift={row.drift} />
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
          <p className="mt-4 text-muted-foreground text-xs">All percentages are of total portfolio value.</p>
        </div>
      </DriftSection>

      <DriftSection title={allocationTitle} description={allocationDescription} icon={PieChart}>
        <div className="overflow-x-auto p-4 sm:p-5">
          <Table>
            <TableHeader>
              <TableRow className="hover:bg-transparent">
                <TableHead className="w-8" />
                <TableHead>Asset type</TableHead>
                <TableHead className="text-right">Value ({reportingCode})</TableHead>
                <TableHead className="text-right">Share</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {nestedRows.map(({ item, depth, sourceIndex }) => {
                const row = item.row;
                const color = DRIFT_RULE_COLORS[sourceIndex % DRIFT_RULE_COLORS.length];
                const shareWidth = Math.min(Math.max(row.actual_pct, 0), 100);
                return (
                  <TableRow key={`actual-${row.rule_label}-${sourceIndex}`}>
                    <TableCell>
                      <span className="inline-block size-2.5 rounded-full ring-2 ring-background" style={{ background: color }} />
                    </TableCell>
                    <TableCell>
                      <div className="flex min-w-0 items-center gap-3">
                        <NestedRuleLabel label={row.rule_label} depth={depth} />
                        <div className="hidden h-1.5 min-w-[60px] max-w-[100px] flex-1 rounded-full bg-muted/70 sm:block">
                          <div
                            className="h-full rounded-full transition-all"
                            style={{ width: `${shareWidth}%`, background: color }}
                          />
                        </div>
                      </div>
                    </TableCell>
                    <TableCell className="text-right font-medium tabular-nums">
                      {formatDriftAmount(row.actual_value, reportingCode)}
                    </TableCell>
                    <TableCell className="text-right tabular-nums">{formatDriftPct(row.actual_pct)}</TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
            <TableFooter>
              <TableRow className="bg-muted/30 hover:bg-muted/30">
                <TableCell />
                <TableCell className="font-semibold">Total</TableCell>
                <TableCell className="text-right font-semibold tabular-nums">
                  {formatDriftAmount(totalPortfolioValue, reportingCode)}
                </TableCell>
                <TableCell className="text-right font-semibold tabular-nums">100%</TableCell>
              </TableRow>
            </TableFooter>
          </Table>
        </div>
      </DriftSection>
    </div>
  );
}
