'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Eye, EyeOff, Smartphone, Lock } from 'lucide-react';
import { apiRequest, clearTokens, setCurrentUser, getCurrentUser } from '../../../lib/api';
import { safeNextPath } from '../../../lib/authRedirect';
import { Button } from '../../../components/Button';
import { AuthShell, AuthField, AuthError } from '../../../components/AuthShell';

const STAFF_ROLES = new Set(['SUPER_ADMIN', 'ADMIN', 'SCORER']);

/** Customer password login only — OTP login hidden until re-enabled. */
export default function LoginPage() {
  const router = useRouter();
  const [nextPath, setNextPath] = useState('/');
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [showPw, setShowPw] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const q = new URLSearchParams(window.location.search).get('next');
    const next = safeNextPath(q, '/');
    setNextPath(next);
    if (getCurrentUser()) router.replace(next);
  }, [router]);

  const rejectIfStaff = async (user: any) => {
    if (!STAFF_ROLES.has(user.role)) return false;
    clearTokens();
    try {
      await apiRequest('/auth/logout', { method: 'POST', body: '{}' });
    } catch {
      /* ignore */
    }
    setError('Admin and scorer accounts sign in at the staff login.');
    return true;
  };

  const cleanPhone = phone.replace(/\D/g, '');

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    if (cleanPhone.length < 10) {
      setError('Enter a valid 10-digit mobile number.');
      return;
    }
    setLoading(true);
    try {
      const response = await apiRequest('/auth/login', {
        method: 'POST',
        body: JSON.stringify({ phone: cleanPhone, password }),
      });
      if (await rejectIfStaff(response.data.user)) return;
      setCurrentUser(response.data.user);
      router.push(nextPath);
    } catch (err: any) {
      setError(err.message || 'Login failed.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <AuthShell title="Welcome back" subtitle="Login with your mobile number and password to play contests.">
      {error && (
        <div className="mb-4">
          <AuthError message={error} />
          {error.includes('staff login') && (
            <p className="mt-2 text-center text-xs">
              <Link href="/ops/login" className="font-bold text-d11-red hover:underline">
                Go to staff login
              </Link>
            </p>
          )}
        </div>
      )}

      <form onSubmit={handleLogin} className="space-y-4">
        <AuthField label="Mobile number">
          <div className="flex overflow-hidden rounded-xl border border-gray-300 bg-white focus-within:border-d11-red focus-within:ring-2 focus-within:ring-d11-red/20">
            <span className="flex items-center gap-1.5 border-r border-gray-200 bg-gray-50 px-3 text-sm font-semibold text-gray-600">
              <Smartphone className="h-3.5 w-3.5 text-d11-muted" />
              +91
            </span>
            <input
              required
              inputMode="numeric"
              autoComplete="tel"
              maxLength={10}
              value={phone}
              onChange={(e) => setPhone(e.target.value.replace(/\D/g, '').slice(0, 10))}
              placeholder="10-digit number"
              className="min-w-0 flex-1 border-0 bg-transparent px-3.5 py-3 text-sm text-d11-ink outline-none placeholder:text-gray-400"
            />
          </div>
        </AuthField>

        <AuthField label="Password">
          <div className="relative">
            <Lock className="pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
            <input
              required
              type={showPw ? 'text' : 'password'}
              autoComplete="current-password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="Enter password"
              className="d11-input pl-10 pr-11"
            />
            <button
              type="button"
              onClick={() => setShowPw((v) => !v)}
              className="absolute right-3 top-1/2 -translate-y-1/2 rounded-md p-1 text-gray-400 hover:text-gray-700"
              aria-label={showPw ? 'Hide password' : 'Show password'}
            >
              {showPw ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
            </button>
          </div>
        </AuthField>

        <Button type="submit" loading={loading} className="w-full rounded-xl text-sm font-bold">
          Continue to play
        </Button>
      </form>

      <p className="mt-6 text-center text-sm text-gray-500">
        New to MY11s?{' '}
        <Link href="/register" className="font-bold text-d11-red hover:underline">
          Create account
        </Link>
      </p>
    </AuthShell>
  );
}
