import { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { useWalletStore } from '../store/wallet';
import { validateMnemonic } from '../lib/crypto';

export default function RecoverWalletPage() {
  const { recoverWallet, isLoading, error, clearError } = useWalletStore();
  const navigate = useNavigate();

  const [mnemonic, setMnemonic] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [localError, setLocalError] = useState('');

  const handleRecover = async (e: React.FormEvent) => {
    e.preventDefault();
    setLocalError('');

    const normalizedMnemonic = mnemonic.trim().toLowerCase().replace(/\s+/g, ' ');

    if (!validateMnemonic(normalizedMnemonic)) {
      setLocalError('Invalid recovery phrase. Please check your words.');
      return;
    }

    if (password.length < 8) {
      setLocalError('Password must be at least 8 characters');
      return;
    }

    if (password !== confirmPassword) {
      setLocalError('Passwords do not match');
      return;
    }

    try {
      await recoverWallet(normalizedMnemonic, password);
      navigate('/wallet');
    } catch {
      // Error handled by store
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center p-4">
      <div className="max-w-lg w-full">
        <Link
          to="/"
          className="inline-flex items-center gap-2 text-slate-400 hover:text-white mb-6"
        >
          ← Back
        </Link>

        <div className="card">
          <h1 className="text-2xl font-bold mb-6">Recover Wallet</h1>

          <form onSubmit={handleRecover} className="space-y-4">
            <div>
              <label className="block text-sm text-slate-400 mb-2">
                Recovery Phrase
              </label>
              <textarea
                value={mnemonic}
                onChange={(e) => setMnemonic(e.target.value)}
                className="input min-h-[100px] resize-none"
                placeholder="Enter your 12 or 24 word recovery phrase..."
                autoFocus
              />
              <p className="text-xs text-slate-500 mt-1">
                Separate words with spaces
              </p>
            </div>

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

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

            {(localError || error) && (
              <div className="p-3 bg-red-900/50 border border-red-700 rounded-lg text-red-300 text-sm">
                {localError || error}
                <button
                  type="button"
                  onClick={() => {
                    setLocalError('');
                    clearError();
                  }}
                  className="ml-2 text-red-400 hover:text-red-200"
                >
                  ×
                </button>
              </div>
            )}

            <button
              type="submit"
              disabled={isLoading || !mnemonic || !password || !confirmPassword}
              className="w-full btn btn-primary py-3"
            >
              {isLoading ? 'Recovering...' : 'Recover Wallet'}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}
