"use client";

import { Component, type ReactNode } from "react";
import Link from "next/link";
import { Button } from "@/components/atoms/button";
import { ExclamationTriangleIcon } from "@heroicons/react/24/outline";
import { logger } from "@/core/logger";

interface Props {
  children: ReactNode;
}

interface State {
  hasError: boolean;
  error: Error | null;
}

/**
 * CheckoutErrorBoundary - Error boundary for checkout flow
 *
 * Catches errors during checkout and provides recovery options.
 */
export class CheckoutErrorBoundary extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error: Error): State {
    return { hasError: true, error };
  }

  override componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    logger.error("Checkout error", { error, componentStack: errorInfo.componentStack });
  }

  override render() {
    if (this.state.hasError) {
      return (
        <div className="max-w-md mx-auto text-center py-16">
          <div className="bg-card rounded-2xl border border-border p-8 shadow-[var(--cp-shadow-1)]">
            <div className="w-16 h-16 bg-destructive/10 rounded-full flex items-center justify-center mx-auto mb-6">
              <ExclamationTriangleIcon className="h-8 w-8 text-destructive" />
            </div>
            <h2 className="text-xl font-semibold text-foreground mb-2">Something went wrong</h2>
            <p className="text-muted-foreground mb-6">
              We encountered an error during checkout. Your cart has been saved.
            </p>
            <div className="flex gap-4 justify-center">
              <Button
                onClick={() => this.setState({ hasError: false, error: null })}
                variant="outline"
              >
                Try Again
              </Button>
              <Button as="a" href="/services">
                Return to Services
              </Button>
            </div>
            <p className="text-xs text-muted-foreground mt-6">
              If this problem persists, please{" "}
              <Link href="/contact" className="text-primary hover:underline">
                contact support
              </Link>
              .
            </p>
          </div>
        </div>
      );
    }

    return this.props.children;
  }
}
