"use client";

import { clsx } from "clsx";
import { formatMoney } from "~/lib/format.js";
import { InfoTooltip } from "~/components/ui/InfoTooltip.js";

interface Warning {
  level: string;
  message: string;
}

interface BudgetStatusBarProps {
  budgetCents: number;
  allocatedCents: number;
  confirmedCents: number;
  proposedCents: number;
  warnings: Warning[];
  className?: string;
}

const formatEur = (cents: number) => formatMoney(cents, "EUR", 2);

function getConfirmedBarColor(utilizationPercent: number): string {
  if (utilizationPercent > 95) return "bg-red-600";
  if (utilizationPercent > 85) return "bg-orange-600";
  if (utilizationPercent > 70) return "bg-yellow-600";
  return "bg-green-600";
}

function getProposedBarColor(utilizationPercent: number): string {
  if (utilizationPercent > 95) return "bg-red-300";
  if (utilizationPercent > 85) return "bg-orange-300";
  if (utilizationPercent > 70) return "bg-yellow-300";
  return "bg-green-300";
}

function getWarningBadgeStyle(level: string): string {
  if (level === "critical") return "bg-red-100 text-red-700 border border-red-200";
  if (level === "warning") return "bg-orange-100 text-orange-700 border border-orange-200";
  return "bg-yellow-100 text-yellow-700 border border-yellow-200";
}

export function BudgetStatusBar({
  budgetCents,
  allocatedCents,
  confirmedCents,
  proposedCents,
  warnings,
  className,
}: BudgetStatusBarProps) {
  const utilizationPercent = budgetCents > 0 ? (allocatedCents / budgetCents) * 100 : 0;
  const confirmedPercent = budgetCents > 0 ? (confirmedCents / budgetCents) * 100 : 0;
  const proposedPercent = budgetCents > 0 ? (proposedCents / budgetCents) * 100 : 0;
  const remainingCents = budgetCents - allocatedCents;

  // Cap visual bar segments at 100% total
  const cappedConfirmedPercent = Math.min(confirmedPercent, 100);
  const cappedProposedPercent = Math.min(proposedPercent, Math.max(0, 100 - cappedConfirmedPercent));

  const highestWarning = warnings.length > 0
    ? warnings.reduce((prev, curr) => {
        const levels: Record<string, number> = { info: 0, warning: 1, critical: 2 };
        return (levels[curr.level] ?? 0) > (levels[prev.level] ?? 0) ? curr : prev;
      })
    : null;

  return (
    <div className={clsx("space-y-1.5", className)}>
      {/* Progress bar with stacked segments */}
      <div className="flex items-center gap-1 mb-0.5">
        <span className="text-xs text-gray-500">Budget utilization</span>
        <InfoTooltip content="Visual budget bar: the solid segment shows confirmed costs, the lighter segment shows proposed costs. Green = within budget, yellow = approaching limit, red = over budget." />
      </div>
      <div className="relative h-3 bg-gray-100 rounded-full overflow-hidden">
        {/* Confirmed segment */}
        <div
          className={clsx("absolute left-0 top-0 h-full transition-all", getConfirmedBarColor(utilizationPercent))}
          style={{ width: `${cappedConfirmedPercent}%` }}
        />
        {/* Proposed segment */}
        <div
          className={clsx("absolute top-0 h-full transition-all", getProposedBarColor(utilizationPercent))}
          style={{ left: `${cappedConfirmedPercent}%`, width: `${cappedProposedPercent}%` }}
        />
      </div>

      {/* Labels row */}
      <div className="flex items-center justify-between text-xs text-gray-600">
        <span>
          <span className="font-medium">{formatEur(allocatedCents)}</span>
          {" / "}
          <span>{formatEur(budgetCents)}</span>
          {" "}
          <span className="text-gray-400">({utilizationPercent.toFixed(1)}%)</span>
        </span>

        <div className="flex items-center gap-2">
          {highestWarning && (
            <span
              className={clsx(
                "inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium",
                getWarningBadgeStyle(highestWarning.level),
              )}
            >
              {highestWarning.level === "critical" ? "⚠" : highestWarning.level === "warning" ? "!" : "i"}
              {warnings.length > 1 ? `${warnings.length} warnings` : "Warning"}
            </span>
          )}
          <span className={clsx("font-medium", remainingCents < 0 ? "text-red-600" : "text-gray-700")}>
            {remainingCents >= 0 ? `${formatEur(remainingCents)} left` : `${formatEur(Math.abs(remainingCents))} over`}
          </span>
        </div>
      </div>

      {/* Legend */}
      <div className="flex items-center gap-3 text-xs text-gray-500">
        <span className="flex items-center gap-1">
          <span className={clsx("inline-block w-2.5 h-2.5 rounded-sm", getConfirmedBarColor(utilizationPercent))} />
          Confirmed {formatEur(confirmedCents)}
        </span>
        <span className="flex items-center gap-1">
          <span className={clsx("inline-block w-2.5 h-2.5 rounded-sm", getProposedBarColor(utilizationPercent))} />
          Proposed {formatEur(proposedCents)}
        </span>
      </div>
    </div>
  );
}
