'use client';

import { useEffect, useState } from 'react';
import Button from '@/components/ui/button/Button';
import { Typography } from '@/components/atoms/typogrpahy';
import { TOP_UP_COMPLETION_PATH } from '../../topupFlow';
import Image from 'next/image';
import { getSafeImageSource } from './paymentImage';

interface EWalletPageProps {
  redirectUrl?: string; // Make it optional
  deeplinkUrl?: string;
  qrCodeUrl?: string;
  channelName: string;
  channelLogoUrl?: string;
  amount: number;
  mobileNumber?: string;
  onClose: () => void;
}

const EWalletPage: React.FC<EWalletPageProps> = ({
  redirectUrl,
  deeplinkUrl,
  qrCodeUrl,
  channelName,
  channelLogoUrl,
  amount,
  mobileNumber,
  onClose,
}) => {
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [isMobile, setIsMobile] = useState<boolean | null>(null);
  const normalizedChannelName = channelName.trim().toLowerCase();
  const isGopay = normalizedChannelName === 'gopay';
  const paymentUrl = isGopay ? deeplinkUrl : redirectUrl;
  const showQrCode = isGopay && isMobile === false && qrCodeUrl;
  const canOpenPaymentLink = Boolean(paymentUrl) && (!isGopay || isMobile === true);

  // Auto redirect if no required data (only runs on client-side)
  useEffect(() => {
    if (!channelName) {
      onClose();
    }
  }, [channelName, onClose]);

  useEffect(() => {
    if (typeof navigator !== 'undefined') {
      setIsMobile(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent));
    }
  }, []);

  useEffect(() => {
    if (isGopay && isMobile === true && deeplinkUrl) {
      window.location.href = deeplinkUrl;
    }
  }, [deeplinkUrl, isGopay, isMobile]);

  const handleClose = () => {
    setShowConfirmModal(true);
  };
  const handleConfirmClose = () => {
    window.location.href = TOP_UP_COMPLETION_PATH;
  };

  const handleCancelClose = () => {
    setShowConfirmModal(false);
  };

  const handleRedirectToPayment = () => {
    if (paymentUrl) {
      window.open(paymentUrl, '_blank', 'noopener,noreferrer');
    }
  };

  // This component will only be rendered client-side when currentView changes
  // So no need for SSR/hydration checks
  if (!channelName) {
    return null;
  }

  const logoSrc = getSafeImageSource(channelLogoUrl);

  return (
    <div className="flex flex-col min-h-screen bg-white dark:bg-gray-900">
      <div className="flex-shrink-0">
        <div className="p-6">
          <button
            onClick={handleClose}
            className="flex items-center gap-2 text-gray-600 hover:text-gray-800 dark:text-gray-300 dark:hover:text-white transition-colors"
          >
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
            </svg>
            <span className="font-medium">Back</span>
          </button>
        </div>
      </div>
      
      <div className="flex-1 flex items-center justify-center px-4">
        <div className="w-full max-w-md mx-auto">
          <div className="text-center text-black dark:text-white">
            {/* E-Wallet Icon */}
            <div className="mx-auto w-24 h-16 md:w-40 md:h-24 bg-white dark:bg-gray-800 rounded-2xl flex items-center justify-center p-4 border-gray-100 dark:border-gray-700">
              {logoSrc ? (
                <Image
                  src={logoSrc}
                  alt={channelName}
                  width={64}
                  height={40}
                  className="w-full h-full object-contain"
                />
              ) : null}
            </div>

            <h1 className="mb-4 text-3xl font-bold text-brand-500">E-Wallet Payment</h1>
            <p className="text-sm text-gray-500 dark:text-gray-400 mb-8">
              {canOpenPaymentLink
                ? `Complete your payment using ${channelName} by clicking the payment link below`
                : showQrCode
                  ? `Scan the QRIS below with your ${channelName} app to complete the payment`
                  : `E-Wallet payment request created successfully using ${channelName}`
              }
            </p>

            {/* Payment Details Card */}
            <div className="bg-gray-50 dark:bg-gray-800 rounded-2xl p-6 mb-8">
              <div className="space-y-6">
                <div className="flex justify-between items-center py-3 border-b border-gray-200 dark:border-gray-700">
                  <Typography variant="b2" className="text-gray-600 dark:text-gray-300">E-Wallet</Typography>
                  <Typography variant="h5" className="font-bold text-black dark:text-white">
                    {channelName}
                  </Typography>
                </div>
                
                {mobileNumber && (
                  <div className="flex justify-between items-center py-3 border-b border-gray-200 dark:border-gray-700">
                    <Typography variant="b2" className="text-gray-600 dark:text-gray-300">Mobile Number</Typography>
                    <Typography variant="h5" className="font-bold text-brand-500 font-mono">
                      {mobileNumber}
                    </Typography>
                  </div>
                )}
                
                <div className="flex justify-between items-center py-3">
                  <Typography variant="b2" className="text-gray-600 dark:text-gray-300">Amount to Pay</Typography>
                  <Typography variant="h5" className="font-bold text-black dark:text-white">
                    Rp {amount?.toLocaleString('id-ID') || '0'}
                  </Typography>
                </div>
              </div>
            </div>

            {/* Instructions */}
            <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-700 rounded-xl p-4 mb-8 text-left">
                <div className="flex items-start">
                  <div className="flex-shrink-0 mr-3">
                    <svg className="h-6 w-6 text-blue-400 mt-1" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
                  </svg>
                </div>
                <div className="flex-1">
                  <Typography variant="b3" className="text-blue-800 dark:text-blue-200 leading-relaxed">
                    <strong>How to pay:</strong>
                    <br />
                    {canOpenPaymentLink ? (
                      <>
                        1. Click the "Open {channelName} Payment" button below
                        <br />
                        2. You will be redirected to {channelName} payment page
                        <br />
                        3. Complete the payment using your {channelName} account
                        <br />
                        4. Return to this page after payment completion
                      </>
                    ) : showQrCode ? (
                      <>
                        1. Open your {channelName} app
                        <br />
                        2. Scan the QRIS shown below
                        <br />
                        3. Confirm the payment amount
                        <br />
                        4. Complete the payment in your {channelName} app
                      </>
                    ) : (
                      <>
                        1. Open your {channelName} app manually
                        <br />
                        2. Look for payment or transfer options
                        <br />
                        3. Complete the payment using your {channelName} account
                        <br />
                        4. Check your transaction history for confirmation
                      </>
                    )}
                    <br />
                    <br />
                    Your wallet will be credited automatically after successful payment.
                  </Typography>
                </div>
              </div>
            </div>

            {showQrCode && (
              <div className="bg-white dark:bg-gray-800 rounded-2xl p-6 mb-8 border border-gray-100 dark:border-gray-700">
                <div className="flex flex-col items-center gap-4">
                  <Typography variant="b2" className="text-gray-600 dark:text-gray-300">
                    Scan QRIS
                  </Typography>
                  <img
                    src={qrCodeUrl}
                    alt={`${channelName} QRIS`}
                    className="w-56 h-56 object-contain"
                  />
                </div>
              </div>
            )}

            {/* Action Buttons */}
            <div className="space-y-3">
              {canOpenPaymentLink && (
                <Button 
                  variant="primary"
                  size="md"
                  className="w-full text-lg font-bold bg-brand text-white hover:bg-brand/90 py-4"
                  onClick={handleRedirectToPayment}
                >
                  <Typography variant="s5" className="text-white">Open {channelName} Payment</Typography>
                </Button>
              )}
              
              <Button 
                variant="outline" 
                size="md"
                onClick={handleClose}
                className="w-full text-lg font-semibold border-2 border-gray-300 text-black dark:border-gray-600 dark:text-white hover:bg-gray-50 dark:hover:bg-gray-800 py-4"
              >
                <Typography variant="s5">Done</Typography>
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* Confirmation Modal */}
      {showConfirmModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
          <div className="bg-white dark:bg-gray-800 rounded-2xl p-6 w-full max-w-md mx-auto">
            <div className="text-center">
              {/* Warning Icon */}
              <div className="mx-auto mb-4 w-16 h-16 bg-yellow-100 dark:bg-yellow-900/20 rounded-full flex items-center justify-center">
                <svg className="w-8 h-8 text-yellow-600 dark:text-yellow-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
                </svg>
              </div>

              <Typography variant="h4" className="font-bold text-black dark:text-white mb-3">
                {canOpenPaymentLink ? 'Payment Still Pending' : 'E-Wallet Payment Created'}
              </Typography>
              
              <Typography variant="b2" className="text-gray-600 dark:text-gray-300 mb-6 leading-relaxed">
                {canOpenPaymentLink ? (
                  <>
                    Have you completed the payment on {channelName}? If you haven't finished the payment process, 
                    please go back and complete it first. Your wallet will only be credited after successful payment.
                  </>
                ) : (
                  <>
                    Your e-wallet payment request has been created successfully. Please complete the payment 
                    manually using your {channelName} app. Your wallet will be credited after successful payment.
                  </>
                )}
              </Typography>

              <div className="space-y-3">
                <Button
                  variant="primary"
                  size="md"
                  onClick={handleConfirmClose}
                  className="w-full bg-brand text-white hover:bg-brand/90 py-3"
                >
                  <Typography variant="s5" className="text-white">Yes, payment completed</Typography>
                </Button>
                
                <Button
                  variant="outline"
                  size="md"
                  onClick={handleCancelClose}
                  className="w-full border-2 border-gray-300 text-black dark:border-gray-600 dark:text-white hover:bg-gray-50 dark:hover:bg-gray-800 py-3"
                >
                  <Typography variant="s5">Not yet, go back</Typography>
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default EWalletPage;
