'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import StoreLayout from '@/components/layout/StoreLayout';
import { useAuth } from '@/context/AuthContext';
import { useLanguage } from '@/context/LanguageContext';
import styles from './auth.module.css';

export default function LoginPage() {
  const { login } = useAuth();
  const { t, language } = useLanguage();
  const router = useRouter();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    const ok = await login(email, password);
    setLoading(false);
    if (ok) router.push('/');
    else setError(language === 'ar' ? 'بريد إلكتروني أو كلمة مرور خاطئة' : 'Invalid email or password');
  };

  // Quick demo admin login
  const demoLogin = async () => {
    setEmail('admin@fasttimephone.kw');
    setPassword('admin123');
    setLoading(true);
    const ok = await login('admin@fasttimephone.kw', 'admin123');
    setLoading(false);
    if (ok) router.push('/admin');
  };

  return (
    <StoreLayout>
      <div className={styles.page}>
        <div className={styles.card}>
          <div className={styles.logo}>
            <span style={{ fontSize: '2.5rem' }}>⚡</span>
          </div>
          <h1 className={styles.title}>{t.auth.loginTitle}</h1>
          <p className={styles.subtitle}>{t.auth.loginSubtitle}</p>

          {error && <div className={styles.error}>{error}</div>}

          <form onSubmit={handleSubmit} className={styles.form}>
            <div className="form-group">
              <label className="form-label">{t.auth.email}</label>
              <input type="email" required className="form-input" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@example.com" />
            </div>
            <div className="form-group">
              <label className="form-label">{t.auth.password}</label>
              <input type="password" required className="form-input" value={password} onChange={e => setPassword(e.target.value)} placeholder="••••••••" />
            </div>
            <button type="submit" className="btn btn-primary btn-full btn-lg" disabled={loading}>
              {loading ? '⏳...' : t.auth.login}
            </button>
          </form>

          <div className={styles.demo}>
            <button className="btn btn-outline btn-full btn-sm" onClick={demoLogin} disabled={loading}>
              🔑 {language === 'ar' ? 'دخول تجريبي (مسؤول)' : 'Demo Login (Admin)'}
            </button>
          </div>

          <p className={styles.altLink}>
            {t.auth.noAccount}
            <Link href="/auth/register"> {t.auth.signUp}</Link>
          </p>
        </div>
      </div>
    </StoreLayout>
  );
}
