"use client";

import { PieChart, Scale } from "lucide-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 } from "./drift-ui-primitives";
import { formatDriftAmount, formatDriftPct, formatSignedPct } from "./format-drift";

type GapSummaryTablesProps = {
  comparison: DriftAllocationComparison[];
  totalPortfolioValue: number;
  reportingCode: string;
};

export function GapSummaryTables({ comparison, totalPortfolioValue, reportingCode }: GapSummaryTablesProps) {
  return (
    <div className="grid gap-4 xl:grid-cols-2">
      <DriftSection
        title="Actual vs Ideal (The Gap)"
        description="Compare your target allocation with where you are today. Difference shows over or under target."
        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>
              {comparison.map((row, index) => {
                const color = DRIFT_RULE_COLORS[index % DRIFT_RULE_COLORS.length];
                return (
                  <TableRow key={`gap-${row.rule_label}-${index}`} className="group">
                    <TableCell>
                      <span className="inline-block size-2.5 rounded-full ring-2 ring-background" style={{ background: color }} />
                    </TableCell>
                    <TableCell className="font-medium">{row.rule_label}</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="Actual allocation (current state)"
        description="What you currently hold — changes with market movements, investments, withdrawals and rebalancing."
        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>
              {comparison.map((row, index) => {
                const color = DRIFT_RULE_COLORS[index % DRIFT_RULE_COLORS.length];
                const shareWidth = Math.min(Math.max(row.actual_pct, 0), 100);
                return (
                  <TableRow key={`actual-${row.rule_label}-${index}`}>
                    <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">
                        <span className="font-medium">{row.rule_label}</span>
                        <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>
  );
}
