'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';

interface VirtualAccountPageProps {
  vaNumber: string;
  bankName: string;
  bankLogoUrl?: string;
  amount: number;
  onClose: () => void;
}

const VirtualAccountPage: React.FC<VirtualAccountPageProps> = ({
  vaNumber,
  bankName,
  bankLogoUrl,
  amount,
  onClose,
}) => {
  const [showConfirmModal, setShowConfirmModal] = useState(false);

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

  const handleClose = () => {
    setShowConfirmModal(true);
  };

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

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

  const handleCopyVANumber = async () => {
    if (vaNumber && typeof navigator !== 'undefined' && navigator.clipboard) {
      try {
        await navigator.clipboard.writeText(vaNumber);
        alert('Virtual Account number copied to clipboard!');
      } catch (err) {
        console.error('Failed to copy: ', err);
        // Fallback for older browsers
        const textArea = document.createElement('textarea');
        textArea.value = vaNumber;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
        alert('Virtual Account number copied to clipboard!');
      }
    }
  };

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

  const logoSrc = bankLogoUrl?.trim();

  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-lg mx-auto">
          <div className="text-center text-black dark:text-white">
            {/* Bank 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={bankName}
                  width={96}
                  height={60}
                  className="w-full h-full object-contain"
                />
              ) : null}
            </div>

            <h1 className="mb-4 text-3xl font-bold text-brand-500">Payment Details</h1>
            <p className="text-sm text-gray-500 dark:text-gray-400 mb-8">
              Complete your payment using the details below
            </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">Bank Name</Typography>
                  <Typography variant="h5" className="font-bold text-black dark:text-white">
                    {bankName}
                  </Typography>
                </div>
                
                <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">Virtual Account</Typography>
                  <Typography variant="h5" className="font-bold text-brand-500 font-mono tracking-wider">
                    {vaNumber}
                  </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 />
                    1. Open your banking app or visit ATM
                    <br />
                    2. Select "Transfer" or "Virtual Account"
                    <br />
                    3. Enter the Virtual Account number above
                    <br />
                    4. Enter the exact amount to pay
                    <br />
                    5. Confirm and complete the transaction
                    <br />
                    <br />
                    Your wallet will be credited automatically after payment confirmation.
                  </Typography>
                </div>
              </div>
            </div>

            {/* Action Buttons */}
            <div className="space-y-3">
              <Button 
                variant="primary"
                size="md"
                className="w-full text-lg font-bold bg-brand text-white hover:bg-brand/90 py-4"
                onClick={handleCopyVANumber}
              >
                <Typography variant="s5">Copy Virtual Account Number</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">
                Save Your Payment Information
              </Typography>
              
              <Typography variant="b3" className="text-gray-600 dark:text-gray-300 mb-6 leading-relaxed">
                Please make sure you have saved or copied your Virtual Account number before closing this page. 
                Once closed, this information cannot be retrieved and you'll need to create a new payment request.
              </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, I have saved it</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 VirtualAccountPage;
