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

type Step = 'password' | 'mnemonic' | 'verify';

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

  const [step, setStep] = useState<Step>('password');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [mnemonic, setMnemonic] = useState('');
  const [verifyWords, setVerifyWords] = useState<{ index: number; word: string }[]>([]);
  const [userVerification, setUserVerification] = useState<Record<number, string>>({});
  const [localError, setLocalError] = useState('');

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

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

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

    try {
      const phrase = await createNewWallet(password);
      setMnemonic(phrase);

      // Select 3 random words to verify
      const words = phrase.split(' ');
      const indices = new Set<number>();
      while (indices.size < 3) {
        indices.add(Math.floor(Math.random() * words.length));
      }
      setVerifyWords(
        Array.from(indices)
          .sort((a, b) => a - b)
          .map((i) => ({ index: i, word: words[i] }))
      );

      setStep('mnemonic');
    } catch {
      // Error handled by store
    }
  };

  const handleVerify = () => {
    // Check all verification words
    for (const { index, word } of verifyWords) {
      if (userVerification[index]?.toLowerCase().trim() !== word.toLowerCase()) {
        setLocalError('Verification failed. Please check your mnemonic.');
        return;
      }
    }

    navigate('/wallet');
  };

  const handleContinueToVerify = () => {
    setStep('verify');
  };

  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>

        {step === 'password' && (
          <div className="card">
            <h1 className="text-2xl font-bold mb-6">Create New Wallet</h1>

            <form onSubmit={handleCreateWallet} className="space-y-4">
              <div>
                <label className="block text-sm text-slate-400 mb-2">
                  Password
                </label>
                <input
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="input"
                  placeholder="At least 8 characters"
                  autoFocus
                />
              </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 || !password || !confirmPassword}
                className="w-full btn btn-primary py-3"
              >
                {isLoading ? 'Creating...' : 'Continue'}
              </button>
            </form>
          </div>
        )}

        {step === 'mnemonic' && (
          <div className="card">
            <h1 className="text-2xl font-bold mb-2">Recovery Phrase</h1>
            <p className="text-slate-400 mb-6">
              Write down these 24 words in order. You'll need them to recover your wallet.
            </p>

            <div className="bg-slate-900 rounded-lg p-4 mb-6">
              <div className="grid grid-cols-3 gap-2">
                {mnemonic.split(' ').map((word, i) => (
                  <div key={i} className="flex items-center gap-2">
                    <span className="text-slate-500 text-sm w-6">{i + 1}.</span>
                    <span className="font-mono">{word}</span>
                  </div>
                ))}
              </div>
            </div>

            <div className="p-3 bg-yellow-900/30 border border-yellow-700 rounded-lg text-yellow-300 text-sm mb-6">
              <strong>Warning:</strong> Never share your recovery phrase. Anyone with these words can access your funds.
            </div>

            <button
              onClick={handleContinueToVerify}
              className="w-full btn btn-primary py-3"
            >
              I've Written It Down
            </button>
          </div>
        )}

        {step === 'verify' && (
          <div className="card">
            <h1 className="text-2xl font-bold mb-2">Verify Recovery Phrase</h1>
            <p className="text-slate-400 mb-6">
              Enter the following words from your recovery phrase to confirm you've saved it.
            </p>

            <div className="space-y-4 mb-6">
              {verifyWords.map(({ index }) => (
                <div key={index}>
                  <label className="block text-sm text-slate-400 mb-2">
                    Word #{index + 1}
                  </label>
                  <input
                    type="text"
                    value={userVerification[index] || ''}
                    onChange={(e) =>
                      setUserVerification((prev) => ({
                        ...prev,
                        [index]: e.target.value,
                      }))
                    }
                    className="input"
                    placeholder={`Enter word #${index + 1}`}
                  />
                </div>
              ))}
            </div>

            {localError && (
              <div className="p-3 bg-red-900/50 border border-red-700 rounded-lg text-red-300 text-sm mb-4">
                {localError}
              </div>
            )}

            <button
              onClick={handleVerify}
              className="w-full btn btn-primary py-3"
            >
              Verify & Open Wallet
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
