'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Eye, EyeOff, Smartphone, Lock, ShieldCheck } from 'lucide-react';
import { apiRequest, clearTokens, setCurrentUser } from '../../../lib/api';
import { Button } from '../../../components/Button';

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

export default function OpsLoginPage() {
  const router = useRouter();
  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);

  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 }),
      });
      const user = response.data.user;
      if (!STAFF_ROLES.has(user.role)) {
        clearTokens();
        try {
          await apiRequest('/auth/logout', { method: 'POST', body: '{}' });
        } catch {
          /* ignore */
        }
        setError('Player accounts sign in at the customer login.');
        return;
      }
      setCurrentUser(user);
      if (user.role === 'SCORER') router.push('/scorer');
      else router.push('/admin');
    } catch (err: any) {
      setError(err.message || 'Login failed.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex min-h-[100dvh] flex-col bg-[#090a0f]">
      <div className="mx-auto flex w-full max-w-md flex-1 flex-col justify-center px-5 py-10">
        <div className="mb-8 text-center">
          <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-xl border border-zinc-800 bg-zinc-900 text-emerald-400">
            <ShieldCheck className="h-6 w-6" />
          </div>
          <h1 className="text-2xl font-extrabold tracking-tight text-white">
            Staff <span className="text-emerald-400">login</span>
          </h1>
          <p className="mt-2 text-sm text-zinc-400">Admin panel and scorer console. Mobile + password only.</p>
        </div>

        {error && (
          <div className="mb-4 rounded-xl border border-rose-500/30 bg-rose-500/10 px-3.5 py-3 text-sm text-rose-300" role="alert">
            {error}
            {error.includes('customer login') && (
              <Link href="/login" className="mt-1 block font-semibold text-emerald-400 underline">
                Go to player login
              </Link>
            )}
          </div>
        )}

        <form onSubmit={handleLogin} className="space-y-4 rounded-2xl border border-zinc-800 bg-zinc-900/80 p-5">
          <label className="block text-xs font-semibold text-zinc-400">
            Mobile number
            <div className="mt-1.5 flex overflow-hidden rounded-xl border border-zinc-700 bg-zinc-950 focus-within:border-emerald-500">
              <span className="flex items-center gap-1.5 border-r border-zinc-800 bg-zinc-900 px-3 text-sm font-semibold text-zinc-400">
                <Smartphone className="h-3.5 w-3.5" />
                +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-white outline-none placeholder:text-zinc-600"
              />
            </div>
          </label>

          <label className="block text-xs font-semibold text-zinc-400">
            Password
            <div className="relative mt-1.5">
              <Lock className="pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-500" />
              <input
                required
                type={showPw ? 'text' : 'password'}
                autoComplete="current-password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="Enter password"
                className="w-full rounded-xl border border-zinc-700 bg-zinc-950 py-3 pl-10 pr-11 text-sm text-white outline-none placeholder:text-zinc-600 focus:border-emerald-500"
              />
              <button
                type="button"
                onClick={() => setShowPw((v) => !v)}
                className="absolute right-3 top-1/2 -translate-y-1/2 rounded-md p-1 text-zinc-500 hover:text-zinc-200"
                aria-label={showPw ? 'Hide password' : 'Show password'}
              >
                {showPw ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
          </label>

          <Button type="submit" loading={loading} className="w-full rounded-xl bg-emerald-600 text-sm font-bold hover:bg-emerald-500">
            Sign in to ops
          </Button>
        </form>

        <p className="mt-6 text-center text-xs text-zinc-500">
          Player?{' '}
          <Link href="/login" className="font-semibold text-emerald-400 hover:underline">
            Use customer login
          </Link>
          {' · '}
          <Link href="/ops" className="hover:underline">
            Ops home
          </Link>
        </p>
      </div>
    </div>
  );
}
