"use client";

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

interface BudgetStatusCardProps {
  projectId: string;
}

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

function WarningIcon({ level }: { level: string }) {
  if (level === "critical") {
    return (
      <svg className="w-4 h-4 text-red-500 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
        <path
          fillRule="evenodd"
          d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z"
          clipRule="evenodd"
        />
      </svg>
    );
  }
  if (level === "warning") {
    return (
      <svg className="w-4 h-4 text-orange-500 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
        <path
          fillRule="evenodd"
          d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z"
          clipRule="evenodd"
        />
      </svg>
    );
  }
  return (
    <svg className="w-4 h-4 text-blue-500 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
      <path
        fillRule="evenodd"
        d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
        clipRule="evenodd"
      />
    </svg>
  );
}

function getWarningRowStyle(level: string): string {
  if (level === "critical") return "bg-red-50 dark:bg-red-900/30 border border-red-100 dark:border-red-800 text-red-800 dark:text-red-400";
  if (level === "warning") return "bg-orange-50 dark:bg-orange-900/30 border border-orange-100 dark:border-orange-800 text-orange-800 dark:text-orange-400";
  return "bg-blue-50 dark:bg-blue-900/30 border border-blue-100 dark:border-blue-800 text-blue-800 dark:text-blue-400";
}

export function BudgetStatusCard({ projectId }: BudgetStatusCardProps) {
  const { data, isLoading, error } = trpc.timeline.getBudgetStatus.useQuery({ projectId });

  if (isLoading) {
    return (
      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
        <div className="h-4 shimmer-skeleton rounded w-1/3 mb-4" />
        <div className="h-3 shimmer-skeleton rounded-full mb-3" />
        <div className="grid grid-cols-4 gap-3">
          {[0, 1, 2, 3].map((i) => (
            <div key={i} className="h-14 shimmer-skeleton rounded-lg" />
          ))}
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-white dark:bg-gray-800 rounded-xl border border-red-200 dark:border-red-800 p-6">
        <p className="text-sm text-red-600 dark:text-red-400">Failed to load budget status: {error.message}</p>
      </div>
    );
  }

  if (!data) return null;

  const {
    budgetCents,
    allocatedCents,
    confirmedCents,
    proposedCents,
    remainingCents,
    winProbabilityWeightedCents,
    warnings,
  } = data;

  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 space-y-5">
      <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300 uppercase tracking-wider">Budget Status</h3>

      {/* Progress bar */}
      <BudgetStatusBar
        budgetCents={budgetCents}
        allocatedCents={allocatedCents}
        confirmedCents={confirmedCents}
        proposedCents={proposedCents}
        warnings={warnings}
      />

      {/* Numeric details grid */}
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
        <div className="bg-gray-50 dark:bg-gray-900 rounded-lg p-3">
          <p className="text-xs text-gray-500 dark:text-gray-400 mb-1 flex items-center">Total Budget<InfoTooltip content="The total approved budget for this project as set during creation or editing." /></p>
          <p className="text-sm font-semibold text-gray-900 dark:text-gray-100">{formatEur(budgetCents)}</p>
        </div>
        <div className="bg-green-50 dark:bg-green-900/30 rounded-lg p-3">
          <p className="text-xs text-gray-500 dark:text-gray-400 mb-1 flex items-center">Confirmed<InfoTooltip content="Sum of costs from confirmed assignments (working days x daily rate)." /></p>
          <p className="text-sm font-semibold text-green-800 dark:text-green-400">{formatEur(confirmedCents)}</p>
        </div>
        <div className="bg-yellow-50 dark:bg-yellow-900/30 rounded-lg p-3">
          <p className="text-xs text-gray-500 dark:text-gray-400 mb-1 flex items-center">Proposed<InfoTooltip content="Sum of costs from proposed (not yet confirmed) assignments." /></p>
          <p className="text-sm font-semibold text-yellow-800 dark:text-yellow-400">{formatEur(proposedCents)}</p>
        </div>
        <div className={clsx("rounded-lg p-3", remainingCents < 0 ? "bg-red-50 dark:bg-red-900/30" : "bg-blue-50 dark:bg-blue-900/30")}>
          <p className="text-xs text-gray-500 dark:text-gray-400 mb-1 flex items-center">Remaining<InfoTooltip content="Total budget minus all allocated costs (confirmed + proposed). Negative means over budget." /></p>
          <p className={clsx("text-sm font-semibold", remainingCents < 0 ? "text-red-800 dark:text-red-400" : "text-blue-800 dark:text-blue-400")}>
            {formatEur(remainingCents)}
          </p>
        </div>
      </div>

      {/* Win-probability weighted amount */}
      <div className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400 border-t border-gray-100 dark:border-gray-700 pt-3">
        <span className="text-gray-400 dark:text-gray-500 flex items-center">Win-probability weighted cost:<InfoTooltip content="Allocated cost multiplied by the project's win probability. Reflects expected cost in the pipeline." /></span>
        <span className="font-medium text-gray-800 dark:text-gray-100">{formatEur(winProbabilityWeightedCents)}</span>
      </div>

      {/* Warnings list */}
      {warnings.length > 0 && (
        <div className="space-y-2 border-t border-gray-100 dark:border-gray-700 pt-3">
          <p className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Warnings</p>
          {warnings.map((warning, idx) => (
            <div
              key={idx}
              className={clsx(
                "flex items-start gap-2 rounded-lg px-3 py-2 text-sm",
                getWarningRowStyle(warning.level),
              )}
            >
              <WarningIcon level={warning.level} />
              <span>{warning.message}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
