"use client";

import { type Lang } from "@/lib/config";
import Link from "next/link";
import { CheckoutErrorCode } from "@/lib/errors/checkout-errors";

interface CheckoutErrorResponse {
  error: string;
  errorAr?: string;
  code?: CheckoutErrorCode;
  retryable?: boolean;
  recoverySteps?: string[];
  recoveryStepsAr?: string[];
  details?: string | string[];
}

interface CheckoutErrorDisplayProps {
  error: CheckoutErrorResponse | string;
  lang: Lang;
  onRetry?: () => void;
  onBack?: () => void;
  className?: string;
}

/**
 * Checkout Error Display Component
 *
 * Displays user-friendly error messages with recovery guidance
 * Supports both English and Arabic with RTL
 */
export default function CheckoutErrorDisplay({
  error,
  lang,
  onRetry,
  onBack,
  className = "",
}: CheckoutErrorDisplayProps) {
  const isAr = lang === "ar";

  // Parse error
  const errorData: CheckoutErrorResponse =
    typeof error === "string"
      ? {
          error,
          retryable: false,
        }
      : error;

  const {
    error: errorMessage,
    errorAr,
    code,
    retryable = false,
    recoverySteps = [],
    recoveryStepsAr = [],
    details,
  } = errorData;

  // Get localized error message
  const displayMessage = isAr && errorAr ? errorAr : errorMessage;

  // Get localized recovery steps with fallback to English if Arabic is empty
  const displaySteps =
    isAr && recoveryStepsAr.length > 0 ? recoveryStepsAr : recoverySteps;

  // Determine error severity
  const isRetryable = retryable;
  const isCritical = code
    ? [
        CheckoutErrorCode.USER_NOT_FOUND,
        CheckoutErrorCode.MISSING_USER_ID,
        CheckoutErrorCode.MISSING_EMAIL,
      ].includes(code)
    : false;

  // Get appropriate icon and color
  const getErrorStyle = () => {
    if (isCritical) {
      return {
        borderColor: "border-red-300",
        bgColor: "bg-red-50",
        iconColor: "text-red-600",
        textColor: "text-red-800",
        icon: "⚠️",
      };
    }
    if (isRetryable) {
      return {
        borderColor: "border-yellow-300",
        bgColor: "bg-yellow-50",
        iconColor: "text-yellow-600",
        textColor: "text-yellow-800",
        icon: "ℹ️",
      };
    }
    return {
      borderColor: "border-orange-300",
      bgColor: "bg-orange-50",
      iconColor: "text-orange-600",
      textColor: "text-orange-800",
      icon: "⚠️",
    };
  };

  const style = getErrorStyle();

  return (
    <div
      className={`rounded-lg border-2 ${style.borderColor} ${style.bgColor} p-6 ${className}`}
      role="alert"
      aria-live="assertive"
    >
      {/* Error Header */}
      <div className="mb-4 flex items-start gap-3">
        <span className="text-2xl" aria-hidden="true">
          {style.icon}
        </span>
        <div className="flex-1">
          <h3 className={`mb-1 text-lg font-semibold ${style.textColor}`}>
            {isAr ? "حدث خطأ" : "Error Occurred"}
          </h3>
          <p className={`text-sm ${style.textColor}`}>{displayMessage}</p>
          {details && (
            <details className="mt-2">
              <summary
                className={`cursor-pointer text-xs ${style.textColor} opacity-75`}
              >
                {isAr ? "التفاصيل التقنية" : "Technical Details"}
              </summary>
              <pre className="mt-2 overflow-x-auto rounded bg-white/50 p-2 text-xs">
                {typeof details === "string"
                  ? details
                  : JSON.stringify(details, null, 2)}
              </pre>
            </details>
          )}
        </div>
      </div>

      {/* Recovery Steps */}
      {displaySteps.length > 0 && (
        <div className="mb-4">
          <h4 className={`mb-2 text-sm font-semibold ${style.textColor}`}>
            {isAr ? "خطوات الحل:" : "How to resolve:"}
          </h4>
          <ol
            className={`space-y-1 text-sm ${style.textColor} ${isAr ? "pr-5" : "pl-5"}`}
          >
            {displaySteps.map((step, index) => (
              <li key={index} className="list-decimal">
                {step}
              </li>
            ))}
          </ol>
        </div>
      )}

      {/* Action Buttons */}
      <div className="flex gap-3">
        {isRetryable && onRetry && (
          <button
            onClick={onRetry}
            className="flex-1 rounded-lg bg-brand-green px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-brand-green/90"
            type="button"
          >
            {isAr ? "حاول مرة أخرى" : "Try Again"}
          </button>
        )}

        {onBack && (
          <button
            onClick={onBack}
            className="flex-1 rounded-lg border-2 border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:border-brand-green hover:text-brand-green"
            type="button"
          >
            {isAr ? "رجوع" : "Go Back"}
          </button>
        )}

        {isCritical && (
          <Link
            href={`/${lang}/signup`}
            className="flex-1 rounded-lg border-2 border-brand-green bg-brand-green px-4 py-2 text-center text-sm font-medium text-white transition-colors hover:bg-brand-green/90"
          >
            {isAr ? "ابدأ من جديد" : "Start Over"}
          </Link>
        )}

        {/* Support Link */}
        <Link
          href={`/${lang}/support`}
          className="rounded-lg border-2 border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:border-brand-green hover:text-brand-green"
        >
          {isAr ? "اتصل بالدعم" : "Contact Support"}
        </Link>
      </div>

      {/* Error Code (for debugging) */}
      {code && (
        <p className="mt-4 text-xs text-gray-500">
          {isAr ? "رمز الخطأ:" : "Error Code:"}{" "}
          <code className="font-mono">{code}</code>
        </p>
      )}
    </div>
  );
}
