'use client';

import React, { Suspense } from 'react';
import { useParams } from 'next/navigation';
import { ItemsList } from '@/components/ItemsList';

// Loading component for better UX
function LoadingSpinner() {
  return (
    <div className="flex items-center justify-center min-h-[400px]">
      <div className="flex flex-col items-center space-y-4">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
        <span className="text-gray-600 text-sm">Loading items...</span>
      </div>
    </div>
  );
}

// Error boundary component
function ErrorFallback({ error, resetError }: { error: Error; resetError: () => void }) {
  return (
    <div className="flex flex-col items-center justify-center min-h-[400px] p-8">
      <div className="bg-red-50 border border-red-200 rounded-lg p-6 max-w-md w-full">
        <h2 className="text-red-800 text-lg font-semibold mb-2">
          Something went wrong
        </h2>
        <p className="text-red-600 text-sm mb-4">
          {error.message || 'An unexpected error occurred while loading the items.'}
        </p>
        <div className="flex space-x-3">
          <button
            onClick={resetError}
            className="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700 transition-colors text-sm"
          >
            Try again
          </button>
          <button
            onClick={() => window.location.reload()}
            className="bg-gray-600 text-white px-4 py-2 rounded hover:bg-gray-700 transition-colors text-sm"
          >
            Reload page
          </button>
        </div>
      </div>
    </div>
  );
}

// Simple error boundary implementation
class ErrorBoundary extends React.Component<
  { children: React.ReactNode; fallback: (error: Error, resetError: () => void) => React.ReactNode },
  { hasError: boolean; error?: Error }
> {
  constructor(props: { children: React.ReactNode; fallback: (error: Error, resetError: () => void) => React.ReactNode }) {
    super(props);
    this.state = { hasError: false };
  }

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

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error('Error caught by boundary:', error, errorInfo);
  }

  render() {
    if (this.state.hasError && this.state.error) {
      return this.props.fallback(this.state.error, () => {
        this.setState({ hasError: false, error: undefined });
      });
    }

    return this.props.children;
  }
}

export default function UrlPage() {
  const params = useParams();
  const encodedUrlParam = params.encodedUrl || '';
  
  // Handle both string and string[] cases
  const encodedUrl = Array.isArray(encodedUrlParam) ? encodedUrlParam[0] : encodedUrlParam;
  const decodedUrl = decodeURIComponent(encodedUrl);

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <div className="flex items-center">
              <h1 className="text-xl font-semibold text-gray-900">
                CompareWare
              </h1>
            </div>
            <div className="flex items-center space-x-4">
              <div className="text-sm text-gray-500">
                Item Comparison Tool
              </div>
            </div>
          </div>
        </div>
      </header>

      {/* Main content */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="mb-8">
          <h2 className="text-2xl font-bold text-gray-900 mb-2">
            {`Items Comparison for "${decodedUrl}"`}
          </h2>
        </div>

        {/* Items list with error boundary and suspense */}
        <ErrorBoundary fallback={(error, resetError) => <ErrorFallback error={error} resetError={resetError} />}>
          <Suspense fallback={<LoadingSpinner />}>
            <ItemsList url={decodedUrl} />
          </Suspense>
        </ErrorBoundary>
      </main>

      {/* Footer */}
      <footer className="bg-white border-t mt-16">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div className="text-center text-gray-500 text-sm">
            <p>&copy; 2025 CompareWare.</p>
          </div>
        </div>
      </footer>
    </div>
  );
}
