import React, { useState } from 'react';
import { useAuth } from '../../context/AuthContext';
import { API_BASE_URL, isLocalMode } from '../../config/apiConfig';
import { localLogin } from '../../services/localApi';

// Import crypto library for hashing
import crypto from 'crypto-js';

const Login: React.FC = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const { login } = useAuth();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setIsLoading(true);

    try {
      // Create a SHA-256 hash of the password
      const hashedPassword = crypto.SHA256(password).toString();
      
      // Choose between local and remote API based on configuration
      if (isLocalMode()) {
        // Use local authentication
        const result = await localLogin(email, hashedPassword);
        
        if (result.success && result.token) {
          login(result.token);
        } else {
          setError(result.error || 'Authentication failed');
        }
      } else {
        // Use remote authentication (original implementation)
        const response = await fetch(`${API_BASE_URL}/api/login.php`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            // Add security headers
            'X-Requested-With': 'XMLHttpRequest', // Help prevent CSRF
          },
          // Send the plaintext email but hashed password
          body: JSON.stringify({
            email,
            password: hashedPassword,
          }),
          // Include credentials like cookies if needed
          credentials: 'include',
        });

        const data = await response.json();
        
        if (response.ok) {
          // If response is successful, we should have a token
          if (data.token) {
            login(data.token);
          } else {
            setError('Invalid server response');
          }
        } else {
          // Handle error responses
          setError(data.error || 'Authentication failed');
        }
      }
    } catch (err) {
      setError('Failed to connect to the server. Please try again.');
      console.error('Login error:', err);
    } finally {
      // Clear password from memory for security
      setPassword('');
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-100 px-4">
      <div className="max-w-md w-full mx-auto p-6 bg-white rounded shadow">
        <div className="flex justify-center mb-6">
          <img 
            src="/images/logo.webp" 
            alt="Logo" 
            className="h-16"
          />
        </div>
        <h2 className="text-2xl font-bold mb-4 text-center">Login</h2>
        {error && <p className="text-red-500 mb-4">{error}</p>}
        <form onSubmit={handleSubmit}>
          <div className="mb-4">
            <label className="block text-gray-700">Email</label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="w-full px-3 py-2 border rounded"
              required
              disabled={isLoading}
            />
          </div>
          <div className="mb-4">
            <label className="block text-gray-700">Password</label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="w-full px-3 py-2 border rounded"
              required
              disabled={isLoading}
            />
          </div>
          <button
            type="submit"
            className="w-full bg-blue-600 text-white py-2 rounded hover:bg-blue-700 disabled:bg-blue-400"
            disabled={isLoading}
          >
            {isLoading ? 'Logging in...' : 'Login'}
          </button>
          {isLocalMode() && (
            <div className="mt-4 text-sm text-gray-500">
              <p>Demo accounts:</p>
              <p>Email: admin@example.com / Password: admin123</p>
              <p>Email: user@example.com / Password: user123</p>
            </div>
          )}
        </form>
      </div>
    </div>
  );
};

export default Login;