"use client";
import Link from 'next/link';
import { useState } from 'react';
import { useRouter } from 'next/navigation';

export default function LoginPage() {
  const router = useRouter();

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState<string | null>(null);
  const [msg, setMsg] = useState<string | null>(null);

  const submitForm = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setErr(null);
    setMsg(null);

    if (!email || !password) {
      setErr('Please enter username/email and password.');
      return;
    }

    setLoading(true);
    try {
      const res = await fetch('http://localhost:3050/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      });

      const contentType = res.headers.get('content-type') || '';
      const data = contentType.includes('application/json') ? await res.json() : await res.text();

      if (!res.ok) {
        throw new Error((typeof data === 'object' && (data?.message || data?.error)) || `Login failed (${res.status})`);
      }

      try {
        sessionStorage.setItem('USERID', data.userid);
        localStorage.setItem('vgproducts_uid', data.userid);
        localStorage.setItem('d4a_email', data.email);
        
        // Dispatch event to update navbar state immediately
        window.dispatchEvent(new Event('storage'));
      } catch {
        console.log('Error setting storage');
      }

      setMsg('Login successful!');
      setTimeout(() => router.push('/'), 500); // Redirect to homepage or dashboard after login
    } catch (e: any) {
      setErr(e?.message || 'Something went wrong. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-page-wrapper">
      {/* ── INNER BANNER ── */}
      {/* <section className="inner-banner fade-up">
        <div className="inner-banner-content">
          <h1 className="section-h2">Customer <span>Login</span></h1>
          <div className="banner-breadcrumb" style={{ marginTop: '30px', marginBottom: '0' }}>
            <Link href="/">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>
              Home
            </Link>
            <span className="separator">/</span>
            <span>Login</span>
          </div>
        </div>
      </section> */}

      <div className="auth-page">
        <div className="auth-card">
          <h2 className="auth-title">Access Your <span>Account</span></h2>

        {err && <div style={{ color: 'red', marginBottom: '20px', fontSize: '13px', background: 'rgba(255,0,0,0.1)', padding: '12px', borderRadius: '6px', border: '1px solid rgba(255,0,0,0.2)' }}>{err}</div>}
        {msg && <div style={{ color: '#4ade80', marginBottom: '20px', fontSize: '13px', background: 'rgba(74,222,128,0.1)', padding: '12px', borderRadius: '6px', border: '1px solid rgba(74,222,128,0.2)' }}>{msg}</div>}

        <form className="auth-form" onSubmit={submitForm}>
          <div className="form-group">
            <label className="form-label">Username / Email</label>
            <input
              className="form-input"
              type="text"
              placeholder="Enter Customer Email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
          </div>
          <div className="form-group">
            <label className="form-label">Password</label>
            <input
              className="form-input"
              type="password"
              placeholder="••••••••"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
          </div>

          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '32px', marginTop: '8px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <input type="checkbox" id="remember" />
              <label htmlFor="remember" style={{ fontSize: '12px', color: 'rgba(255,255,255,0.5)', cursor: 'pointer' }}>Remember me</label>
            </div>
            <Link href="#" style={{ fontSize: '12px', color: 'var(--orange)', textDecoration: 'none', fontWeight: 600 }}>Forgot Password?</Link>
          </div>

          <button type="submit" className="form-submit" disabled={loading}>
            {loading ? 'Logging in...' : 'Login to Portal →'}
          </button>
        </form>
      </div>
    </div>
  </div>
  );
}
