'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Eye, EyeOff, Mail, Lock, ChevronRight, AlertCircle, Zap } from 'lucide-react';
import { useAuth } from '@client/contexts/AuthContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import { usePublicBranding } from '@client/hooks/usePublicBranding';


interface FormErrors {
  email?: string;
  password?: string;
  general?: string;
}

function FieldError({ message }: { message?: string }) {
  if (!message) return null;
  return (
    <p className="flex items-center gap-1 text-xs mt-1.5 font-medium" style={{ color: 'hsl(0, 84%, 44%)' }}>
      <AlertCircle size={12} />
      {message}
    </p>
  );
}

function DefaultLogoMark({ size = 32 }: { size?: number }) {
  return (
    <div
      className="rounded-xl flex items-center justify-center shrink-0"
      style={{ width: size, height: size, background: 'linear-gradient(135deg, hsl(22,89%,48%), hsl(22,89%,35%))' }}
    >
      <svg width={size * 0.45} height={size * 0.45} viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
        <path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"/>
        <path d="M19 10v2a7 7 0 0 1-14 0v-2"/>
        <line x1="12" y1="19" x2="12" y2="22"/>
      </svg>
    </div>
  );
}

function BrandedLogo({ logoUrl, siteName, size = 32, light = false }: { logoUrl: string; siteName: string; size?: number; light?: boolean }) {
  const { t } = useLanguage();
  return (
    <Link href="/" className="flex items-center gap-3 group" aria-label={t("common.goToHomepage", "Go to homepage")}>
      {logoUrl
        ? <img src={logoUrl} alt={siteName} className="rounded-xl object-contain shrink-0" style={{ width: size, height: size }} />
        : <DefaultLogoMark size={size} />
      }
      <span className={`font-bold text-xl leading-tight ${light ? 'text-white' : ''}`} style={light ? {} : { color: 'hsl(var(--foreground))' }}>
        {siteName}
      </span>
    </Link>
  );
}

export default function LoginPage() {
  const router = useRouter();
  const { signIn } = useAuth();
  const { t } = useLanguage();
  const DEMO_ACCOUNTS = [
    {
      label: t('auth.demoRestaurantOwner', 'Restaurant Owner'),
      email: 'demo@restroagent.com',
      password: 'demo123456',
      color: 'hsl(22, 89%, 48%)',
      bg: 'hsl(22, 89%, 97%)',
      border: 'hsl(22, 89%, 85%)',
    },
    {
      label: t('auth.demoAdminPanel', 'Admin Panel'),
      email: 'admin@restroagent.com',
      password: 'admin123456',
      color: 'hsl(231, 60%, 48%)',
      bg: 'hsl(231, 60%, 97%)',
      border: 'hsl(231, 60%, 85%)',
    },
  ];
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<FormErrors>({});
  const [touched, setTouched] = useState<Record<string, boolean>>({});

  const { logoUrl, siteTitle: siteName } = usePublicBranding();

  const validateEmail = (val: string): string | undefined => {
    if (!val.trim()) return t('auth.emailRequired', 'Email address is required');
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val)) return t('auth.emailInvalid', 'Please enter a valid email address');
  };

  const validatePassword = (val: string): string | undefined => {
    if (!val) return t('auth.passwordRequired', 'Password is required');
    if (val.length < 6) return t('auth.passwordMinLength', 'Password must be at least 6 characters');
  };

  const handleBlur = (field: string) => {
    setTouched(prev => ({ ...prev, [field]: true }));
    if (field === 'email') setErrors(prev => ({ ...prev, email: validateEmail(email) }));
    if (field === 'password') setErrors(prev => ({ ...prev, password: validatePassword(password) }));
  };

  const validate = (): boolean => {
    const newErrors: FormErrors = {
      email: validateEmail(email),
      password: validatePassword(password),
    };
    setErrors(newErrors);
    setTouched({ email: true, password: true });
    return !newErrors.email && !newErrors.password;
  };

  const getRedirectPath = (role?: string) =>
    role === 'superadmin' || role === 'support' ? '/admin/dashboard' : '/restaurant-dashboard';

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;
    setLoading(true);
    setErrors({});
    try {
      const { user } = await signIn(email, password);
      router.push(getRedirectPath(user?.role));
    } catch (err: any) {
      setErrors({ general: err?.message || t('auth.invalidCredentials', 'Invalid email or password. Please try again.') });
    } finally {
      setLoading(false);
    }
  };

  const handleDemoLogin = async (account: typeof DEMO_ACCOUNTS[0]) => {
    setEmail(account.email);
    setPassword(account.password);
    setErrors({});
    setTouched({ email: true, password: true });
    setLoading(true);
    try {
      const { user } = await signIn(account.email, account.password);
      router.push(getRedirectPath(user?.role));
    } catch (err: any) {
      setErrors({ general: err?.message || t('auth.demoLoginFailed', 'Demo login failed. Please try again.') });
    } finally {
      setLoading(false);
    }
  };

  const inputStyle = (field: string) => ({
    borderColor: touched[field] && errors[field as keyof FormErrors] ? 'hsl(0, 84%, 44%)' : undefined,
    boxShadow: touched[field] && errors[field as keyof FormErrors] ? '0 0 0 2px hsl(0, 84%, 44%, 0.15)' : undefined,
  });

  return (
    <div className="min-h-screen flex" style={{ backgroundColor: 'hsl(var(--background))' }}>
      {/* Left panel */}
      <div className="hidden lg:flex lg:w-1/2 flex-col justify-between p-12 relative overflow-hidden" style={{ background: 'linear-gradient(145deg, hsl(231, 40%, 10%) 0%, hsl(231, 40%, 18%) 60%, hsl(22, 89%, 20%) 100%)' }}>
        <div className="relative z-10">
          <div className="mb-16">
            <BrandedLogo logoUrl={logoUrl} siteName={siteName} size={36} light />
          </div>
          <h1 className="text-4xl font-bold text-white leading-tight mb-4">
            {t('auth.loginHeroTitle1', 'AI-powered restaurant')}<br />
            {t('auth.loginHeroTitle2', 'management, simplified.')}
          </h1>
          <p className="text-base" style={{ color: 'rgba(255,255,255,0.6)' }}>
            {t('auth.loginHeroSubtitle', 'Handle orders, reservations, and customer conversations — all through one intelligent platform.')}
          </p>
        </div>
        <div className="relative z-10 grid grid-cols-3 gap-4">
          {[
            { value: '94%', label: t('auth.statResolutionRate', 'AI Resolution Rate') },
            { value: '3.2s', label: t('auth.statResponseTime', 'Avg Response Time') },
            { value: '12k+', label: t('auth.statOrdersProcessed', 'Orders Processed') },
          ].map(stat => (
            <div key={stat.label} className="p-4 rounded-xl" style={{ backgroundColor: 'rgba(255,255,255,0.08)', backdropFilter: 'blur(8px)' }}>
              <p className="text-2xl font-bold text-white">{stat.value}</p>
              <p className="text-xs mt-0.5" style={{ color: 'rgba(255,255,255,0.5)' }}>{stat.label}</p>
            </div>
          ))}
        </div>
        <div className="absolute -top-20 -right-20 w-80 h-80 rounded-full opacity-10" style={{ background: 'radial-gradient(circle, hsl(22, 89%, 48%), transparent)' }} />
        <div className="absolute -bottom-10 -left-10 w-60 h-60 rounded-full opacity-10" style={{ background: 'radial-gradient(circle, hsl(210, 100%, 60%), transparent)' }} />
      </div>

      {/* Right panel */}
      <div className="flex-1 flex items-center justify-center p-6 lg:p-12">
        <div className="w-full max-w-md">
          <div className="lg:hidden mb-8">
            <BrandedLogo logoUrl={logoUrl} siteName={siteName} size={28} />
          </div>

          <div className="mb-8">
            <h2 className="text-2xl font-bold mb-1" style={{ color: 'hsl(var(--foreground))' }}>{t('auth.welcomeBack', 'Welcome back')}</h2>
            <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('auth.signInToDashboard', 'Sign in to your restaurant dashboard')}</p>
          </div>

          {errors.general && (
            <div className="flex items-center gap-2 p-3 rounded-xl mb-4 text-sm" style={{ backgroundColor: 'hsl(0, 84%, 97%)', color: 'hsl(0, 84%, 44%)', border: '1px solid hsl(0, 84%, 90%)' }}>
              <AlertCircle size={15} />
              {errors.general}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4" noValidate>
            <div>
              <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('auth.emailAddress', 'Email address')}</label>
              <div className="relative">
                <Mail size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: touched.email && errors.email ? 'hsl(0, 84%, 44%)' : 'hsl(var(--muted-foreground))' }} />
                <input
                  type="email"
                  className="input-base pl-9"
                  placeholder={t('auth.emailPlaceholder', 'you@restaurant.com')}
                  value={email}
                  onChange={e => { setEmail(e.target.value); if (touched.email) setErrors(prev => ({ ...prev, email: validateEmail(e.target.value) })); }}
                  onBlur={() => handleBlur('email')}
                  style={inputStyle('email')}
                />
              </div>
              <FieldError message={touched.email ? errors.email : undefined} />
            </div>

            <div>
              <div className="flex items-center justify-between mb-1.5">
                <label className="text-xs font-semibold" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('auth.password', 'Password')}</label>
                <Link href="/forgot-password" className="text-xs font-medium" style={{ color: 'hsl(var(--primary))' }}>
                  {t('auth.forgotPassword', 'Forgot password?')}
                </Link>
              </div>
              <div className="relative">
                <Lock size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: touched.password && errors.password ? 'hsl(0, 84%, 44%)' : 'hsl(var(--muted-foreground))' }} />
                <input
                  type={showPassword ? 'text' : 'password'}
                  className="input-base pl-9 pr-10"
                  placeholder="••••••••"
                  value={password}
                  onChange={e => { setPassword(e.target.value); if (touched.password) setErrors(prev => ({ ...prev, password: validatePassword(e.target.value) })); }}
                  onBlur={() => handleBlur('password')}
                  style={inputStyle('password')}
                />
                <button
                  type="button"
                  className="absolute right-3 top-1/2 -translate-y-1/2"
                  onClick={() => setShowPassword(!showPassword)}
                  style={{ color: 'hsl(var(--muted-foreground))' }}
                >
                  {showPassword ? <EyeOff size={15} /> : <Eye size={15} />}
                </button>
              </div>
              <FieldError message={touched.password ? errors.password : undefined} />
            </div>

            <button
              type="submit"
              disabled={loading}
              className="btn-primary w-full justify-center py-2.5 mt-2"
            >
              {loading ? (
                <span className="flex items-center gap-2">
                  <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                  {t('auth.signingIn', 'Signing in...')}
                </span>
              ) : (
                <span className="flex items-center gap-2">
                  {t('auth.signIn', 'Sign in')} <ChevronRight size={16} />
                </span>
              )}
            </button>
          </form>

          <p className="text-center text-sm mt-6" style={{ color: 'hsl(var(--muted-foreground))' }}>
            {t('auth.noAccount', "Don't have an account?")}{' '}
            <Link href="/register" className="font-semibold" style={{ color: 'hsl(var(--primary))' }}>
              {t('auth.createFree', 'Create one free')}
            </Link>
          </p>

          {/* Demo Credentials Card */}
          <div className="mt-6 rounded-xl overflow-hidden" style={{ border: '1px solid hsl(var(--border))' }}>
            <div className="flex items-center gap-2 px-4 py-2.5" style={{ backgroundColor: 'hsl(var(--muted))', borderBottom: '1px solid hsl(var(--border))' }}>
              <Zap size={13} style={{ color: 'hsl(var(--primary))' }} />
              <span className="text-xs font-semibold" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('auth.demoCredentials', 'Demo Credentials')} — {t('auth.clickToAutoFill', 'click to auto-fill')}</span>
            </div>
            <div className="p-3 space-y-2" style={{ backgroundColor: 'hsl(var(--background))' }}>
              {DEMO_ACCOUNTS.map(account => (
                <button
                  key={account.label}
                  type="button"
                  onClick={() => handleDemoLogin(account)}
                  className="w-full text-left rounded-lg px-3 py-2.5 transition-all hover:opacity-90 active:scale-[0.99]"
                  style={{ backgroundColor: account.bg, border: `1px solid ${account.border}` }}
                >
                  <div className="flex items-center justify-between">
                    <span className="text-xs font-bold" style={{ color: account.color }}>{account.label}</span>
                    <span className="text-xs font-medium px-2 py-0.5 rounded-full" style={{ backgroundColor: account.color, color: '#fff' }}>{t('common.use', 'Use')}</span>
                  </div>
                  <div className="mt-1 space-y-0.5">
                    <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      <span className="font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('auth.email', 'Email')}:</span> {account.email}
                    </p>
                    <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      <span className="font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('auth.password', 'Password')}:</span> {account.password}
                    </p>
                  </div>
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
