import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Mail, Lock, Eye, EyeOff } from 'lucide-react';
import { Input } from '../components/ui/Input';
import { GradientButton } from '../components/ui/GradientButton';
import { Button } from '../components/ui/Button';
import { Modal } from '../components/ui/Modal';
import { useAuth } from '../context/AuthContext';
import { api } from '../api/client';

export function LoginPage() {
  const navigate = useNavigate();
  const { login } = useAuth();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  // Forgot password
  const [showForgot, setShowForgot] = useState(false);
  const [forgotEmail, setForgotEmail] = useState('');
  const [forgotMessage, setForgotMessage] = useState('');
  const [forgotSending, setForgotSending] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setIsLoading(true);
    try {
      await login(email, password);
      navigate('/');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Login failed');
    } finally {
      setIsLoading(false);
    }
  };

  const handleForgotPassword = async () => {
    if (!forgotEmail) return;
    setForgotSending(true);
    setForgotMessage('');
    try {
      const res = await api.post<{ message: string }>('/auth/forgot-password', { email: forgotEmail });
      setForgotMessage(res.message);
    } catch (err) {
      setForgotMessage(err instanceof Error ? err.message : 'Failed to send reset link');
    }
    setForgotSending(false);
  };

  const handleSocialLogin = () => {
    setError('Social login is not yet available. Please use email and password.');
  };

  return (
    <div className="min-h-[80vh] flex items-center justify-center px-4 py-12">
      <div className="w-full max-w-md">
        <div className="bg-white rounded-3xl shadow-xl p-8">
          <div className="text-center mb-8">
            <h1 className="text-2xl font-bold text-gray-900">Log In</h1>
            <p className="text-sm text-gray-500 mt-2">Welcome back! Please sign in to your account</p>
          </div>

          {/* Social Login */}
          <div className="space-y-3 mb-6">
            <Button variant="outline" className="w-full justify-center gap-2" onClick={handleSocialLogin}>
              <img src="https://www.gstatic.com/firebasejs/ui/2.0.0/images/auth/google.svg" alt="Google" className="w-5 h-5" />
              Log in with Google
            </Button>
            <Button variant="outline" className="w-full justify-center gap-2 !border-blue-200 !text-blue-600 hover:!bg-blue-50" onClick={handleSocialLogin}>
              <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>
              Log in with Facebook
            </Button>
          </div>

          <div className="relative mb-6">
            <div className="absolute inset-0 flex items-center"><div className="w-full border-t border-gray-200" /></div>
            <div className="relative flex justify-center text-sm"><span className="px-3 bg-white text-gray-400">or</span></div>
          </div>

          {error && (
            <div className="mb-4 p-3 rounded-xl bg-red-50 text-red-600 text-sm">{error}</div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            <Input label="Email" type="email" placeholder="Enter your email" value={email} onChange={(e) => setEmail(e.target.value)}
              icon={<Mail className="w-4 h-4" />} required />
            <div className="relative">
              <Input label="Password" type={showPassword ? 'text' : 'password'} placeholder="Enter your password" value={password} onChange={(e) => setPassword(e.target.value)}
                icon={<Lock className="w-4 h-4" />} required />
              <button type="button" onClick={() => setShowPassword(!showPassword)}
                className="absolute right-3 top-[38px] text-gray-400 hover:text-gray-600 cursor-pointer">
                {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
              </button>
            </div>
            <div className="text-right">
              <button type="button" onClick={() => { setShowForgot(true); setForgotEmail(email); setForgotMessage(''); }}
                className="text-xs text-primary-600 hover:text-primary-700 cursor-pointer">Forgot password?</button>
            </div>
            <GradientButton type="submit" className="w-full" size="lg" isLoading={isLoading}>
              Log In
            </GradientButton>
          </form>

          <p className="text-center text-sm text-gray-500 mt-6">
            Don't have an account?{' '}
            <Link to="/signup" className="text-primary-600 font-semibold hover:text-primary-700">Sign Up &gt;</Link>
          </p>
        </div>
      </div>

      {/* Forgot Password Modal */}
      <Modal isOpen={showForgot} onClose={() => setShowForgot(false)} title="Reset Password" size="sm">
        <p className="text-sm text-gray-500 mb-4">Enter your email address and we'll send you a password reset link.</p>
        {forgotMessage && <p className="text-sm text-green-600 mb-3">{forgotMessage}</p>}
        <div className="mb-6">
          <Input label="Email" type="email" value={forgotEmail} onChange={(e) => setForgotEmail(e.target.value)} placeholder="Enter your email" />
        </div>
        <div className="flex gap-3">
          <Button variant="secondary" className="flex-1" onClick={() => setShowForgot(false)}>Cancel</Button>
          <GradientButton className="flex-1" onClick={handleForgotPassword} disabled={forgotSending}>
            {forgotSending ? 'Sending...' : 'Send Reset Link'}
          </GradientButton>
        </div>
      </Modal>
    </div>
  );
}
