'use client';

import { useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useBookingStore } from '@/lib/booking-store';
import { usePaymentStore } from '@/lib/payment-store';
import { apiClient } from '@/lib/api-client';
import { CheckCircle, Loader2 } from 'lucide-react';
import { Suspense } from 'react';

function TelebirrSuccessContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { bookingId } = useBookingStore();
  const { updateStatus } = usePaymentStore();
  const [status, setStatus] = useState<'processing' | 'done' | 'error'>('processing');

  // Telebirr callback query params
  const orderid      = searchParams.get('orderid')      || '';
  const trxRef       = searchParams.get('trxRef')       || searchParams.get('outTradeNo') || '';
  const bookingIdQp  = searchParams.get('bookingId')    || bookingId || '';

  useEffect(() => {
    const confirm = async () => {
      try {
        if (bookingIdQp) {
          await apiClient.patch(`/bookings/${bookingIdQp}/confirm`, {
            paymentReference: orderid || trxRef,
            paymentMethod: 'TELEBIRR',
          });
        }

        updateStatus('SUCCEEDED');
        setStatus('done');
        setTimeout(() => router.push('/booking/confirmation'), 1500);
      } catch (err: any) {
        updateStatus('SUCCEEDED');
        setStatus('done');
        setTimeout(() => router.push('/booking/confirmation'), 1500);
      }
    };

    confirm();
  // 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">
        {status === 'processing' && (
          <>
            <Loader2 className="w-14 h-14 text-primary animate-spin mx-auto mb-4" />
            <h1 className="text-xl font-bold text-gray-900 dark:text-white mb-2">Confirming payment…</h1>
            <p className="text-sm text-gray-500 dark:text-gray-400">Please wait while we confirm your Telebirr payment.</p>
          </>
        )}
        {status === 'done' && (
          <>
            <CheckCircle className="w-14 h-14 text-green-500 mx-auto mb-4" />
            <h1 className="text-xl font-bold text-gray-900 dark:text-white mb-2">Payment Successful!</h1>
            <p className="text-sm text-gray-500 dark:text-gray-400 mb-1">Your Telebirr payment was received.</p>
            {orderid && <p className="text-xs text-gray-400">Order ID: {orderid}</p>}
            {trxRef && <p className="text-xs text-gray-400">Transaction Ref: {trxRef}</p>}
            <p className="text-xs text-gray-400 mt-3">Redirecting to your booking confirmation…</p>
          </>
        )}
        {status === 'error' && (
          <>
            <div className="w-14 h-14 rounded-full bg-red-100 flex items-center justify-center mx-auto mb-4">
              <span className="text-3xl">⚠️</span>
            </div>
            <h1 className="text-xl font-bold text-gray-900 dark:text-white mb-2">Something went wrong</h1>
            <p className="text-sm text-red-500 mb-4">Unable to confirm payment</p>
            <button onClick={() => router.push('/booking/confirmation')}
              className="btn-primary w-full">Go to confirmation</button>
          </>
        )}
      </div>
    </div>
  );
}

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