import React, { useState } from 'react';
import { supabase } from '../lib/supabaseClient';
import { useTradingAuth } from '../lib/tradingAuth';

export function Login() {
  const tradingAuth = useTradingAuth();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isSignUp, setIsSignUp] = useState(false);
  const [isResetPassword, setIsResetPassword] = useState(false);
  const [message, setMessage] = useState<string | null>(null);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    setMessage(null);

    try {
      if (isResetPassword) {
        const { error } = await supabase.auth.resetPasswordForEmail(email, {
          redirectTo: window.location.origin + '/reset-callback',
        });
        if (error) throw error;
        setMessage('Password reset link sent! Check your email.');
      } else if (isSignUp) {
        const ok = await tradingAuth.register(email, password, email.split('@')[0] || 'Trader');
        if (!ok) throw new Error(tradingAuth.error || 'Registration failed');
        setMessage('Check your email for the confirmation link!');
      } else {
        const ok = await tradingAuth.login(email, password);
        if (!ok) throw new Error(tradingAuth.error || 'Login failed');
      }
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-container">
      <div className="login-card">
        <h1>Trading Dashboard</h1>
        <p className="subtitle">
          {isResetPassword
            ? 'Reset your password'
            : isSignUp
              ? 'Create an account'
              : 'Sign in to access bot controls'}
        </p>

        <form onSubmit={handleLogin}>
          <div className="form-group">
            <label>Email</label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="trader@example.com"
              required
            />
          </div>

          {!isResetPassword && (
            <div className="form-group">
              <label>Password</label>
              <input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="••••••••"
                required
              />
            </div>
          )}

          {error && <div className="error-message">{error}</div>}
          {message && <div className="success-message" style={{
            color: '#00ff88',
            background: 'rgba(0, 255, 136, 0.1)',
            padding: '10px',
            borderRadius: '6px',
            marginBottom: '20px',
            textAlign: 'center',
            fontSize: '0.9rem'
          }}>{message}</div>}

          <button type="submit" disabled={loading} className="auth-button">
            {loading ? 'Processing...' : isResetPassword ? 'Send Reset Link' : isSignUp ? 'Sign Up' : 'Sign In'}
          </button>
        </form>

        <div className="auth-footer" style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
          {!isResetPassword && (
            <button onClick={() => setIsSignUp(!isSignUp)} className="link-button">
              {isSignUp ? 'Already have an account? Sign In' : 'Need an account? Sign Up'}
            </button>
          )}

          {!isSignUp && (
            <button onClick={() => {
              setIsResetPassword(!isResetPassword);
              setError(null);
              setMessage(null);
            }} className="link-button">
              {isResetPassword ? 'Back to Sign In' : 'Forgot Password?'}
            </button>
          )}
        </div>
      </div>

      <style>{`
        .login-container {
          display: flex;
          align-items: center;
          justify-content: center;
          min-height: 100vh;
          background: #0a0b0d;
          color: #fff;
        }

        .login-card {
          background: #14151a;
          border: 1px solid rgba(255, 255, 255, 0.1);
          padding: 40px;
          border-radius: 16px;
          width: 100%;
          max-width: 400px;
          box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
        }

        h1 {
          margin: 0 0 8px 0;
          font-size: 1.5rem;
          text-align: center;
          background: linear-gradient(90deg, #fff, #00ff88);
          -webkit-background-clip: text;
          background-clip: text;
          -webkit-text-fill-color: transparent;
        }

        .subtitle {
          text-align: center;
          color: #929292;
          margin-bottom: 32px;
          font-size: 0.9rem;
        }

        .form-group {
          margin-bottom: 20px;
        }

        label {
          display: block;
          margin-bottom: 8px;
          color: #ccc;
          font-size: 0.9rem;
        }

        input {
          width: 100%;
          padding: 12px;
          background: rgba(255, 255, 255, 0.05);
          border: 1px solid rgba(255, 255, 255, 0.1);
          border-radius: 8px;
          color: #fff;
          font-size: 1rem;
          box-sizing: border-box;
        }

        input:focus {
          outline: none;
          border-color: #00ff88;
        }

        .auth-button {
          width: 100%;
          padding: 12px;
          background: #00ff88;
          color: #000;
          border: none;
          border-radius: 8px;
          font-weight: bold;
          font-size: 1rem;
          cursor: pointer;
          margin-top: 10px;
          transition: opacity 0.2s;
        }

        .auth-button:disabled {
          opacity: 0.7;
          cursor: not-allowed;
        }

        .error-message {
          color: #ff3366;
          background: rgba(255, 51, 102, 0.1);
          padding: 10px;
          border-radius: 6px;
          margin-bottom: 20px;
          font-size: 0.9rem;
          text-align: center;
        }

        .auth-footer {
          margin-top: 24px;
          text-align: center;
        }

        .link-button {
          background: none;
          border: none;
          color: #929292;
          cursor: pointer;
          font-size: 0.9rem;
          text-decoration: underline;
        }

        .link-button:hover {
          color: #fff;
        }
      `}</style>
    </div>
  );
}
