'use client';

import { useSearchParams, useRouter } from 'next/navigation';
import { usePaymentStore } from '@/lib/payment-store';
import { useEffect, Suspense } from 'react';
import { XCircle, Loader2, RefreshCw } from 'lucide-react';

function TelebirrFailureContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { updateStatus } = usePaymentStore();

  const merchantOrderId = searchParams.get('merchantOrderId') || '';
  const trxRef     = searchParams.get('trxRef')     || searchParams.get('outTradeNo') || '';
  const resultCode = searchParams.get('resultCode') || searchParams.get('code')       || '';
  const resultMsg  = searchParams.get('resultMsg')  || searchParams.get('message')    || 'Payment was not completed.';

  useEffect(() => {
    updateStatus('FAILED');
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center px-4">
      <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-8 max-w-md w-full text-center">
        <XCircle className="w-14 h-14 text-red-500 mx-auto mb-4" />
        <h1 className="text-xl font-bold text-gray-900 dark:text-white mb-2">Payment Failed</h1>
        <p className="text-sm text-gray-500 dark:text-gray-400 mb-1">{resultMsg}</p>
        {resultCode && <p className="text-xs text-gray-400 mb-1">Code: {resultCode}</p>}
        {merchantOrderId && <p className="text-xs text-gray-400 mb-1">Order ID: {merchantOrderId}</p>}
        {trxRef && <p className="text-xs text-gray-400 mb-4">Ref: {trxRef}</p>}
        <div className="flex flex-col gap-3 mt-4">
          <button onClick={() => router.push('/booking/payment')}
            className="btn-primary w-full flex items-center justify-center gap-2">
            <RefreshCw className="w-4 h-4" />
            Try Again
          </button>
          <button onClick={() => router.push('/booking/review')}
            className="btn-secondary w-full">
            Back to Review
          </button>
        </div>
      </div>
    </div>
  );
}

export default function TelebirrFailurePage() {
  return (
    <Suspense fallback={<div className="min-h-screen flex items-center justify-center"><Loader2 className="w-10 h-10 animate-spin text-primary" /></div>}>
      <TelebirrFailureContent />
    </Suspense>
  );
}
