import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { ArrowLeft, AlertTriangle } from 'lucide-react';
import { useWalletStore } from '../store/wallet';

export default function ImportWallet() {
  const navigate = useNavigate();
  const { importWallet } = useWalletStore();

  const [mnemonic, setMnemonic] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  /**
   * Clear all sensitive data from component state
   * Called after successful import and on unmount
   */
  const clearSensitiveData = useCallback(() => {
    setMnemonic('');
    setPassword('');
    setConfirmPassword('');
  }, []);

  /**
   * Clear sensitive state on unmount to prevent data leaks
   */
  useEffect(() => {
    return () => {
      clearSensitiveData();
    };
  }, [clearSensitiveData]);

  const handleImport = async () => {
    if (password !== confirmPassword) {
      setError('Passwords do not match');
      return;
    }
    if (password.length < 8) {
      setError('Password must be at least 8 characters');
      return;
    }

    const words = mnemonic.trim().split(/\s+/);
    if (words.length !== 24) {
      setError('Recovery phrase must be exactly 24 words');
      return;
    }

    setLoading(true);
    setError('');

    try {
      await importWallet(mnemonic.trim(), password);
      // Clear sensitive data immediately after successful import
      clearSensitiveData();
      navigate('/dashboard');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to import wallet');
      // Clear password on error but keep mnemonic for retry
      setPassword('');
      setConfirmPassword('');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="h-full flex flex-col items-center justify-center p-8">
      <div className="w-full max-w-md">
        {/* Back button */}
        <button
          onClick={() => navigate('/')}
          className="flex items-center gap-2 text-gray-400 hover:text-white mb-8 transition-colors"
        >
          <ArrowLeft size={20} />
          Back
        </button>

        <div className="card">
          <h2 className="text-xl font-semibold text-white mb-6">
            Import Wallet
          </h2>

          <div className="space-y-4">
            <div>
              <label className="block text-sm text-gray-400 mb-2">
                Recovery Phrase
              </label>
              <textarea
                value={mnemonic}
                onChange={(e) => setMnemonic(e.target.value)}
                className="input min-h-[120px] resize-none font-mono text-sm"
                placeholder="Enter your 24-word recovery phrase, separated by spaces"
              />
            </div>

            <div>
              <label className="block text-sm text-gray-400 mb-2">
                New Password
              </label>
              <input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="input"
                placeholder="Create a password (min 8 characters)"
              />
            </div>

            <div>
              <label className="block text-sm text-gray-400 mb-2">
                Confirm Password
              </label>
              <input
                type="password"
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                className="input"
                placeholder="Confirm password"
              />
            </div>

            {error && (
              <p className="text-red-400 text-sm flex items-center gap-2">
                <AlertTriangle size={16} />
                {error}
              </p>
            )}

            <button
              onClick={handleImport}
              disabled={loading || !mnemonic || !password || !confirmPassword}
              className="btn btn-primary w-full"
            >
              {loading ? 'Importing...' : 'Import Wallet'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
