import React, { useState, useEffect } from 'react';
import { Link, useNavigate, useLocation } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { supabase } from '../config/supabase';
import Logo from '../components/Logo';
import { ArrowLeft, Shield, Heart, BookOpen } from 'lucide-react';

const Login: React.FC = () => {
  const [isLogin, setIsLogin] = useState(true);
  const [showForgotPassword, setShowForgotPassword] = useState(false);
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [fullName, setFullName] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [resetEmailSent, setResetEmailSent] = useState(false);
  const [justLoggedIn, setJustLoggedIn] = useState(false);

  const { signIn, signUp, user } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();

  // Redirect after successful login once user data is loaded
  useEffect(() => {
    if (justLoggedIn && user) {
      const redirectTo = location.state?.from?.pathname || 
        (user.role === 'admin' ? '/admin-dashboard' : 
         user.role === 'volunteer' ? '/team-dashboard' : 
         '/user-dashboard');
      navigate(redirectTo, { replace: true });
      setJustLoggedIn(false);
    }
  }, [user, justLoggedIn, navigate, location]);

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

    try {
      if (isLogin) {
        const { error } = await signIn(email, password);
        if (error) {
          setError(error.message);
        } else {
          setJustLoggedIn(true);
        }
      } else {
        const { error } = await signUp(email, password, fullName, 'user');
        if (error) {
          setError(error.message);
        } else {
          setError('');
          alert('Registration successful! Please check your email to verify your account.');
          setIsLogin(true);
        }
      }
    } catch (err) {
      setError('An unexpected error occurred');
    } finally {
      setLoading(false);
    }
  };

  const handleForgotPassword = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    setResetEmailSent(false);

    try {
      if (!email) {
        setError('Please enter your email address');
        return;
      }

      const { error } = await supabase.auth.resetPasswordForEmail(email, {
        redirectTo: `${window.location.origin}/reset-password`,
      });

      if (error) {
        setError(error.message);
      } else {
        setResetEmailSent(true);
      }
    } catch (err) {
      setError('Failed to send reset email. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex">
      {/* Left panel - branding (hidden on small screens) */}
      <div className="hidden lg:flex lg:w-1/2 xl:w-[55%] bg-gradient-to-br from-primary-green to-deep-forest p-12 xl:p-16 flex-col justify-between relative overflow-hidden">
        <div className="absolute inset-0 opacity-10">
          <div className="absolute top-20 left-20 w-72 h-72 rounded-full bg-white" />
          <div className="absolute bottom-32 right-16 w-96 h-96 rounded-full bg-white" />
        </div>
        <div className="relative">
          <Link to="/" className="inline-flex items-center gap-2 text-white/90 hover:text-white text-sm font-medium mb-12">
            <ArrowLeft className="h-4 w-4" /> Back to home
          </Link>
          <Logo size="lg" className="[&_span]:text-white [&_img]:brightness-0 [&_img]:invert" />
          <p className="mt-6 text-lg text-white/90 max-w-sm">
            Supporting student food security on campus. Sign in to access your pantry portal or manage your institution.
          </p>
        </div>
        <ul className="relative space-y-4 text-white/90">
          <li className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center flex-shrink-0">
              <Shield className="h-5 w-5 text-white" />
            </div>
            <span>Secure sign-in for students and staff</span>
          </li>
          <li className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center flex-shrink-0">
              <Heart className="h-5 w-5 text-white" />
            </div>
            <span>Reserve items and schedule pickup with dignity</span>
          </li>
          <li className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center flex-shrink-0">
              <BookOpen className="h-5 w-5 text-white" />
            </div>
            <span>No student should choose between studying and eating</span>
          </li>
        </ul>
      </div>

      {/* Right panel - form */}
      <div className="w-full lg:w-1/2 xl:w-[45%] flex items-center justify-center py-12 px-4 sm:px-6 lg:px-10 bg-gradient-to-b from-beige/80 to-light-green/10 min-h-screen">
        <div className="w-full max-w-md space-y-8">
          {/* Mobile: back link + logo */}
          <div className="lg:hidden text-center">
            <Link to="/" className="inline-flex items-center gap-2 text-secondary-text hover:text-primary-green text-sm font-medium mb-6">
              <ArrowLeft className="h-4 w-4" /> Back to home
            </Link>
            <div className="flex justify-center mb-4">
              <Logo size="lg" />
            </div>
          </div>

          <div>
            <h2 className="text-2xl sm:text-3xl font-extrabold text-deep-forest text-center lg:text-left">
              {showForgotPassword ? 'Reset your password' : isLogin ? 'Sign in to your account' : 'Create your account'}
            </h2>
            <p className="mt-2 text-center lg:text-left text-sm text-secondary-text">
              {showForgotPassword ? (
                <>
                  Remember your password?{' '}
                  <button
                    type="button"
                    className="font-medium text-primary-green hover:text-deep-forest"
                    onClick={() => {
                      setShowForgotPassword(false);
                      setError('');
                      setResetEmailSent(false);
                    }}
                  >
                    Sign in
                  </button>
                </>
              ) : (
                <>
                  {isLogin ? "Don't have an account? " : "Already have an account? "}
                  <button
                    type="button"
                    className="font-medium text-primary-green hover:text-deep-forest"
                    onClick={() => {
                      setIsLogin(!isLogin);
                      setError('');
                      setResetEmailSent(false);
                    }}
                  >
                    {isLogin ? 'Sign up' : 'Sign in'}
                  </button>
                </>
              )}
            </p>
          </div>
        
        {showForgotPassword ? (
          <form className="mt-8 space-y-6 bg-white p-8 rounded-xl shadow-lg border border-light-gray" onSubmit={handleForgotPassword}>
            {resetEmailSent ? (
              <div className="rounded-md bg-fresh/10 border border-fresh p-4">
                <div className="flex">
                  <div className="flex-shrink-0">
                    <svg className="h-5 w-5 text-primary-green" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                      <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                    </svg>
                  </div>
                  <div className="ml-3">
                    <h3 className="text-sm font-medium text-primary-green">Reset email sent!</h3>
                    <div className="mt-2 text-sm text-secondary-text">
                      <p>Please check your email for instructions to reset your password. The link will expire in 1 hour.</p>
                    </div>
                  </div>
                </div>
              </div>
            ) : (
              <>
                <div>
                  <p className="text-sm text-secondary-text text-center mb-4">
                    Enter your email address and we'll send you a link to reset your password.
                  </p>
                  <label htmlFor="reset-email" className="sr-only">
                    Email address
                  </label>
                  <input
                    id="reset-email"
                    name="email"
                    type="email"
                    autoComplete="email"
                    required
                    className="appearance-none relative block w-full px-3 py-2 border border-light-gray placeholder-secondary-text text-primary-text rounded-md focus:outline-none focus:ring-2 focus:ring-primary-green focus:border-primary-green focus:z-10 sm:text-sm"
                    placeholder="Email address"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                  />
                </div>

                {error && (
                  <div className="rounded-md bg-warning/10 border border-warning p-4">
                    <div className="text-sm text-warning font-medium">{error}</div>
                  </div>
                )}

                <div>
                  <button
                    type="submit"
                    disabled={loading}
                    className="group relative w-full flex justify-center py-3 px-4 border border-transparent text-sm font-semibold rounded-lg text-white bg-btn-primary hover:bg-btn-primary-hover active:bg-btn-primary-active focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-green disabled:opacity-50 disabled:cursor-not-allowed shadow-md transition-colors"
                  >
                    {loading ? (
                      <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>
                    ) : null}
                    Send Reset Link
                  </button>
                </div>
              </>
            )}
          </form>
        ) : (
          <form className="mt-8 space-y-6 bg-white p-8 rounded-xl shadow-lg border border-light-gray" onSubmit={handleSubmit}>
          <div className="rounded-md shadow-sm -space-y-px">
            {!isLogin && (
              <div>
                <label htmlFor="fullName" className="sr-only">
                  Full Name
                </label>
                <input
                  id="fullName"
                  name="fullName"
                  type="text"
                  required={!isLogin}
                  className="appearance-none rounded-none relative block w-full px-3 py-2 border border-light-gray placeholder-secondary-text text-primary-text rounded-t-md focus:outline-none focus:ring-2 focus:ring-primary-green focus:border-primary-green focus:z-10 sm:text-sm"
                  placeholder="Full Name"
                  value={fullName}
                  onChange={(e) => setFullName(e.target.value)}
                />
              </div>
            )}
            <div>
              <label htmlFor="email-address" className="sr-only">
                Email address
              </label>
              <input
                id="email-address"
                name="email"
                type="email"
                autoComplete="email"
                required
                className={`appearance-none rounded-none relative block w-full px-3 py-2 border border-light-gray placeholder-secondary-text text-primary-text ${
                  !isLogin ? '' : 'rounded-t-md'
                } focus:outline-none focus:ring-2 focus:ring-primary-green focus:border-primary-green focus:z-10 sm:text-sm`}
                placeholder="Email address"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
              />
            </div>
            <div>
              <label htmlFor="password" className="sr-only">
                Password
              </label>
              <input
                id="password"
                name="password"
                type="password"
                autoComplete="current-password"
                required
                className="appearance-none rounded-none relative block w-full px-3 py-2 border border-light-gray placeholder-secondary-text text-primary-text rounded-b-md focus:outline-none focus:ring-2 focus:ring-primary-green focus:border-primary-green focus:z-10 sm:text-sm"
                placeholder="Password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
              />
            </div>
          </div>

          {error && (
            <div className="rounded-md bg-warning/10 border border-warning p-4">
              <div className="text-sm text-warning font-medium">{error}</div>
            </div>
          )}

          {isLogin && (
            <div className="flex items-center justify-center">
              <button
                type="button"
                onClick={() => {
                  setShowForgotPassword(true);
                  setError('');
                  setResetEmailSent(false);
                }}
                className="text-sm font-medium text-primary-green hover:text-deep-forest"
              >
                Forgot your password?
              </button>
            </div>
          )}

          <div>
            <button
              type="submit"
              disabled={loading}
              className="group relative w-full flex justify-center py-3 px-4 border border-transparent text-sm font-semibold rounded-lg text-white bg-btn-primary hover:bg-btn-primary-hover active:bg-btn-primary-active focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-green disabled:opacity-50 disabled:cursor-not-allowed shadow-md transition-colors"
            >
              {loading ? (
                <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
              ) : null}
              {isLogin ? 'Sign in' : 'Sign up'}
            </button>
          </div>
        </form>
        )}

          <p className="text-center lg:text-left text-xs text-secondary-text mt-6 flex items-center justify-center lg:justify-start gap-1.5">
            <Shield className="h-3.5 w-3.5 text-primary-green" />
            Secure sign-in
          </p>
        </div>
      </div>
    </div>
  );
};

export default Login;
