import React, { useState, useEffect, useRef } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import {
  CheckCircle,
  AlertCircle,
  CreditCard,
  ArrowLeft,
  Shield,
  Lock,
} from 'lucide-react';
import { toast } from 'react-toastify';
import { getBookingById, type Booking } from '../../features/bookings/services/bookingService';
import {
  getPaymentsByBookingId,
  type Payment,
} from '../../features/payments/services/paymentService';
import Loading from '../../shared/components/Loading';
import { useFormatCurrency } from '../../features/payments/hooks/useFormatCurrency';
import { parseDateLocal } from '../../shared/utils/format';
import StripePaymentWrapper from '../../features/payments/components/StripePaymentWrapper';
import useAuthStore from '../../store/useAuthStore';
import { validateBookingId } from '../../shared/utils/routeValidation';
import { validateAndHandleBookingOwnership } from '../../shared/utils/ownershipValidation';
import { BOOKING_STATUS, PAYMENT_METHOD } from '../../shared/constants/bookingConstants';
import { logSecurityWarning } from '../../shared/utils/errorReporter';

const FullPaymentPage: React.FC = () => {
  const { bookingId } = useParams<{ bookingId: string }>();
  const navigate = useNavigate();
  const { formatCurrency } = useFormatCurrency();
  const { userInfo } = useAuthStore();
  const abortControllerRef = useRef<AbortController | null>(null);

  const [booking, setBooking] = useState<Booking | null>(null);
  const [stripePayment, setStripePayment] = useState<Payment | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [paymentSuccess, setPaymentSuccess] = useState(false);

  // SECURITY: Payment page security - prevent caching and verify HTTPS
  useEffect(() => {
    // Set no-cache headers via meta tags (server should also set HTTP headers)
    const metaTags = [
      { httpEquiv: 'Cache-Control', content: 'no-cache, no-store, must-revalidate' },
      { httpEquiv: 'Pragma', content: 'no-cache' },
      { httpEquiv: 'Expires', content: '0' },
    ];
    
    metaTags.forEach(tag => {
      let meta = document.querySelector(`meta[http-equiv="${tag.httpEquiv}"]`);
      if (!meta) {
        meta = document.createElement('meta');
        meta.setAttribute('http-equiv', tag.httpEquiv);
        document.head.appendChild(meta);
      }
      meta.setAttribute('content', tag.content);
    });
    
    // Verify HTTPS in production
    if (import.meta.env.PROD && window.location.protocol !== 'https:') {
      logSecurityWarning('Payment page should use HTTPS in production!', {
        protocol: window.location.protocol,
        url: window.location.href,
      });
    }
  }, []);

  // Validate route parameter
  useEffect(() => {
    const validatedId = validateBookingId(bookingId);
    if (!validatedId) {
      setError('Invalid booking ID');
      setLoading(false);
      toast.error('Invalid booking ID');
      navigate('/bookings');
      return;
    }
  }, [bookingId, navigate]);

  // Fetch data with ownership validation
  useEffect(() => {
    const validatedId = validateBookingId(bookingId);
    if (!validatedId) {
      return;
    }

    // Cancel previous request if exists
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }

    // Create new abort controller
    abortControllerRef.current = new AbortController();

    fetchData(validatedId);

    // Cleanup: abort request on unmount
    return () => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [bookingId]);

  const fetchData = async (id: number) => {
    try {
      setLoading(true);
      setError(null);

      const bookingResponse = await getBookingById(id);
      if (!bookingResponse.success || !bookingResponse.data?.booking) {
        throw new Error('Booking not found');
      }

      const bookingData = bookingResponse.data.booking;

      // Validate ownership
      if (!validateAndHandleBookingOwnership(bookingData, userInfo?.id, navigate)) {
        setLoading(false);
        return;
      }

      setBooking(bookingData);

      // Check if already confirmed
      if (bookingData.status === BOOKING_STATUS.CONFIRMED || bookingData.status === BOOKING_STATUS.CHECKED_IN) {
        toast.success('Booking is already confirmed!');
        navigate(`/bookings/${id}`);
        return;
      }

      // Check payment method
      if (bookingData.payment_method !== PAYMENT_METHOD.STRIPE) {
        toast.info('This booking does not use Stripe payment');
        navigate(`/bookings/${id}`);
        return;
      }

      // Fetch payments
      const paymentsResponse = await getPaymentsByBookingId(id);
      
      if (paymentsResponse.success && paymentsResponse.data?.payments) {
        const payments = paymentsResponse.data.payments;
        
        // Find pending Stripe payment
        const stripePaymentFound = payments.find(
          (p: Payment) => 
            (p.payment_method === PAYMENT_METHOD.STRIPE || p.payment_method === PAYMENT_METHOD.CREDIT_CARD) && 
            p.payment_status === 'pending'
        );
        
        if (stripePaymentFound) {
          setStripePayment(stripePaymentFound);
        } else {
          // Check for completed payment
          const completedPayment = payments.find(
            (p: Payment) => 
              (p.payment_method === PAYMENT_METHOD.STRIPE || p.payment_method === PAYMENT_METHOD.CREDIT_CARD) && 
              p.payment_status === 'completed'
          );
          
          if (completedPayment) {
            setStripePayment(completedPayment);
            setPaymentSuccess(true);
            
            // Check if booking is already confirmed or checked in
            const bookingStatus = bookingData.status as string;
            if (bookingStatus === BOOKING_STATUS.CONFIRMED || bookingStatus === BOOKING_STATUS.CHECKED_IN) {
              toast.info('Payment already completed. Booking is confirmed.');
              setTimeout(() => {
                navigate(`/bookings/${id}`);
              }, 1500);
              return;
            }
          } else {
            throw new Error('No Stripe payment record found for this booking. The payment may not have been created properly.');
          }
        }
      } else {
        // Fallback to payments from booking data
        if (bookingData.payments && bookingData.payments.length > 0) {
          const stripePaymentFromBooking = bookingData.payments.find(
            (p: Payment) => 
              (p.payment_method === PAYMENT_METHOD.STRIPE || p.payment_method === PAYMENT_METHOD.CREDIT_CARD) && 
              p.payment_status === 'pending'
          );
          
          if (stripePaymentFromBooking) {
            setStripePayment(stripePaymentFromBooking as unknown as Payment);
          } else {
            throw new Error('No pending Stripe payment found for this booking');
          }
        } else {
          throw new Error('Payment information not found. Please wait a moment and refresh, or contact support if the issue persists.');
        }
      }
    } catch (err: unknown) {
      // Don't show error if request was aborted
      if (err && typeof err === 'object' && 'name' in err && err.name === 'AbortError') {
        return;
      }

      const message =
        (err && typeof err === 'object' && 'response' in err && err.response && typeof err.response === 'object' && 'data' in err.response && err.response.data && typeof err.response.data === 'object' && 'message' in err.response.data && typeof err.response.data.message === 'string' ? err.response.data.message : undefined) || (err instanceof Error ? err.message : undefined) || 'Unable to load payment information';
      setError(message);
      toast.error(message);
    } finally {
      setLoading(false);
    }
  };

  const formatPrice = (price: number) => formatCurrency(price);

  if (loading) {
    return <Loading fullScreen text="Loading..." />;
  }

  if (error || !booking || !stripePayment) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-[#0f0f0f] via-[#1a1a1a] to-[#0f0f0f] py-8">
        <div className="max-w-4xl mx-auto px-4">
          <div
            className="bg-gradient-to-br from-red-900/20 to-red-800/10 
              border border-red-500/30 rounded-xl p-8 text-center 
              backdrop-blur-xl shadow-2xl shadow-red-500/10"
          >
            <AlertCircle className="w-12 h-12 text-red-400 mx-auto mb-4" />
            <p className="text-red-300 font-medium mb-6 tracking-wide">
              {error || 'Payment information not found'}
            </p>
            <Link
              to="/bookings"
              className="inline-flex items-center gap-2 
                bg-gradient-to-r from-[var(--luxury-gold)] to-[var(--luxury-gold-dark)] 
                text-[#0f0f0f] px-6 py-3 rounded-sm 
                hover:from-[var(--luxury-gold-light)] hover:to-[var(--luxury-gold)] 
                transition-all duration-300 font-medium 
                tracking-wide shadow-lg shadow-[var(--luxury-gold)]/30"
            >
              <ArrowLeft className="w-4 h-4" />
              Back to booking list
            </Link>
          </div>
        </div>
      </div>
    );
  }

  let paymentAmount = parseFloat(stripePayment.amount.toString());
  const isPaymentCompleted = stripePayment.payment_status === 'completed';
  
  // Validate and correct payment amount if needed
  if (paymentAmount > 999999.99 || (booking && Math.abs(paymentAmount - booking.total_price) > 0.01)) {
    if (booking) {
      paymentAmount = parseFloat(booking.total_price.toString());
    }
  }
  
  // Check Stripe maximum
  if (paymentAmount > 999999.99) {
    const errorMsg = `Payment amount exceeds Stripe's maximum. Please contact support.`;
    setError(errorMsg);
    return null;
  }

  return (
    <div className="min-h-screen bg-gradient-to-b from-[#0f0f0f] via-[#1a1a1a] to-[#0f0f0f] py-8">
      <div className="max-w-4xl mx-auto px-4">
        {}
        <Link
          to={`/bookings/${bookingId}`}
          className="inline-flex items-center gap-2 
            text-[var(--luxury-gold)]/80 hover:text-[var(--luxury-gold)] 
            mb-6 transition-all duration-300 
            group font-light tracking-wide"
        >
          <ArrowLeft className="w-5 h-5 group-hover:-translate-x-1 transition-transform" />
          <span>Back to booking details</span>
        </Link>

        {}
        {isPaymentCompleted && (
          <div
            className="bg-gradient-to-br from-green-900/20 to-green-800/10 
              border-2 border-green-500/30 rounded-xl p-6 mb-6 
              backdrop-blur-xl shadow-2xl shadow-green-500/10"
          >
            <div className="flex items-center gap-4">
              <div
                className="w-16 h-16 bg-green-500/20 rounded-full 
                  flex items-center justify-center border border-green-500/30"
              >
                <CheckCircle className="w-10 h-10 text-green-400" />
              </div>
              <div className="flex-1">
                <h1 className="text-2xl font-serif font-bold text-green-300 mb-1 tracking-wide">
                  Payment successful!
                </h1>
                <p className="text-green-400/80 font-light tracking-wide">
                  Your booking has been confirmed.
                </p>
              </div>
            </div>
          </div>
        )}

        {}
        {!isPaymentCompleted && (
          <div
            className="bg-gradient-to-br from-[var(--luxury-gold)]/10 to-[var(--luxury-gold-dark)]/5 
              border-2 border-[var(--luxury-gold)]/30 rounded-xl p-6 mb-6 
              backdrop-blur-xl shadow-2xl shadow-[var(--luxury-gold)]/10"
          >
            <div className="flex items-center gap-4">
              <div
                className="w-16 h-16 bg-[var(--luxury-gold)]/20 rounded-full 
                  flex items-center justify-center border border-[var(--luxury-gold)]/30"
              >
                <CreditCard className="w-10 h-10 text-[var(--luxury-gold)]" />
              </div>
              <div className="flex-1">
                <h1 className="text-2xl font-serif font-bold text-[var(--luxury-gold)] mb-1 tracking-wide">
                  Complete Payment
                </h1>
                <p className="text-gray-300 font-light tracking-wide">
                  Please complete your payment to confirm your booking
                </p>
              </div>
            </div>
          </div>
        )}

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {}
          <div className="lg:col-span-2 space-y-6">
            {}
            <div 
              className="bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] 
                rounded-xl border border-[var(--luxury-gold)]/20 
                backdrop-blur-xl shadow-2xl shadow-[var(--luxury-gold)]/5 p-6"
            >
              <h2 className="text-xl font-serif font-semibold text-[var(--luxury-gold)] mb-4 flex items-center gap-2">
                <div className="w-1 h-6 bg-gradient-to-b from-[var(--luxury-gold)] to-[var(--luxury-gold-dark)]" />
                Payment Information
              </h2>

              <div className="space-y-3">
                <div className="flex justify-between">
                  <span className="text-gray-400 font-light">Total Room Price</span>
                  <span className="font-medium text-white">
                    {formatPrice(booking.total_price)}
                  </span>
                </div>

                <div
                  className="flex justify-between border-t border-[var(--luxury-gold)]/20 pt-3 
                    text-[var(--luxury-gold)]"
                >
                  <span className="font-medium">
                    Amount to Pay
                  </span>
                  <span className="text-xl font-bold">
                    {formatPrice(paymentAmount)}
                  </span>
                </div>
              </div>

              {isPaymentCompleted && (
                <div className="mt-4 bg-green-500/10 border border-green-500/30 rounded-lg p-3">
                  <p className="text-sm text-green-400 font-light">
                    ✓ Payment completed on:{' '}
                    {stripePayment.payment_date
                      ? new Date(stripePayment.payment_date).toLocaleString('en-US')
                      : 'N/A'}
                  </p>
                  {stripePayment.transaction_id && (
                    <p className="text-xs text-green-400/70 mt-1 font-light">
                      Transaction ID: {stripePayment.transaction_id}
                    </p>
                  )}
                </div>
              )}
            </div>

            {}
            {!isPaymentCompleted && booking && stripePayment && (
              <div 
                className="bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] 
                  rounded-xl border border-[var(--luxury-gold)]/20 
                  backdrop-blur-xl shadow-2xl shadow-[var(--luxury-gold)]/5 p-6"
              >
                <h2 className="text-xl font-serif font-semibold text-[var(--luxury-gold)] mb-4 flex items-center gap-2">
                  <div className="w-1 h-6 bg-gradient-to-b from-[var(--luxury-gold)] to-[var(--luxury-gold-dark)]" />
                  <CreditCard className="w-5 h-5" />
                  Card Payment
                </h2>

                {paymentSuccess ? (
                  <div className="bg-green-500/10 border border-green-500/30 rounded-lg p-6 text-center">
                    <CheckCircle className="w-12 h-12 text-green-400 mx-auto mb-3" />
                    <h3 className="text-lg font-serif font-bold text-green-300 mb-2 tracking-wide">
                      Payment Successful!
                    </h3>
                    <p className="text-green-400/80 font-light mb-4 tracking-wide">
                      Your payment has been confirmed.
                    </p>
                    <button
                      onClick={() => navigate(`/bookings/${booking.id}`)}
                      className="bg-gradient-to-r from-[var(--luxury-gold)] to-[var(--luxury-gold-dark)] 
                        text-[#0f0f0f] px-6 py-3 rounded-sm 
                        hover:from-[var(--luxury-gold-light)] hover:to-[var(--luxury-gold)] 
                        transition-all duration-300 font-medium 
                        tracking-wide shadow-lg shadow-[var(--luxury-gold)]/30"
                    >
                      View Booking
                    </button>
                  </div>
                ) : (
                  <StripePaymentWrapper
                    bookingId={booking.id}
                    amount={paymentAmount}
                    onSuccess={() => {
                      setPaymentSuccess(true);
                      toast.success('✅ Payment successful! Your booking has been confirmed.');
                      
                      setTimeout(() => {
                        navigate(`/bookings/${booking.id}`);
                      }, 2000);
                    }}
                    onError={(error) => {
                      toast.error(error || 'Payment failed');
                    }}
                  />
                )}
              </div>
            )}
          </div>

          {}
          <div className="lg:col-span-1">
            <div 
              className="bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] 
                rounded-xl border border-[var(--luxury-gold)]/20 
                backdrop-blur-xl shadow-2xl shadow-[var(--luxury-gold)]/5 p-6 
                sticky top-6"
            >
              <h3 className="text-lg font-serif font-semibold text-[var(--luxury-gold)] mb-4 flex items-center gap-2">
                <div className="w-1 h-5 bg-gradient-to-b from-[var(--luxury-gold)] to-[var(--luxury-gold-dark)]" />
                Booking Summary
              </h3>

              <div className="space-y-3 text-sm">
                <div>
                  <span className="text-gray-400 font-light">Booking Number</span>
                  <p className="text-white font-medium">{booking.booking_number}</p>
                </div>
                
                <div>
                  <span className="text-gray-400 font-light">Room</span>
                  <p className="text-white font-medium">
                    {booking.room?.room_number || 'N/A'}
                  </p>
                </div>
                
                <div>
                  <span className="text-gray-400 font-light">Check-in</span>
                  <p className="text-white font-medium">
                    {parseDateLocal(booking.check_in_date).toLocaleDateString('en-US')}
                  </p>
                </div>
                
                <div>
                  <span className="text-gray-400 font-light">Check-out</span>
                  <p className="text-white font-medium">
                    {parseDateLocal(booking.check_out_date).toLocaleDateString('en-US')}
                  </p>
                </div>
                
                <div className="pt-3 border-t border-[var(--luxury-gold)]/20">
                  <span className="text-gray-400 font-light">Total Amount</span>
                  <p className="text-xl font-bold text-[var(--luxury-gold)]">
                    {formatPrice(booking.total_price)}
                  </p>
                </div>
              </div>

              {/* PCI DSS Compliance Trust Badge */}
              {!isPaymentCompleted && (
                <div className="mt-6 pt-6 border-t border-[var(--luxury-gold)]/20">
                  <div className="bg-gradient-to-r from-blue-900/20 to-indigo-900/20 border border-blue-500/30 rounded-lg p-4">
                    <div className="flex items-start gap-3">
                      <div className="flex-shrink-0">
                        <div className="w-10 h-10 bg-gradient-to-br from-blue-500/20 to-indigo-500/20 rounded-full flex items-center justify-center border border-blue-500/30">
                          <Shield className="w-5 h-5 text-blue-400" />
                        </div>
                      </div>
                      <div className="flex-1 min-w-0">
                        <h4 className="text-sm font-semibold text-blue-300 mb-1 flex items-center gap-2">
                          <Lock className="w-4 h-4" />
                          Secure Payment Processing
                        </h4>
                        <p className="text-xs text-blue-400/80 font-light leading-relaxed mb-2">
                          Your payment is processed securely through Stripe, a PCI DSS Level 1 compliant payment processor. Your card details are encrypted and never stored on our servers.
                        </p>
                        <div className="flex flex-wrap items-center gap-2 mt-2">
                          <span className="text-xs px-2 py-1 bg-blue-500/20 border border-blue-500/30 rounded text-blue-300 font-light">
                            PCI DSS Compliant
                          </span>
                          <span className="text-xs px-2 py-1 bg-green-500/20 border border-green-500/30 rounded text-green-300 font-light">
                            SSL Encrypted
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default FullPaymentPage;

