import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { supabase } from '../config/supabase';
import { Loader2, CheckCircle, AlertTriangle } from 'lucide-react';

const ResetPassword: React.FC = () => {
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);
  const [validatingToken, setValidatingToken] = useState(true);
  const [tokenValid, setTokenValid] = useState(false);
  const navigate = useNavigate();

  useEffect(() => {
    // Check if we have a valid session from the email link
    const checkSession = async () => {
      try {
        const { data: { session }, error } = await supabase.auth.getSession();
        
        if (error || !session) {
          setTokenValid(false);
          setError('This password reset link is invalid or has expired. Please request a new one.');
        } else {
          setTokenValid(true);
        }
      } catch (err) {
        setTokenValid(false);
        setError('Unable to verify reset link. Please try again.');
      } finally {
        setValidatingToken(false);
      }
    };

    checkSession();
  }, []);

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

    // Validation
    if (!newPassword || newPassword.length < 6) {
      setError('Password must be at least 6 characters long');
      setLoading(false);
      return;
    }

    if (newPassword !== confirmPassword) {
      setError('Passwords do not match');
      setLoading(false);
      return;
    }

    try {
      // Update the password
      const { error: updateError } = await supabase.auth.updateUser({
        password: newPassword,
      });

      if (updateError) throw updateError;

      setSuccess(true);
      
      // Redirect to login after 3 seconds
      setTimeout(() => {
        navigate('/login');
      }, 3000);
    } catch (err: any) {
      setError(err.message || 'Failed to reset password. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const handleRequestNewLink = () => {
    navigate('/login');
  };

  if (validatingToken) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-beige to-light-green/20 flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
        <div className="max-w-md w-full">
          <div className="bg-white p-8 rounded-xl shadow-lg border border-light-gray text-center">
            <Loader2 className="h-12 w-12 animate-spin text-primary-green mx-auto mb-4" />
            <p className="text-secondary-text">Verifying your reset link...</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-beige to-light-green/20 flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-md w-full space-y-8">
        <div>
          <div className="w-16 h-16 bg-primary-green rounded-xl flex items-center justify-center mx-auto mb-4 shadow-lg">
            <span className="text-3xl">🔐</span>
          </div>
          <h2 className="mt-6 text-center text-3xl font-extrabold text-deep-forest">
            {success ? 'Password Reset Successful!' : 'Create New Password'}
          </h2>
          <p className="mt-2 text-center text-sm text-secondary-text">
            {success 
              ? 'You can now sign in with your new password' 
              : tokenValid 
                ? 'Enter your new password below'
                : 'Link expired or invalid'}
          </p>
        </div>

        <div className="bg-white p-8 rounded-xl shadow-lg border border-light-gray">
          {success ? (
            <div className="text-center space-y-4">
              <div className="rounded-full bg-fresh/10 w-16 h-16 flex items-center justify-center mx-auto">
                <CheckCircle className="h-10 w-10 text-primary-green" />
              </div>
              <div className="space-y-2">
                <p className="text-primary-green font-semibold">Password updated successfully!</p>
                <p className="text-sm text-secondary-text">Redirecting you to login page...</p>
              </div>
              <div className="pt-4">
                <button
                  onClick={() => navigate('/login')}
                  className="text-sm font-medium text-primary-green hover:text-deep-forest"
                >
                  Go to Login Now
                </button>
              </div>
            </div>
          ) : !tokenValid ? (
            <div className="text-center space-y-4">
              <div className="rounded-full bg-warning/10 w-16 h-16 flex items-center justify-center mx-auto">
                <AlertTriangle className="h-10 w-10 text-warning" />
              </div>
              <div className="space-y-2">
                <p className="text-warning font-semibold">Link Expired or Invalid</p>
                <p className="text-sm text-secondary-text">
                  Password reset links expire after 1 hour for security. Please request a new one.
                </p>
              </div>
              {error && (
                <div className="rounded-md bg-warning/10 border border-warning p-4">
                  <div className="text-sm text-warning">{error}</div>
                </div>
              )}
              <div className="pt-4">
                <button
                  onClick={handleRequestNewLink}
                  className="w-full px-4 py-3 bg-btn-primary text-white rounded-lg hover:bg-btn-primary-hover transition-colors font-semibold shadow-sm"
                >
                  Request New Reset Link
                </button>
              </div>
            </div>
          ) : (
            <form onSubmit={handleSubmit} className="space-y-6">
              {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 className="space-y-4">
                <div>
                  <label htmlFor="new-password" className="block text-sm font-medium text-primary-text mb-2">
                    New Password *
                  </label>
                  <input
                    id="new-password"
                    name="new-password"
                    type="password"
                    required
                    value={newPassword}
                    onChange={(e) => setNewPassword(e.target.value)}
                    className="w-full px-3 py-2 border border-light-gray rounded-lg focus:ring-2 focus:ring-primary-green focus:border-primary-green text-primary-text"
                    placeholder="Enter new password (min. 6 characters)"
                    autoComplete="new-password"
                  />
                </div>

                <div>
                  <label htmlFor="confirm-password" className="block text-sm font-medium text-primary-text mb-2">
                    Confirm New Password *
                  </label>
                  <input
                    id="confirm-password"
                    name="confirm-password"
                    type="password"
                    required
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                    className="w-full px-3 py-2 border border-light-gray rounded-lg focus:ring-2 focus:ring-primary-green focus:border-primary-green text-primary-text"
                    placeholder="Confirm new password"
                    autoComplete="new-password"
                  />
                </div>
              </div>

              <div className="bg-stable/10 border border-stable rounded-lg p-4">
                <p className="text-xs text-secondary-text">
                  <strong className="text-primary-text">Password Requirements:</strong>
                </p>
                <ul className="text-xs text-secondary-text mt-2 space-y-1 list-disc list-inside">
                  <li>At least 6 characters long</li>
                  <li>Mix of letters and numbers recommended</li>
                  <li>Avoid using common passwords</li>
                </ul>
              </div>

              <button
                type="submit"
                disabled={loading}
                className="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 ? (
                  <>
                    <Loader2 className="h-5 w-5 mr-2 animate-spin" />
                    Updating Password...
                  </>
                ) : (
                  'Reset Password'
                )}
              </button>

              <div className="text-center pt-2">
                <button
                  type="button"
                  onClick={() => navigate('/login')}
                  className="text-sm font-medium text-primary-green hover:text-deep-forest"
                >
                  Back to Login
                </button>
              </div>
            </form>
          )}
        </div>
      </div>
    </div>
  );
};

export default ResetPassword;

