'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { authApi } from '@/lib/api';
import { getDefaultPathAfterLogin } from '@/lib/authRedirect';

export default function LoginPage() {
  const router = useRouter();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  // Check if already logged in - only on initial mount
  useEffect(() => {
    const token = localStorage.getItem('access_token');
    if (token) {
      try {
        const raw = localStorage.getItem('user_info');
        const user = raw ? JSON.parse(raw) : null;
        router.replace(getDefaultPathAfterLogin(user));
      } catch {
        router.replace('/dashboard?section=overview');
      }
    }
  }, []); // Empty array - only check once on mount

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

    if (!username.trim() || !password) {
      setError('Please enter both username and password');
      return;
    }

    setError('');
    setLoading(true);

    try {
      const data = await authApi.login(username, password);
      
      // Store tokens and user info (industry standard: access + refresh)
      localStorage.setItem('access_token', data.access_token);
      if (data.refresh_token) localStorage.setItem('refresh_token', data.refresh_token);
      const userJson = JSON.stringify(data.user);
      localStorage.setItem('user_info', userJson);
      localStorage.setItem('user', userJson); // used by Workstations and Administrator page
      
      // Redirect: duty dashboard for indexing/scanning officers, else main dashboard
      router.replace(getDefaultPathAfterLogin(data.user));
    } catch (err: any) {
      if (err.code === 'ECONNABORTED' || err.message?.includes('timeout')) {
        setError('Connection timed out. Is the API server running? Try again in a moment.');
      } else if (err.message === 'Network Error' || !err.response) {
        setError('Cannot reach the server. Check that the backend is running (e.g. on port 8001).');
      } else {
        setError(err.response?.data?.detail || 'Login failed. Please check your credentials.');
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-page">
      {/* Animated background pattern */}
      <div className="animated-bg" />

      <div className="login-container">
        {/* Header */}
        <div className="login-header">
          <h1>📁 Boundary Commission</h1>
          <p>Boundary Commission Digital Archive System</p>
        </div>

        {/* Login Form */}
        <form className="login-form" onSubmit={handleSubmit}>
          {/* Error Message */}
          {error && (
            <div className="error-message">
              {error}
            </div>
          )}

          {/* Username Field */}
          <div className="form-group">
            <label htmlFor="username">Username</label>
            <input
              type="text"
              id="username"
              name="username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              placeholder="Enter your username"
              required
              autoComplete="username"
            />
          </div>

          {/* Password Field */}
          <div className="form-group">
            <label htmlFor="password">Password</label>
            <input
              type="password"
              id="password"
              name="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="Enter your password"
              required
              autoComplete="current-password"
            />
          </div>

          {/* Submit Button */}
          <button type="submit" className="btn-login" disabled={loading}>
            {loading ? (
              <>
                <span style={{ display: 'none' }}>Sign In</span>
                <div className="loading-spinner" />
              </>
            ) : (
              <span>Sign In</span>
            )}
          </button>
        </form>

        {/* Footer */}
        <div className="footer-text">
          Boundary Commission Digital Archive System
        </div>
      </div>

      <style jsx>{`
        .login-page {
          min-height: 100vh;
          background: linear-gradient(135deg, #047857 0%, #064e3b 100%);
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 20px;
          position: relative;
          overflow: hidden;
        }

        .animated-bg {
          content: '';
          position: absolute;
          width: 200%;
          height: 200%;
          background-image: 
            radial-gradient(circle at 20% 50%, rgba(16, 185, 129, 0.1) 0%, transparent 50%),
            radial-gradient(circle at 80% 80%, rgba(5, 150, 105, 0.1) 0%, transparent 50%),
            radial-gradient(circle at 40% 20%, rgba(6, 95, 70, 0.1) 0%, transparent 50%);
          animation: float 20s ease-in-out infinite;
        }

        @keyframes float {
          0%, 100% { transform: translate(0, 0) rotate(0deg); }
          33% { transform: translate(30px, -30px) rotate(120deg); }
          66% { transform: translate(-20px, 20px) rotate(240deg); }
        }

        .login-container {
          background: rgba(255, 255, 255, 0.15);
          backdrop-filter: blur(20px);
          -webkit-backdrop-filter: blur(20px);
          border: 1px solid rgba(255, 255, 255, 0.2);
          border-radius: 24px;
          box-shadow: 
            0 8px 32px rgba(0, 0, 0, 0.3),
            inset 0 1px 0 rgba(255, 255, 255, 0.3);
          overflow: hidden;
          max-width: 420px;
          width: 100%;
          position: relative;
          z-index: 1;
        }

        .login-header {
          background: linear-gradient(135deg, rgba(16, 185, 129, 0.95) 0%, rgba(5, 150, 105, 0.95) 100%);
          backdrop-filter: blur(10px);
          -webkit-backdrop-filter: blur(10px);
          color: white;
          padding: 40px 30px;
          text-align: center;
          border-bottom: 1px solid rgba(255, 255, 255, 0.2);
        }

        .login-header h1 {
          font-size: 28px;
          margin-bottom: 8px;
        }

        .login-header p {
          font-size: 14px;
          opacity: 0.9;
        }

        .login-form {
          padding: 40px 30px;
          background: rgba(255, 255, 255, 0.5);
          backdrop-filter: blur(10px);
          -webkit-backdrop-filter: blur(10px);
        }

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

        label {
          display: block;
          font-size: 14px;
          font-weight: 600;
          color: #064e3b;
          margin-bottom: 8px;
          text-shadow: 0 1px 2px rgba(255, 255, 255, 0.5);
        }

        input[type="text"],
        input[type="password"] {
          width: 100%;
          padding: 12px 16px;
          border: 2px solid rgba(229, 231, 235, 0.5);
          background: rgba(255, 255, 255, 0.8);
          backdrop-filter: blur(5px);
          -webkit-backdrop-filter: blur(5px);
          border-radius: 10px;
          font-size: 15px;
          transition: all 0.3s ease;
        }

        input[type="text"]:focus,
        input[type="password"]:focus {
          outline: none;
          border-color: #10b981;
          background: rgba(255, 255, 255, 0.95);
          box-shadow: 
            0 0 0 3px rgba(16, 185, 129, 0.15),
            0 4px 12px rgba(16, 185, 129, 0.1);
          transform: translateY(-2px);
        }

        .btn-login {
          width: 100%;
          padding: 14px;
          background: linear-gradient(135deg, #10b981 0%, #059669 100%);
          color: white;
          border: none;
          border-radius: 10px;
          font-size: 16px;
          font-weight: 600;
          cursor: pointer;
          transition: all 0.3s ease;
          box-shadow: 0 4px 15px rgba(16, 185, 129, 0.4);
        }
        
        .btn-login:hover:not(:disabled) {
          transform: translateY(-3px);
          box-shadow: 
            0 10px 25px rgba(16, 185, 129, 0.5),
            0 0 0 1px rgba(255, 255, 255, 0.5) inset;
          background: linear-gradient(135deg, #059669 0%, #047857 100%);
        }

        .btn-login:active {
          transform: translateY(0);
        }

        .btn-login:disabled {
          opacity: 0.6;
          cursor: not-allowed;
          transform: none;
        }

        .error-message {
          background: rgba(254, 226, 226, 0.9);
          backdrop-filter: blur(10px);
          -webkit-backdrop-filter: blur(10px);
          color: #991b1b;
          padding: 12px 16px;
          border-radius: 10px;
          border: 1px solid rgba(153, 27, 27, 0.2);
          margin-bottom: 20px;
          font-size: 14px;
          box-shadow: 0 4px 12px rgba(153, 27, 27, 0.1);
        }

        .loading-spinner {
          width: 20px;
          height: 20px;
          border: 3px solid #ffffff;
          border-top-color: transparent;
          border-radius: 50%;
          animation: spin 0.8s linear infinite;
          margin: 0 auto;
        }

        @keyframes spin {
          to { transform: rotate(360deg); }
        }

        .footer-text {
          text-align: center;
          padding: 20px;
          color: rgba(255, 255, 255, 0.8);
          font-size: 13px;
          background: rgba(255, 255, 255, 0.1);
          backdrop-filter: blur(10px);
          -webkit-backdrop-filter: blur(10px);
        }
      `}</style>
    </div>
  );
}
