'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 OTCPageProps {
  otcCode: string;
  merchantId?: string;
  expiresAt?: string;
  channelName: string;
  channelLogoUrl?: string;
  amount: number;
  onClose: () => void;
}

const OTCPage: React.FC<OTCPageProps> = ({
  otcCode,
  merchantId,
  expiresAt,
  channelName,
  channelLogoUrl,
  amount,
  onClose,
}) => {
  const [showConfirmModal, setShowConfirmModal] = useState(false);

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

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

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

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

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

  const logoSrc = channelLogoUrl?.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-md mx-auto">
          <div className="text-center text-black dark:text-white">
            {/* Payment Channel 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">Over The Counter Payment</h1>
            <p className="text-sm text-gray-500 dark:text-gray-400 mb-8">
              Complete your payment at any {channelName} outlet using the code 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">Outlet</Typography>
                  <Typography variant="h5" className="font-bold text-black dark:text-white">
                    {channelName}
                  </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 text-left">Payment Code</Typography>
                  <Typography variant="h5" className="font-bold text-brand-500 font-mono tracking-wider text-right">
                    {otcCode}
                  </Typography>
                </div>

                {merchantId ? (
                  <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 text-left">Merchant ID</Typography>
                    <Typography variant="h5" className="font-bold text-black dark:text-white font-mono text-right">
                      {merchantId}
                    </Typography>
                  </div>
                ) : null}

                {expiresAt ? (
                  <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">Expires At</Typography>
                    <Typography variant="h5" className="font-bold text-black dark:text-white text-right">
                      {expiresAt}
                    </Typography>
                  </div>
                ) : null}
                
                <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>

            {/* Warning */}
            <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-700 rounded-xl p-4 mb-6">
              <div className="flex items-start">
                <div className="flex-shrink-0 mr-3">
                  <svg className="h-6 w-6 text-yellow-400 mt-1" viewBox="0 0 20 20" fill="currentColor">
                    <path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                  </svg>
                </div>
                <div className="flex-1 text-left">
                  <Typography variant="b3" className="text-yellow-800 dark:text-yellow-200 leading-relaxed">
                    <strong>Important:</strong> Present this payment code to the cashier at any {channelName} outlet. 
                    Payment must be completed within 24 hours or the code will expire.
                  </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. Visit any {channelName} outlet
                    <br />
                    2. Tell the cashier you want to make a payment
                    <br />
                    3. Show or tell them the payment code above
                    <br />
                    4. Pay the exact amount shown
                    <br />
                    5. Keep your receipt as proof of payment
                    <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={handleCopyOTCCode}
              >
                <Typography variant="s5" className="text-white">Copy Payment Code</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 payment code 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 OTCPage;
