import React, { useState, useEffect } from 'react';
import { useNavigate, Link, useLocation, useSearchParams } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { Button } from '../components/ui/button';
import { Input } from '../components/ui/input';
import { PasswordInput } from '../components/ui/password-input';
import { Label } from '../components/ui/label';
import { Card } from '../components/ui/card';
import { toast } from 'sonner';
import PublicNavbar from '../components/PublicNavbar';
import PublicFooter from '../components/PublicFooter';
import { ArrowRight, ArrowLeft } from 'lucide-react';

const Login = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [searchParams] = useSearchParams();
  const { login } = useAuth();
  const basename = process.env.REACT_APP_BASENAME || '';
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    email: '',
    password: ''
  });

  // Show session expiry message on mount
  useEffect(() => {
    const sessionParam = searchParams.get('session');
    const stateMessage = location.state?.message;

    if (sessionParam === 'expired') {
      toast.info('Your session has expired. Please log in again.', {
        duration: 5000,
      });
      // Clean up URL (respect basename for subpath deployments)
      window.history.replaceState({}, '', `${basename}/login`);
    } else if (sessionParam === 'idle') {
      toast.info('You were logged out due to inactivity. Please log in again.', {
        duration: 5000,
      });
      // Clean up URL (respect basename for subpath deployments)
      window.history.replaceState({}, '', `${basename}/login`);
    } else if (stateMessage) {
      toast.info(stateMessage, {
        duration: 5000,
      });
    }
  }, [searchParams, location.state, basename]);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

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

    try {
      const user = await login(formData.email, formData.password);
      toast.success('Login successful!');

      // Check if password change is required
      if (user.force_password_change) {
        toast.warning('You must change your password before continuing', {
          duration: 5000
        });
        navigate('/change-password-required');
        return;
      }

      if (user.role === 'admin' || user.role === 'superadmin') {
        navigate('/admin');
      } else {
        navigate('/dashboard');
      }
    } catch (error) {
      toast.error(error.response?.data?.detail || 'Login failed. Please check your credentials.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-[var(--neutral-100)] to-[var(--neutral-800)]">
      <PublicNavbar />

      <div className="max-w-md mx-auto px-6 py-12 ">
        <div className="mb-8">
          <Link to="/" className="inline-flex items-center text-brand-purple  hover:text-[var(--orange-light)] transition-colors">
            <ArrowLeft className="h-4 w-4 mr-2" />
            Back to Home
          </Link>
        </div>

        <Card className="p-8 md:p-12 bg-background rounded-2xl border border-[var(--neutral-800)] shadow-lg">
          <div className="mb-8 text-center">
            <h1 className="text-4xl md:text-5xl font-semibold text-[var(--purple-ink)] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
              Welcome Back
            </h1>
            <p className="text-lg text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
              Login to access your member dashboard.
            </p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-6" data-testid="login-form">
            <div>
              <Label htmlFor="email">Email</Label>
              <Input
                id="email"
                name="email"
                type="email"
                required
                value={formData.email}
                onChange={handleInputChange}
                placeholder="your.email@example.com"
                className="h-14 rounded-xl border-2  focus:border-brand-purple "
                data-testid="login-email-input "
              />
            </div>

            <div>
              <div className="flex items-center justify-between mb-2">
                <Label htmlFor="password">Password</Label>
                <Link to="/forgot-password" className="text-sm text-[var(--orange-light)] hover:underline">
                  Forgot password?
                </Link>
              </div>
              <PasswordInput
                id="password"
                name="password"
                required
                value={formData.password}
                onChange={handleInputChange}
                placeholder="Enter your password"
                className="h-14 rounded-xl border-2 border-[var(--neutral-800)] focus:border-brand-purple "
                data-testid="login-password-input"
              />
            </div>

            <Button
              type="submit"
              disabled={loading}
              className="w-full py-6 text-lg font-medium shadow-lg hover:scale-105 disabled:opacity-50 btn-lavender"
              data-testid="login-submit-button"
            >
              {loading ? 'Logging in...' : 'Login'}
              <ArrowRight className="ml-2 h-5 w-5" />
            </Button>

            <p className="text-center text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
              Don't have an account?{' '}
              <Link to="/register" className="text-[var(--orange-light)] hover:underline font-medium">
                Register here
              </Link>
            </p>
          </form>
        </Card>
      </div>

      <PublicFooter />
    </div>
  );
};

export default Login;
