import React, { useState, useEffect, useMemo } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { GoogleOAuthProvider, GoogleLogin } from '@react-oauth/google';
import { LOGIN_URL, GOOGLE_CLIENT_ID, GOOGLE_LOGIN_URL } from '../../utils/config';
import axios from "axios";
import { useScrollToError } from '../../hooks/useScrollToError';
import { getMasterStoredAuth, setStoredAuth } from 'hse-auth';

/** Only allow same-app relative paths (block open redirects). */
function safeReturnTo(value) {
  if (!value || typeof value !== "string") return "/";
  const trimmed = value.trim();
  if (!trimmed.startsWith("/") || trimmed.startsWith("//")) return "/";
  if (trimmed.startsWith("/login")) return "/";
  return trimmed;
}

const Login = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const returnTo = useMemo(
    () => safeReturnTo(searchParams.get("returnTo")),
    [searchParams]
  );
  const [showPassword, setShowPassword] = useState(false);
  const [formData, setFormData] = useState({
    employeeId: '',
    email: '',
    password: '',
    remember: false
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  // const [logoImageError, setLogoImageError] = useState(false); // logo commented off

  useScrollToError(error);

  // Already signed in (e.g. returned from SWI/PTW) — go straight to the target page.
  useEffect(() => {
    if (getMasterStoredAuth()?.token) {
      navigate(returnTo, { replace: true });
    }
  }, [navigate, returnTo]);

  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    try {
      const res = await axios.post(LOGIN_URL, {
        employeeId: formData.employeeId,
        email: formData.email,
        password: formData.password
      });

      setStoredAuth({
        token: res.data.token,
        user: {
          userId: res.data.user?.userId,
          employeeName: res.data.user?.employeeName,
          email: res.data.user?.email,
        },
      }, { scope: "master" });
      navigate(returnTo, { replace: true });
    } catch (err) {
      setError(err.response?.data?.message || "Login failed");
    } finally {
      setLoading(false);
    }
  };

  const handleGoogleSuccess = async (credentialResponse) => {
    setError(null);
    try {
      const res = await axios.post(GOOGLE_LOGIN_URL, {
        credential: credentialResponse.credential
      });
      setStoredAuth({
        token: res.data.token,
        user: {
          userId: res.data.user?.userId,
          employeeName: res.data.user?.employeeName,
          email: res.data.user?.email,
        },
      }, { scope: "master" });
      navigate(returnTo, { replace: true });
    } catch (err) {
      setError(err.response?.data?.message || "Google sign in failed");
    }
  };

  const handleGoogleError = () => {
    console.log("Google Sign In Error");
  };

  useEffect(() => {
    document.body.classList.add('login-page');
    return () => document.body.classList.remove('login-page');
  }, []);

  return (
    <div className="login-wrapper">
      <div className="image-section">
        <div className="image-overlay">
          <div className="overlay-content">
            <h2>Welcome to Our HSE Management System  </h2>
            <p>Experience seamless authentication and secure access to your account</p>
            {/* <div className="feature-list">
              <div className="feature-item">
                <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M9 11L12 14L22 4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                  <path d="M21 12V19C21 19.5304 20.7893 20.0391 20.4142 20.4142C20.0391 20.7893 19.5304 21 19 21H5C4.46957 21 3.96086 20.7893 3.58579 20.4142C3.21071 20.0391 3 19.5304 3 19V5C3 4.46957 3.21071 3.96086 3.58579 3.58579C3.96086 3.21071 4.46957 3 5 3H16" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
                <span>Secure & Encrypted</span>
              </div>
              <div className="feature-item">
                <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M9 11L12 14L22 4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                  <path d="M21 12V19C21 19.5304 20.7893 20.0391 20.4142 20.4142C20.0391 20.7893 19.5304 21 19 21H5C4.46957 21 3.96086 20.7893 3.58579 20.4142C3.21071 20.0391 3 19.5304 3 19V5C3 4.46957 3.21071 3.96086 3.58579 3.58579C3.96086 3.21071 4.46957 3 5 3H16" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
                <span>Fast Access</span>
              </div>
              <div className="feature-item">
                <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M9 11L12 14L22 4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                  <path d="M21 12V19C21 19.5304 20.7893 20.0391 20.4142 20.4142C20.0391 20.7893 19.5304 21 19 21H5C4.46957 21 3.96086 20.7893 3.58579 20.4142C3.21071 20.0391 3 19.5304 3 19V5C3 4.46957 3.21071 3.96086 3.58579 3.58579C3.96086 3.21071 4.46957 3 5 3H16" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
                <span>24/7 Support</span>
              </div>
            </div> */}
          </div>
        </div>
      </div>

      <div className="form-section">
        <div className="login-container">
          <div className="login-card">
            <div className="login-header">
              <div className="logo-icon">
                {/* Logo commented off
                {!logoImageError ? (
                  <>
                    <img
                      src={`${"" || ''}/Vesuvius-India-Limited.png`}
                      alt=""
                      role="presentation"
                      className="login-logo-img-loader"
                      onError={() => setLogoImageError(true)}
                      aria-hidden="true"
                    />
                    <div
                      className="login-logo-img"
                      style={{
                        backgroundImage: `url(${"" || ''}/Vesuvius-India-Limited.png)`,
                      }}
                    />
                  </>
                ) : (
                */}
                  <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M12 2L2 7L12 12L22 7L12 2Z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                    <path d="M2 17L12 22L22 17" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                    <path d="M2 12L12 17L22 12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                {/* )} */}
              </div>
              <p className="subtitle">Sign in to access your account</p>
            </div>

            <form className="login-form" onSubmit={handleSubmit}>
              {error && (
                <div className="login-error-message">
                  {error}
                </div>
              )}
              <div className="input-group">
                <label htmlFor="employeeId" className="input-label">Employee ID</label>
                <div className="input-wrapper">
                  <svg className="input-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                  <input
                    type="text"
                    name="employeeId"
                    id="employeeId"
                    className="input-field"
                    placeholder="Enter your employee ID"
                    value={formData.employeeId}
                    onChange={handleChange}
                    required
                  />
                </div>
              </div>

              <div className="input-group">
                <label htmlFor="email" className="input-label">Email</label>
                <div className="input-wrapper">
                  <svg className="input-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                    <path d="M22 6l-10 7L2 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                  <input
                    type="email"
                    name="email"
                    id="email"
                    className="input-field"
                    placeholder="Enter your email"
                    value={formData.email}
                    onChange={handleChange}
                    required
                  />
                </div>
              </div>

              <div className="input-group">
                <label htmlFor="password" className="input-label">Password</label>
                <div className="input-wrapper">
                  <svg className="input-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <rect x="3" y="11" width="18" height="11" rx="2" ry="2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                    <path d="M7 11V7C7 5.67392 7.52678 4.40215 8.46447 3.46447C9.40215 2.52678 10.6739 2 12 2C13.3261 2 14.5979 2.52678 15.5355 3.46447C16.4732 4.40215 17 5.67392 17 7V11" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                  <input
                    type={showPassword ? 'text' : 'password'}
                    name="password"
                    id="password"
                    className="input-field"
                    placeholder="Enter your password"
                    value={formData.password}
                    onChange={handleChange}
                    required
                  />
                  <button type="button" className="toggle-password" onClick={() => setShowPassword(!showPassword)}>
                    <svg className="eye-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M1 12S5 4 12 4s11 8 11 8-4 8-11 8S1 12 1 12z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                      <circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                  </button>
                </div>
              </div>

              {/* Remember me & Forgot password - commented out
              <div className="form-options">
                <label className="checkbox-container">
                  <input
                    type="checkbox"
                    id="remember"
                    name="remember"
                    checked={formData.remember}
                    onChange={handleChange}
                  />
                  <span className="checkmark"></span>
                  <span className="checkbox-label">Remember me</span>
                </label>
                <a href="#!" className="forgot-password">Forgot password?</a>
              </div>
              */}

              <button type="submit" className={`login-button ${loading ? 'loading' : ''}`} disabled={loading}>
                <span>{loading ? 'Signing in...' : 'Sign In'}</span>
                {!loading && (
                  <svg className="button-arrow" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M5 12H19M19 12L12 5M19 12L12 19" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                )}
              </button>
            </form>

            <>
              <div className="divider divider-google">
                <span>or continue with</span>
              </div>

              <div className="social-login">
                <GoogleOAuthProvider clientId={GOOGLE_CLIENT_ID}>
                  <div className="google-signin-wrapper">
                    <GoogleLogin
                      onSuccess={handleGoogleSuccess}
                      onError={handleGoogleError}
                      size="large"
                      type="standard"
                      theme="outline"
                      text="signin_with"
                    />
                  </div>
                </GoogleOAuthProvider>
              </div>
            </>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;

