import React, { useState, useRef, useEffect } from 'react';
import { createPasswordKeypad, XKeypad, XKeypadManager, type XKeypadResult } from '../../utils/xkeypad';
import './xkeypad-sample.css';

export const XkeypadSample: React.FC = () => {
  const [password, setPassword] = useState('');
  const [result, setResult] = useState<XKeypadResult | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [showResult, setShowResult] = useState(false);

  const passwordInputRef = useRef<HTMLInputElement>(null);
  const passwordKeypadRef = useRef<XKeypad | null>(null);

  // RSA Keys (실제 프로덕션에서는 서버에서 받아와야 함)
  const RSA_MODULUS = "C4F7B39E2E93DB19C016C7A0C1C05B028A1D57CB9B91E13F5B7353F8FB5AC6CE6BE31ABEB8E8F7AD18B90C08F4EBC011A6A8FCE614EA879ED5B96296B969CE92923BC9BAD6FD87F00E08F529F93010EA77E40937BDAC1C866E79ACE2F2822A3ECD982F90532D5301CF90D9BF89E953A0593AB6C5F31E99B690DD582FB85F85A9";
  const RSA_EXPONENT = "10001";

  // 키패드 초기화
  useEffect(() => {
    const initializeKeypad = async () => {
      try {
        const manager = XKeypadManager.getInstance({
          modulus: RSA_MODULUS,
          exponent: RSA_EXPONENT
        });

        await manager.loadScripts();
        setIsLoading(false);
      } catch (error) {
        console.error('Failed to load XKeypad:', error);
        setIsLoading(false);
      }
    };

    initializeKeypad();

    return () => {
      // Cleanup
      if (passwordKeypadRef.current) {
        passwordKeypadRef.current.destroy();
      }
    };
  }, []);

  // 비밀번호 입력 처리
  const handlePasswordInput = async () => {
    if (!passwordInputRef.current || isLoading) return;

    // 키패드가 없으면 생성
    if (!passwordKeypadRef.current) {
      passwordKeypadRef.current = createPasswordKeypad(passwordInputRef.current, {
        keyType: 'qwertysmart',
        viewType: 'half',
        maxInputSize: 16,
        useOverlay: true, // 오버레이 사용
        useModal: false,
        hasPressEffect: true,
        onInputChange: (length: number) => {
          console.log('Password length:', length);
        },
        onKeypadClose: () => {
          console.log('Keypad closed');
          // 키패드가 닫힐 때 입력값 업데이트
          if (passwordInputRef.current) {
            setPassword(passwordInputRef.current.value);
          }
        }
      }, {
        modulus: RSA_MODULUS,
        exponent: RSA_EXPONENT
      });
    }

    const result = await passwordKeypadRef.current.initialize(passwordInputRef.current);

    if (result === 0) {
      console.log('Keypad opened successfully');
    } else if (result === -1) {
      alert('지원하지 않는 기기입니다.');
    }
  };

  // 비밀번호 제출
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    if (!passwordKeypadRef.current) {
      alert('비밀번호를 입력해주세요.');
      return;
    }

    const keypadResult = passwordKeypadRef.current.getValue();

    if (!keypadResult || !keypadResult.plainText) {
      alert('비밀번호를 입력해주세요.');
      return;
    }

    // 결과 저장 및 표시
    setResult(keypadResult);
    setShowResult(true);

    console.log('Password submitted:', keypadResult);

    // 서버로 전송할 데이터
    const dataToSend = {
      encryptedPassword: keypadResult.rsaEncrypted || keypadResult.plainText,
      timestamp: new Date().toISOString()
    };

    console.log('Data to send to server:', dataToSend);

    // TODO: 서버로 전송
    // await sendToServer(dataToSend);
  };

  // 초기화
  const handleReset = () => {
    if (passwordKeypadRef.current) {
      passwordKeypadRef.current.clear();
    }

    if (passwordInputRef.current) {
      passwordInputRef.current.value = '';
    }

    setPassword('');
    setResult(null);
    setShowResult(false);
  };

  if (isLoading) {
    return (
      <div className="xkeypad-sample-container">
        <div className="loading">
          <p>키패드 로딩 중...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="xkeypad-sample-container">
      <div className="sample-card">
        <h1>보안 키패드 샘플</h1>
        <p className="description">
          보안 키패드를 사용하여 안전하게 비밀번호를 입력하세요.
        </p>

        <form onSubmit={handleSubmit} className="password-form">
          <div className="form-group">
            <label htmlFor="password">비밀번호</label>
            <div className="input-wrapper">
              <input
                ref={passwordInputRef}
                id="password"
                type="password"
                placeholder="클릭하여 비밀번호 입력"
                onClick={handlePasswordInput}
                readOnly
                className="password-input"
              />
              <span className="input-icon">🔒</span>
            </div>
            <small className="help-text">
              입력 필드를 클릭하면 보안 키패드가 나타납니다.
            </small>
          </div>

          <div className="button-group">
            <button type="submit" className="submit-btn">
              로그인
            </button>
            <button type="button" onClick={handleReset} className="reset-btn">
              초기화
            </button>
          </div>
        </form>

        {showResult && result && (
          <div className="result-section">
            <h3>입력 결과</h3>
            <div className="result-content">
              <div className="result-item">
                <span className="label">Type:</span>
                <span className="value">{result.type}</span>
              </div>
              {result.plainText && (
                <div className="result-item">
                  <span className="label">Plain Text:</span>
                  <span className="value">{'•'.repeat(result.plainText.length)}</span>
                </div>
              )}
              {result.rsaEncrypted && (
                <div className="result-item">
                  <span className="label">RSA Encrypted:</span>
                  <span className="value encrypted">{result.rsaEncrypted.substring(0, 50)}...</span>
                </div>
              )}
            </div>
          </div>
        )}

        <div className="info-section">
          <h3>특징</h3>
          <ul>
            <li>✅ RSA 암호화 지원</li>
            <li>✅ 가상 키패드로 키로거 방지</li>
            <li>✅ 랜덤 키 배열</li>
            <li>✅ 모바일 최적화</li>
            <li>✅ 터치/클릭 이펙트</li>
          </ul>
        </div>
      </div>
    </div>
  );
};

export default XkeypadSample;