import React, { useState, useEffect, useRef } from 'react';
import { 
  useParams, 
  useNavigate, 
  Link 
} from 'react-router-dom';
import {
  ArrowLeft,
  Building2,
  Upload,
  CheckCircle,
  AlertCircle,
  Loader2,
  Copy,
  Check,
} from 'lucide-react';
import { toast } from 'react-toastify';
import {
  getBookingById,
  generateQRCode,
  type Booking,
} from '../../features/bookings/services/bookingService';
import { confirmBankTransfer } from '../../features/payments/services/paymentService';
import useAuthStore from '../../store/useAuthStore';
import { useAuthModal } from '../../features/auth/contexts/AuthModalContext';
import Loading from '../../shared/components/Loading';
import PaymentStatusBadge from '../../shared/components/PaymentStatusBadge';
import { useFormatCurrency } from '../../features/payments/hooks/useFormatCurrency';
import { validateBookingId } from '../../shared/utils/routeValidation';
import { validateAndHandleBookingOwnership } from '../../shared/utils/ownershipValidation';
import { PAYMENT_METHOD, PAYMENT_STATUS } from '../../shared/constants/bookingConstants';
import { useCompanySettings } from '../../shared/contexts/CompanySettingsContext';

const PaymentConfirmationPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { isAuthenticated, userInfo } = useAuthStore();
  const { openModal } = useAuthModal();
  const { formatCurrency } = useFormatCurrency();
  const { settings } = useCompanySettings();
  const abortControllerRef = useRef<AbortController | null>(null);

  const [booking, setBooking] = useState<Booking | null>(
    null
  );
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [uploading, setUploading] = useState(false);
  const [uploadSuccess, setUploadSuccess] = useState(false);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [copiedBookingNumber, setCopiedBookingNumber] = 
    useState(false);

  useEffect(() => {
    if (!isAuthenticated) {
      toast.error(
        'Please login to confirm payment'
      );
      openModal('login');
    }
  }, [isAuthenticated, openModal]);

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

  // Fetch data with ownership validation and request cancellation
  useEffect(() => {
    const validatedId = validateBookingId(id);
    if (!validatedId || !isAuthenticated) {
      return;
    }

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

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

    fetchBookingDetails(validatedId);

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

  /**
   * Fetches booking details with ownership validation and payment method checks
   * Only allows bank transfer payment confirmations on this page
   */
  const fetchBookingDetails = async (bookingId: number) => {
    try {
      setLoading(true);
      setError(null);

      const response = await getBookingById(bookingId);

      if (
        response.success && 
        response.data?.booking
      ) {
        const bookingData = response.data.booking;

        // Validate that the booking belongs to the current user
        if (!validateAndHandleBookingOwnership(bookingData, userInfo?.id, navigate)) {
          setLoading(false);
          return; // Ownership validation handles redirect and error message
        }
        
        // Prevent confirmation if booking is already paid
        if (bookingData.payment_status === PAYMENT_STATUS.PAID) {
          toast.info('This booking has already been paid');
          navigate(`/bookings/${bookingId}`);
          return;
        }
        
        // This page only handles bank transfer confirmations
        // Cash payments are handled on-site, not through this confirmation flow
        if (bookingData.payment_method === PAYMENT_METHOD.CASH) {
          toast.info(
            'This booking uses on-site payment method'
          );
          navigate(`/bookings/${bookingId}`);
          return;
        }
        
        setBooking(bookingData);
      } else {
        throw new Error(
          'Unable to load booking information'
        );
      }
    } catch (err: unknown) {
      const isAbortError = (e: unknown): boolean => {
        if (typeof e === 'object' && e !== null) {
          const error = e as { name?: string; code?: string };
          return error.name === 'AbortError' || error.code === 'ERR_CANCELED';
        }
        return false;
      };
      if (isAbortError(err)) {
        return;
      }
      
      const message =
        getUserFriendlyError(err) ||
        'Unable to load booking information';
      setError(message);
      toast.error(message);
    } finally {
      setLoading(false);
    }
  };

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

  const copyBookingNumber = async () => {
    if (!booking?.booking_number) return;

    try {
      await navigator.clipboard.writeText(
        booking.booking_number
      );
      setCopiedBookingNumber(true);
      toast.success('Booking number copied');
      setTimeout(() => setCopiedBookingNumber(false), 2000);
    } catch (err) {
      toast.error('Unable to copy');
    }
  };

  /**
   * Handles payment confirmation by uploading receipt and notifying the system
   * Creates a unique transaction ID and sends the receipt for manual verification
   */
  const handleConfirmPayment = async () => {
    if (!selectedFile || !booking) return;

    try {
      setUploading(true);

      // Generate unique transaction ID for tracking
      const transactionId = 
        `TXN-${booking.booking_number}-${Date.now()}`;

      const response = await confirmBankTransfer(
        booking.id,
        transactionId,
        selectedFile
      );

      if (response.success) {
        toast.success(
          '✅ Payment confirmation sent successfully!'
        );
        setUploadSuccess(true);
        
        // Redirect to booking details after showing success message
        setTimeout(() => {
          navigate(`/bookings/${booking.id}`);
        }, 2000);
      } else {
        throw new Error(
          response.message || 
          'Unable to confirm payment'
        );
      }
    } catch (err: unknown) {
      const message =
        getUserFriendlyError(err) ||
        'Unable to send payment confirmation';
      toast.error(message);
    } finally {
      setUploading(false);
    }
  };

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

  if (error || !booking) {
    return (
      <div className="min-h-screen bg-gray-50 py-8">
        <div className="max-w-4xl mx-auto px-4">
          <div
            className="bg-red-50 border border-red-200 
              rounded-lg p-8 text-center"
          >
            <AlertCircle
              className="w-12 h-12 text-red-500 
                mx-auto mb-3"
            />
            <p className="text-red-700 font-medium mb-4">
              {error || 'Booking not found'}
            </p>
            <button
              onClick={() => navigate('/bookings')}
              className="px-6 py-2 bg-red-600 
                text-white rounded-lg 
                hover:bg-red-700 transition-colors"
            >
              Back to list
            </button>
          </div>
        </div>
      </div>
    );
  }

  const qrCodeUrl = generateQRCode(
    booking.booking_number,
    booking.total_price,
    settings.bank_code || undefined,
    settings.bank_account_number || undefined,
    settings.bank_account_holder || undefined
  );

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-4xl mx-auto px-4">
        {}
        <Link
          to={`/bookings/${booking.id}`}
          className="inline-flex items-center gap-2 
            text-gray-600 hover:text-gray-900 
            mb-6 transition-colors"
        >
          <ArrowLeft className="w-5 h-5" />
          <span>Back to booking details</span>
        </Link>

        {}
        <div className="mb-6">
          <h1 className="text-3xl font-bold text-gray-900 
            mb-2"
          >
            Payment Confirmation
          </h1>
          <p className="text-gray-600">
            Complete payment for your booking
          </p>
        </div>

        {}
        <div className="bg-white rounded-lg shadow-md 
          p-6 mb-6"
        >
          <div className="flex items-start justify-between 
            gap-4 mb-4"
          >
            <div>
              <p className="text-sm text-gray-600 mb-1">
                Booking Number
              </p>
              <div className="flex items-center gap-2">
                <span className="text-xl font-bold 
                  text-indigo-900 font-mono"
                >
                  {booking.booking_number}
                </span>
                <button
                  onClick={copyBookingNumber}
                  className="p-1 hover:bg-gray-100 
                    rounded transition-colors"
                  title="Copy"
                >
                  {copiedBookingNumber ? (
                    <Check className="w-4 h-4 
                      text-green-600" 
                    />
                  ) : (
                    <Copy className="w-4 h-4 
                      text-gray-400" 
                    />
                  )}
                </button>
              </div>
            </div>

            <PaymentStatusBadge
              status={booking.payment_status}
              size="md"
            />
          </div>

          <div className="border-t pt-4">
            <div className="flex justify-between 
              items-center"
            >
              <span className="text-gray-600">
                Total Payment
              </span>
              <span className="text-2xl font-bold 
                text-indigo-600"
              >
                {formatPrice(booking.total_price)}
              </span>
            </div>
          </div>
        </div>

        {!uploadSuccess ? (
          <>
            {}
            <div
              className="bg-blue-50 border border-blue-200 
                rounded-lg p-6 mb-6"
            >
              <div className="flex items-start gap-3 mb-4">
                <Building2
                  className="w-6 h-6 text-blue-600 
                    mt-1 flex-shrink-0"
                />
                <div className="flex-1">
                  <h3 className="font-bold text-blue-900 
                    mb-3"
                  >
                    Bank Transfer Information
                  </h3>

                  <div className="grid grid-cols-1 
                    md:grid-cols-2 gap-4"
                  >
                    {}
                    <div className="bg-white rounded-lg 
                      p-4 space-y-2 text-sm"
                    >
                      <p>
                        <strong>Bank:</strong> 
                        {settings.bank_name || 'Not configured'}
                      </p>
                      <p>
                        <strong>Account Number:</strong> 
                        {settings.bank_account_number || 'Not configured'}
                      </p>
                      <p>
                        <strong>Account Holder:</strong> 
                        {settings.bank_account_holder || 'Not configured'}
                      </p>
                      <p>
                        <strong>Amount:</strong>{' '}
                        <span className="text-indigo-600 
                          font-bold"
                        >
                          {formatPrice(booking.total_price)}
                        </span>
                      </p>
                      <p>
                        <strong>Content:</strong>{' '}
                        <span className="font-mono 
                          text-indigo-600"
                        >
                          {booking.booking_number}
                        </span>
                      </p>
                    </div>

                    {}
                    <div className="bg-white rounded-lg 
                      p-4 flex flex-col items-center"
                    >
                      <p className="text-sm font-medium 
                        text-gray-700 mb-2"
                      >
                        Scan QR code to transfer
                      </p>
                      {qrCodeUrl ? (
                        <img
                          src={qrCodeUrl}
                          alt="QR Code"
                          className="w-48 h-48 border-2 
                            border-gray-200 rounded-lg"
                        />
                      ) : (
                        <p className="text-sm text-gray-500 text-center">
                          Bank details not configured. Please contact support.
                        </p>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {}
            <div className="bg-white rounded-lg shadow-md 
              p-6 mb-6"
            >
              <h3 className="text-xl font-bold 
                text-gray-900 mb-4"
              >
                <Upload className="w-5 h-5 inline mr-2" />
                Upload Payment Receipt
              </h3>

              <p className="text-gray-600 mb-4">
                After transferring, please upload a receipt image 
                so we can confirm faster.
              </p>

              <div className="space-y-4">
                {}
                <label
                  htmlFor="receipt-upload"
                  className="block w-full px-4 py-6 
                    border-2 border-dashed 
                    border-gray-300 rounded-lg 
                    text-center cursor-pointer 
                    hover:border-indigo-400 
                    hover:bg-indigo-50 
                    transition-all"
                >
                  <input
                    id="receipt-upload"
                    type="file"
                    accept="image/*"
                    onChange={(e) => {
                      const file = e.target.files?.[0];
                      if (file) {
                        setSelectedFile(file);
                      }
                    }}
                    className="hidden"
                  />
                  <span className="text-sm text-gray-600">
                    {selectedFile ? selectedFile.name : 'Click to upload receipt'}
                  </span>
                </label>
                {selectedFile && (
                  <button
                    onClick={handleConfirmPayment}
                    disabled={uploading}
                    className="w-full px-6 py-4 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors font-semibold text-lg disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                  >
                    {uploading ? (
                      <>
                        <Loader2 
                          className="w-5 h-5 animate-spin" 
                        />
                        Processing...
                      </>
                    ) : (
                      <>
                        <CheckCircle className="w-5 h-5" />
                        Confirm Payment
                      </>
                    )}
                  </button>
                )}
              </div>
            </div>
          </>
        ) : (
          <div className="bg-green-50 border 
            border-green-200 rounded-lg p-8 
            text-center"
          >
            <CheckCircle 
              className="w-16 h-16 text-green-600 
                mx-auto mb-4" 
            />
            <h3 className="text-2xl font-bold 
              text-green-900 mb-2"
            >
              Confirmation sent successfully!
            </h3>
            <p className="text-green-700 mb-4">
              We will confirm your payment as soon as possible.
            </p>
            <p className="text-sm text-green-600">
              Redirecting...
            </p>
          </div>
        )}
      </div>
    </div>
  );
};

export default PaymentConfirmationPage;
