import React, { useState } from 'react';
import { useTradingAuth } from '../lib/tradingAuth';
import { Button, Input } from './ui/Primitives';

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 ok = await tradingAuth.forgotPassword(email);
        if (!ok) throw new Error(tradingAuth.error || 'Password reset failed');
        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">
            <Input
              label="Email"
              type="email"
              value={email}
              onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEmail(e.target.value)}
              placeholder="trader@example.com"
              required
            />
          </div>

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

          {error && <div className="error-message">{error}</div>}
          {message && <div className="success-message" style={{
            color: 'var(--bl-success)',
            background: 'var(--bl-success-muted)',
            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 type="button" onClick={() => setIsSignUp(!isSignUp)} variant="link" className="link-button">
              {isSignUp ? 'Already have an account? Sign In' : 'Need an account? Sign Up'}
            </Button>
          )}

          {!isSignUp && (
            <Button type="button" onClick={() => {
              setIsResetPassword(!isResetPassword);
              setError(null);
              setMessage(null);
            }} variant="link" 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: var(--background);
          color: var(--foreground);
        }

        .login-card {
          background: var(--bl-surface-strong);
          border: 1px solid var(--bl-border-soft);
          padding: 40px;
          border-radius: 16px;
          width: 100%;
          max-width: 400px;
          box-shadow: var(--card-shadow);
        }

        h1 {
          margin: 0 0 8px 0;
          font-size: 1.5rem;
          text-align: center;
          background: linear-gradient(90deg, var(--foreground), var(--bl-success));
          -webkit-background-clip: text;
          background-clip: text;
          -webkit-text-fill-color: transparent;
        }

        .subtitle {
          text-align: center;
          color: var(--bl-text-quiet);
          margin-bottom: 32px;
          font-size: 0.9rem;
        }

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

        label {
          display: block;
          margin-bottom: 8px;
          color: var(--bl-text-quiet);
          font-size: 0.9rem;
        }

        input {
          width: 100%;
          padding: 12px;
          background: var(--input);
          border: 1px solid var(--bl-border-soft);
          border-radius: 8px;
          color: var(--foreground);
          font-size: 1rem;
          box-sizing: border-box;
        }

        input:focus {
          outline: none;
          border-color: var(--bl-success);
        }

        .auth-button {
          width: 100%;
          padding: 12px;
          background: var(--bl-success);
          color: var(--primary-foreground);
          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: var(--bl-danger);
          background: var(--bl-danger-muted);
          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: var(--bl-text-quiet);
          cursor: pointer;
          font-size: 0.9rem;
          text-decoration: underline;
        }

        .link-button:hover {
          color: var(--foreground);
        }
      `}</style>
    </div>
  );
}
