"use client";

import {
  AlertCircle,
  ArrowRight,
  CheckCircle2,
  Eye,
  EyeOff,
  Loader2,
  LockKeyhole,
  Mail,
  ShieldAlert,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { loginUser, getSessionToken, getSessionUser, logoutUser } from "@/services/auth-service";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";

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

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);

  const [isLoading, setIsLoading] = useState(false);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [successMsg, setSuccessMsg] = useState<string | null>(null);

  // Redireciona para o painel se já há sessão ativa de SUPERADMIN
  useEffect(() => {
    const user = getSessionUser();
    if (getSessionToken() && user?.role === "SUPERADMIN") {
      router.replace("/admin");
    }
  }, [router]);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMsg(null);
    setSuccessMsg(null);

    if (!email.trim() || !password.trim()) {
      setErrorMsg("Por favor, preencha o e-mail e a senha.");
      return;
    }

    setIsLoading(true);
    try {
      const response = await loginUser({ email, password });
      
      if (response.user?.role !== "SUPERADMIN" && response.user?.role !== "OWNER" && response.user?.role !== "ADMIN") {
        // Se o usuário não for admin, limpar a sessão criada e emitir erro
        logoutUser();
        throw new Error("Acesso negado. Apenas administradores autorizados podem acessar esta área.");
      }

      setSuccessMsg("Autenticação SaaS master realizada! Acessando painel...");
      setTimeout(() => {
        router.push("/admin");
      }, 800);
    } catch (err: any) {
      setErrorMsg(err.message || "Erro ao efetuar login. Verifique suas credenciais.");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <main className="grid min-h-screen bg-slate-950 lg:grid-cols-[0.9fr_1.1fr] text-slate-100">
      {/* Seção Esquerda: Formulário de Autenticação */}
      <section className="flex items-center justify-center px-6 py-10 bg-slate-900/40 backdrop-blur-md">
        <div className="w-full max-w-md space-y-6">
          {/* Logo e Título */}
          <div>
            <div className="flex items-center gap-3">
              <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-blue-600 text-xl font-black text-white shadow-md shadow-blue-500/20">
                BL
              </div>
              <div>
                <h2 className="text-xl font-bold tracking-tight text-white">BlackLoc</h2>
                <p className="text-xs text-blue-400 font-semibold uppercase tracking-wider">SaaS Master Controller</p>
              </div>
            </div>
            <h1 className="mt-8 text-2xl font-bold tracking-tight text-white sm:text-3xl">
              Painel de Controle
            </h1>
            <p className="mt-1.5 text-sm text-slate-400">
              Faça login para gerenciar empresas contratantes, licenças e transmissões globais.
            </p>
          </div>

          {/* Banner de Mensagem de Erro / Sucesso */}
          {errorMsg && (
            <div className="flex items-center gap-2.5 rounded-lg border border-rose-500/30 bg-rose-500/10 p-3 text-xs font-medium text-rose-400">
              <AlertCircle className="h-4 w-4 shrink-0" />
              <span>{errorMsg}</span>
            </div>
          )}

          {successMsg && (
            <div className="flex items-center gap-2.5 rounded-lg border border-emerald-500/30 bg-emerald-500/10 p-3 text-xs font-medium text-emerald-400">
              <CheckCircle2 className="h-4 w-4 shrink-0" />
              <span>{successMsg}</span>
            </div>
          )}

          {/* Card do Formulário */}
          <Card className="p-6 shadow-2xl border-slate-800 bg-slate-900 text-slate-100">
            <form onSubmit={handleLogin} className="space-y-4" autoComplete="off">
              {/* E-mail */}
              <div>
                <label className="mb-1.5 block text-xs font-semibold text-slate-300">
                  E-mail do Administrador SaaS *
                </label>
                <div className="relative">
                  <Mail className="pointer-events-none absolute left-3 top-3 h-4 w-4 text-slate-500" />
                  <Input
                    type="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="pl-9 text-sm bg-slate-950 border-slate-800 text-white placeholder-slate-600 focus-visible:ring-blue-500"
                    placeholder="superadmin@rentx.local"
                    autoComplete="one-time-code"
                    required
                  />
                </div>
              </div>

              {/* Senha */}
              <div>
                <label className="mb-1.5 block text-xs font-semibold text-slate-300">
                  Senha Master *
                </label>
                <div className="relative">
                  <LockKeyhole className="pointer-events-none absolute left-3 top-3 h-4 w-4 text-slate-500" />
                  <Input
                    type={showPassword ? "text" : "password"}
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="pl-9 pr-10 text-sm bg-slate-950 border-slate-800 text-white placeholder-slate-600 focus-visible:ring-blue-500"
                    placeholder="Digite sua senha"
                    autoComplete="new-password"
                    required
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 top-3 text-slate-500 hover:text-slate-300"
                    title={showPassword ? "Ocultar senha" : "Exibir senha"}
                  >
                    {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </button>
                </div>
              </div>

              {/* Botões de Ação */}
              <Button type="submit" disabled={isLoading} className="w-full h-11 text-sm font-semibold bg-blue-600 hover:bg-blue-500 text-white shadow-lg shadow-blue-600/20">
                {isLoading ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" /> Autenticando...
                  </>
                ) : (
                  <>
                    Entrar no Painel Master <ArrowRight className="ml-2 h-4 w-4" />
                  </>
                )}
              </Button>
            </form>
          </Card>
        </div>
      </section>

      {/* Seção Direita: Painel Visual com Imagem Industrial */}
      <section className="relative hidden overflow-hidden bg-slate-950 lg:block">
        <img
          src="https://images.unsplash.com/photo-1486406146926-c627a92ad1ab?auto=format&fit=crop&w=1400&q=80"
          alt="Corporative high-tech building architecture"
          className="h-full w-full object-cover opacity-30 transition-transform duration-700 hover:scale-105"
        />
        <div className="absolute inset-0 bg-gradient-to-t from-slate-950 via-slate-950/50 to-slate-950/20" />

        <div className="absolute bottom-12 left-12 right-12 text-white space-y-6">
          <div className="inline-flex items-center gap-2 rounded-full border border-blue-500/30 bg-blue-600/20 px-3.5 py-1 text-xs font-semibold tracking-wider uppercase text-blue-300 backdrop-blur-md">
            <ShieldAlert className="h-4 w-4 text-blue-400" /> SaaS Administration Node
          </div>

          <h2 className="max-w-xl text-3xl font-extrabold leading-tight tracking-tight sm:text-4xl text-white">
            Área de monitoramento, controle de licenças e faturamento global do ERP.
          </h2>

          <p className="max-w-lg text-sm text-slate-400 leading-relaxed">
            O acesso a este ambiente é restrito apenas a operadores autorizados da RentX. Todas as atividades realizadas são gravadas no log de auditoria global.
          </p>
        </div>
      </section>
    </main>
  );
}
