import React, { useEffect, useState } from 'react';
import Head from 'next/head';
import { useRouter } from 'next/router';
import { useSession, signIn } from 'next-auth/react';
import { Eye, EyeOff } from 'lucide-react';

export default function SignInPage() {
  const router = useRouter();
  const { data: session, status } = useSession();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [providers, setProviders] = useState<any>(null);

  useEffect(() => {
    if (status === 'authenticated') {
      router.replace('/');
    }
  }, [status]);

  useEffect(() => {
    async function fetchProviders() {
      try {
        const r = await fetch('/api/auth/providers');
        if (r.ok) setProviders(await r.json());
      } catch {}
    }
    fetchProviders();
  }, []);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);
    const res = await signIn('credentials', {
      redirect: false,
      username,
      password,
    });
    setLoading(false);
    if (res?.error) {
      setError(res.error || 'Login failed');
      return;
    }
    router.push('/');
  }

  async function handleGoogle() {
    await signIn('google');
  }

  return (
    <>
      <Head>
        <title>Sign in - Gregory AI</title>
      </Head>
      <div style={{ minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center', background:'linear-gradient(180deg,#f8fafc,#f1f5f9)' }}>
        <div style={{ width: '100%', maxWidth: 420, background:'#fff', border:'1px solid #e5e7eb', borderRadius:16, padding:24, boxShadow:'0 12px 30px rgba(2,6,23,0.08)' }}>
          <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:16 }}>
            <img src="/logo.png" alt="Gregory AI" width={40} height={40} style={{ borderRadius:12 }} />
            <h1 style={{ margin:0, fontSize:22 }}>Welcome back</h1>
          </div>
          <p style={{ marginTop:0, color:'#6b7280', fontSize:14 }}>Sign in to continue your conversations.</p>
          <form onSubmit={handleSubmit}>
            <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
              <input value={username} onChange={e=>setUsername(e.target.value)} placeholder="Username or Email" style={{ padding:'12px 14px', borderRadius:10, border:'1px solid #e5e7eb' }} />
              <div style={{ position: 'relative' }}>
                <input 
                  value={password} 
                  onChange={e=>setPassword(e.target.value)} 
                  placeholder="Password" 
                  type={showPassword ? 'text' : 'password'} 
                  style={{ padding:'12px 14px', paddingRight: '44px', borderRadius:10, border:'1px solid #e5e7eb', width: '100%', boxSizing: 'border-box' }} 
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  style={{
                    position: 'absolute',
                    right: '12px',
                    top: '50%',
                    transform: 'translateY(-50%)',
                    background: 'transparent',
                    border: 'none',
                    cursor: 'pointer',
                    padding: '4px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    color: '#6b7280'
                  }}
                  tabIndex={-1}
                >
                  {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                </button>
              </div>
              {error && <div style={{ color:'#ef4444', fontSize:12 }}>{error}</div>}
              <button type="submit" disabled={loading} style={{ padding:'12px 14px', borderRadius:10, border:'1px solid #e6e6e6', background:'#2563eb', color:'#fff', cursor:'pointer' }}>{loading ? 'Signing in...' : 'Sign in'}</button>
              {providers?.google && (
                <button type="button" onClick={handleGoogle} style={{ padding:'12px 14px', borderRadius:10, border:'1px solid #e6e6e6', background:'#fff', cursor:'pointer' }}>Sign in with Google</button>
              )}
            </div>
          </form>
          <div style={{ marginTop:12, color:'#6b7280', fontSize:14 }}>
            New here? <a href="/auth/signup" style={{ color:'#2563eb', textDecoration:'none' }}>Create an account</a>
          </div>
        </div>
      </div>
    </>
  );
}
