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

export default function Unlock() {
  const navigate = useNavigate();
  const { unlockWallet } = useWalletStore();

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

  const handleUnlock = async (e: React.FormEvent) => {
    e.preventDefault();

    setLoading(true);
    setError('');

    try {
      const success = await unlockWallet(password);
      if (success) {
        navigate('/dashboard');
      } else {
        setError('Invalid password');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to unlock wallet');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="h-full flex flex-col items-center justify-center p-8">
      <div className="w-full max-w-sm">
        {/* Logo */}
        <div className="flex justify-center mb-8">
          <div className="w-16 h-16 rounded-xl bg-gradient-to-br from-synor-400 to-synor-600 flex items-center justify-center">
            <Lock className="text-white" size={32} />
          </div>
        </div>

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

          <form onSubmit={handleUnlock} className="space-y-4">
            <div>
              <label className="block text-sm text-gray-400 mb-2">
                Password
              </label>
              <input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="input"
                placeholder="Enter your password"
                autoFocus
              />
            </div>

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

            <button
              type="submit"
              disabled={loading || !password}
              className="btn btn-primary w-full"
            >
              {loading ? 'Unlocking...' : 'Unlock'}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}
