"use client";

import React from "react";
import { CheckCircle2, AlertTriangle, UserCheck } from "lucide-react";
import { ProcessedReceipt } from "@/lib/schema/receipt";
import { receiptNeedsAttention } from "@/lib/ai/recalculate";
import { useI18n } from "@/lib/i18n/context";

export type ReceiptStatusTier = "scanned" | "pending_review" | "confirmed";

export interface StatusBadgeProps {
  /** Explicit status string or tier */
  status?: ReceiptStatusTier | string | null;
  /** Or pass the whole receipt to automatically compute tier */
  receipt?: ProcessedReceipt | null;
  /** Size variant */
  size?: "sm" | "md" | "lg";
  /** Whether to show status icon */
  showIcon?: boolean;
  /** Whether to show colored indicator dot */
  showDot?: boolean;
  /** Custom label override */
  label?: string;
  /** Optional interactive click handler (e.g. for toggling / cycling status) */
  onClick?: (e: React.MouseEvent) => void;
  /** Additional CSS classes */
  className?: string;
  /** Test identifier */
  testId?: string;
}

/**
 * Resolves a raw string or ProcessedReceipt into one of the 3 canonical tiers:
 * - "scanned" (Erfasst / Gültig) -> Emerald
 * - "pending_review" (Prüfung erforderlich) -> Amber
 * - "confirmed" (Bestätigt) -> Slate/Blue
 */
export function resolveReceiptStatusTier(
  input: ProcessedReceipt | string | null | undefined
): ReceiptStatusTier {
  if (!input) return "scanned";

  if (typeof input === "object") {
    // If user manually confirmed receipt
    if (input.validation?.userConfirmed) {
      return "confirmed";
    }
    // If validation needs attention (math error or low confidence)
    if (receiptNeedsAttention(input)) {
      return "pending_review";
    }
    // Check receipt status string if present
    const s = String(input.status || "").toLowerCase();
    if (s === "needs_review" || s === "pending" || s === "pending_review") {
      return "pending_review";
    }
    if (s === "confirmed" || s === "reviewed") {
      return "confirmed";
    }
    return "scanned";
  }

  const normalized = String(input).trim().toLowerCase();
  if (
    normalized === "pending" ||
    normalized === "pending_review" ||
    normalized === "needs_review" ||
    normalized === "pruefen" ||
    normalized === "prüfen" ||
    normalized === "pruefung_erforderlich" ||
    normalized === "prüfung erforderlich" ||
    normalized === "attention"
  ) {
    return "pending_review";
  }

  if (
    normalized === "confirmed" ||
    normalized === "bestaetigt" ||
    normalized === "bestätigt" ||
    normalized === "reviewed" ||
    normalized === "approved"
  ) {
    return "confirmed";
  }

  return "scanned";
}

export function getStatusTierMeta(tier: ReceiptStatusTier) {
  switch (tier) {
    case "pending_review":
      return {
        labelDe: "Prüfung erforderlich",
        labelEn: "Pending Review",
        shortLabelDe: "Prüfen",
        shortLabelEn: "Review",
        bgColor: "bg-amber-50",
        textColor: "text-amber-800",
        borderColor: "border-amber-200",
        dotColor: "bg-amber-500",
        pulseDot: true,
        icon: AlertTriangle,
        iconColor: "text-amber-600",
        description: "Rechnerische Abweichung oder unsichere Felder erkannt",
        descriptionEn: "Math discrepancy or low-confidence fields detected",
      };
    case "confirmed":
      return {
        labelDe: "Bestätigt",
        labelEn: "Confirmed",
        shortLabelDe: "Bestätigt",
        shortLabelEn: "Confirmed",
        bgColor: "bg-blue-50",
        textColor: "text-blue-700",
        borderColor: "border-blue-200",
        dotColor: "bg-blue-600",
        pulseDot: false,
        icon: UserCheck,
        iconColor: "text-blue-600",
        description: "Manuell vom Benutzer verifiziert & freigegeben",
        descriptionEn: "Manually verified and confirmed by user",
      };
    case "scanned":
    default:
      return {
        labelDe: "Erfasst",
        labelEn: "Scanned",
        shortLabelDe: "Gültig",
        shortLabelEn: "Valid",
        bgColor: "bg-emerald-50",
        textColor: "text-emerald-800",
        borderColor: "border-emerald-200",
        dotColor: "bg-emerald-500",
        pulseDot: false,
        icon: CheckCircle2,
        iconColor: "text-emerald-600",
        description: "Erfolgreich ausgelesen und mathematisch plausibel",
        descriptionEn: "Successfully parsed with valid math",
      };
  }
}

export function getReceiptReviewReason(
  receipt?: ProcessedReceipt | null,
  isDe: boolean = false
): {
  detail: string;
  badgeLabel: string;
} {
  if (!receipt) {
    return {
      detail: isDe ? "Status bereit" : "Ready for review",
      badgeLabel: isDe ? "Erfasst" : "Scanned",
    };
  }

  if (receipt.validation?.userConfirmed) {
    return {
      detail: isDe ? "Vom Benutzer verifiziert und bestätigt" : "User verified and confirmed",
      badgeLabel: isDe ? "Bestätigt" : "Confirmed",
    };
  }

  if (receiptNeedsAttention(receipt)) {
    const issues = receipt.validation?.issues || [];
    const firstIssue = issues[0];

    if (firstIssue?.message) {
      // Short clean badge label
      let badgeLabel = isDe ? "Prüfung erforderlich" : "Pending Review";
      if (firstIssue.message.toLowerCase().includes("differenz") || firstIssue.message.toLowerCase().includes("weicht") || firstIssue.message.toLowerCase().includes("diff")) {
        badgeLabel = isDe ? "Prüfen: Summen-Differenz" : "Review: Total Diff";
      } else if (firstIssue.message.toLowerCase().includes("mwst") || firstIssue.message.toLowerCase().includes("steuer") || firstIssue.message.toLowerCase().includes("tax")) {
        badgeLabel = isDe ? "Prüfen: MwSt / Steuer" : "Review: Tax Split";
      } else if (firstIssue.message.toLowerCase().includes("händler") || firstIssue.message.toLowerCase().includes("merchant")) {
        badgeLabel = isDe ? "Prüfen: Händlername" : "Review: Merchant";
      } else if (firstIssue.message.toLowerCase().includes("datum") || firstIssue.message.toLowerCase().includes("date")) {
        badgeLabel = isDe ? "Prüfen: Belegdatum" : "Review: Date";
      }

      return {
        detail: isDe ? `Prüfung erforderlich: ${firstIssue.message}` : `Review needed: ${firstIssue.message}`,
        badgeLabel,
      };
    }

    if (receipt.validation?.reviewReason) {
      return {
        detail: isDe ? `Prüfung erforderlich: ${receipt.validation.reviewReason}` : `Review needed: ${receipt.validation.reviewReason}`,
        badgeLabel: isDe ? "Prüfen: Betrag unklar" : "Review: Ambiguous Total",
      };
    }

    if (!receipt.validation?.isMathValid) {
      return {
        detail: isDe
          ? "Prüfung erforderlich: Netto + Steuer stimmt nicht mit Brutto überein"
          : "Review needed: Net + Tax does not equal gross total",
        badgeLabel: isDe ? "Prüfen: Summe/MwSt" : "Review: Math/Tax",
      };
    }

    if ((receipt.merchant?.confidence ?? 1) < 0.8) {
      return {
        detail: isDe
          ? "Prüfung erforderlich: Händlername mit geringer Konfidenz erkannt"
          : "Review needed: Merchant recognized with low confidence",
        badgeLabel: isDe ? "Prüfen: Händler" : "Review: Merchant",
      };
    }

    return {
      detail: isDe ? "Prüfung erforderlich: Bitte Beleg kontrollieren" : "Review needed: Please inspect receipt",
      badgeLabel: isDe ? "Prüfung erforderlich" : "Pending Review",
    };
  }

  return {
    detail: isDe ? "Erfolgreich erfasst und mathematisch plausibel" : "Successfully parsed and math verified",
    badgeLabel: isDe ? "Erfasst" : "Scanned",
  };
}

export function StatusBadge({
  status,
  receipt,
  size = "md",
  showIcon = true,
  showDot = true,
  label,
  onClick,
  className = "",
  testId,
}: StatusBadgeProps) {
  const { language } = useI18n();
  const isDe = language === "de";

  const tier = resolveReceiptStatusTier(receipt ?? status);
  const meta = getStatusTierMeta(tier);
  const reviewInfo = receipt ? getReceiptReviewReason(receipt, isDe) : null;

  const defaultLabel = isDe ? meta.labelDe : meta.labelEn;

  const displayLabel =
    label ??
    (tier === "pending_review" && reviewInfo?.badgeLabel
      ? reviewInfo.badgeLabel
      : defaultLabel);

  const tooltipText =
    tier === "pending_review" && reviewInfo?.detail
      ? `${reviewInfo.detail} (${isDe ? "Klicken zum Öffnen" : "Click to open"})`
      : isDe
      ? meta.description
      : meta.descriptionEn || meta.description;

  const IconComponent = meta.icon;

  const sizeClasses = {
    sm: "px-1.5 py-0.5 text-[10px] gap-1",
    md: "px-2 py-0.5 text-[11px] gap-1.5",
    lg: "px-3 py-1 text-xs gap-2",
  }[size];

  const iconSizes = {
    sm: "w-2.5 h-2.5",
    md: "w-3 h-3",
    lg: "w-3.5 h-3.5",
  }[size];

  const dotSizes = {
    sm: "w-1.5 h-1.5",
    md: "w-2 h-2",
    lg: "w-2.5 h-2.5",
  }[size];

  const isInteractive = Boolean(onClick);

  return (
    <span
      data-testid={testId || `status-badge-${tier}`}
      data-status-tier={tier}
      onClick={onClick}
      role={isInteractive ? "button" : undefined}
      tabIndex={isInteractive ? 0 : undefined}
      title={tooltipText}
      className={`inline-flex items-center border font-mono font-medium tracking-tight rounded-none select-none transition-colors ${
        meta.bgColor
      } ${meta.textColor} ${meta.borderColor} ${sizeClasses} ${
        isInteractive ? "cursor-pointer hover:opacity-80 active:scale-95" : ""
      } ${className}`}
    >
      {showDot && (
        <span
          className={`shrink-0 rounded-full ${meta.dotColor} ${dotSizes} ${
            meta.pulseDot ? "animate-pulse" : ""
          }`}
          aria-hidden="true"
        />
      )}
      {showIcon && (
        <IconComponent className={`shrink-0 ${meta.iconColor} ${iconSizes}`} aria-hidden="true" />
      )}
      <span className="truncate">{displayLabel}</span>
    </span>
  );
}
