"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { useLocale, useTranslations } from "next-intl"
import { Eye, EyeOff, AlertCircle, Loader2 } from "lucide-react"

import { login } from "@/src/lib/api/auth"
import { tokenStorage } from "@/src/lib/api/storage"
import { useAuth } from "@/src/features/auth/auth-context"

// Couleurs extraites du logo ACX
const NAVY = "#1a3578"
const TEAL  = "#4dba96"

export function LoginForm({
  mode = "tenant",
  theme = "light",
}: {
  mode?: "tenant" | "admin"
  theme?: "light" | "dark"
}) {
  const router = useRouter()
  const locale = useLocale()
  const t = useTranslations("auth")
  const { refreshMe } = useAuth()

  const isDark = theme === "dark"

  const [username, setUsername] = useState("")
  const [password, setPassword] = useState("")
  const [showPwd, setShowPwd] = useState(false)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault()
    setError(null)

    if (!username.trim() || !password) {
      setError(t("error_generic"))
      return
    }

    setLoading(true)
    try {
      const tokens = await login(username.trim(), password)
      tokenStorage.setTokens(tokens.access, tokens.refresh)
      await refreshMe()

      const raw = localStorage.getItem("acx_me")
      const me = raw ? JSON.parse(raw) : null

      if (mode === "admin") {
        if (!me?.is_superuser) {
          tokenStorage.clear()
          setError(t("error_not_superuser"))
          return
        }
        router.replace(`/${locale}/admin`)
        return
      }

      if (me?.must_change_password) {
        router.replace(`/${locale}/change-password`)
      } else if (me?.is_superuser) {
        router.replace(`/${locale}/admin`)
      } else {
        router.replace(`/${locale}/dashboard`)
      }
    } catch (err: any) {
      setError(err?.message ?? t("error_generic"))
    } finally {
      setLoading(false)
    }
  }

  const inputBg      = isDark ? "rgba(255,255,255,0.07)" : "#ffffff"
  const inputBorder  = isDark ? "rgba(255,255,255,0.14)" : "#e2e8f0"
  const inputColor   = isDark ? "#ffffff" : "#0f172a"
  const labelColor   = isDark ? "rgba(255,255,255,0.40)" : "#94a3b8"
  const eyeColor     = isDark ? "rgba(255,255,255,0.40)" : "#94a3b8"
  const eyeHoverColor = isDark ? "rgba(255,255,255,0.75)" : "#475569"

  const inputClass = `
    w-full rounded-2xl border px-4 py-3.5 text-[15px]
    placeholder:text-slate-400 outline-none
    transition-all duration-150
    disabled:cursor-not-allowed disabled:opacity-50
  `

  function inputStyle(extra?: React.CSSProperties): React.CSSProperties {
    return {
      background: inputBg,
      borderColor: inputBorder,
      color: inputColor,
      ...extra,
    }
  }

  return (
    <form onSubmit={onSubmit} noValidate className="space-y-5">

      {/* Erreur */}
      {error && (
        <div
          className="flex items-start gap-3 rounded-2xl px-4 py-3.5 text-sm ring-1"
          style={isDark
            ? { background: "rgba(239,68,68,0.10)", borderColor: "rgba(239,68,68,0.25)", color: "#fca5a5" }
            : { background: "#fef2f2", borderColor: "#fee2e2", color: "#b91c1c" }}
        >
          <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />
          <span className="leading-snug">{error}</span>
        </div>
      )}

      {/* Username */}
      <div className="space-y-2">
        <label
          htmlFor="acx-username"
          className="block text-[11px] font-semibold uppercase tracking-widest"
          style={{ color: labelColor }}
        >
          {t("username_placeholder")}
        </label>
        <input
          id="acx-username"
          type="text"
          autoComplete="username"
          spellCheck={false}
          value={username}
          onChange={(e) => setUsername(e.target.value)}
          disabled={loading}
          placeholder={t("username_hint")}
          className={inputClass}
          style={inputStyle()}
          onFocus={(e) => {
            e.currentTarget.style.borderColor = TEAL
            e.currentTarget.style.boxShadow = `0 0 0 4px rgba(77,186,150,0.15)`
          }}
          onBlur={(e) => {
            e.currentTarget.style.borderColor = inputBorder
            e.currentTarget.style.boxShadow = ""
          }}
        />
      </div>

      {/* Password */}
      <div className="space-y-2">
        <label
          htmlFor="acx-password"
          className="block text-[11px] font-semibold uppercase tracking-widest"
          style={{ color: labelColor }}
        >
          {t("password_placeholder")}
        </label>
        <div className="relative">
          <input
            id="acx-password"
            type={showPwd ? "text" : "password"}
            autoComplete="current-password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            disabled={loading}
            placeholder="••••••••"
            className={`${inputClass} pr-14`}
            style={inputStyle()}
            onFocus={(e) => {
              e.currentTarget.style.borderColor = TEAL
              e.currentTarget.style.boxShadow = `0 0 0 4px rgba(77,186,150,0.15)`
            }}
            onBlur={(e) => {
              e.currentTarget.style.borderColor = inputBorder
              e.currentTarget.style.boxShadow = ""
            }}
          />
          <button
            type="button"
            tabIndex={-1}
            onClick={() => setShowPwd((v) => !v)}
            aria-label={showPwd ? t("hide_password") : t("show_password")}
            className="absolute right-4 top-1/2 -translate-y-1/2 transition focus:outline-none"
            style={{ color: eyeColor }}
            onMouseEnter={(e) => { e.currentTarget.style.color = eyeHoverColor }}
            onMouseLeave={(e) => { e.currentTarget.style.color = eyeColor }}
          >
            {showPwd
              ? <EyeOff className="h-[18px] w-[18px]" />
              : <Eye    className="h-[18px] w-[18px]" />
            }
          </button>
        </div>
      </div>

      {/* Bouton */}
      <button
        type="submit"
        disabled={loading}
        className="
          mt-2 flex w-full items-center justify-center gap-2.5
          rounded-2xl py-3.5 text-[15px] font-semibold text-white
          transition-all duration-150 active:scale-[0.98]
          disabled:cursor-not-allowed disabled:opacity-70
          focus:outline-none
        "
        style={{
          background: isDark
            ? `linear-gradient(135deg, #2d9073 0%, #4dba96 100%)`
            : `linear-gradient(135deg, ${NAVY} 0%, #1e4494 100%)`,
          boxShadow: isDark
            ? `0 4px 24px rgba(77,186,150,0.30)`
            : `0 4px 24px rgba(26,53,120,0.25)`,
        }}
        onMouseEnter={(e) => {
          e.currentTarget.style.boxShadow = isDark
            ? `0 6px 28px rgba(77,186,150,0.45)`
            : `0 6px 28px rgba(26,53,120,0.38)`
          e.currentTarget.style.transform = "translateY(-1px)"
        }}
        onMouseLeave={(e) => {
          e.currentTarget.style.boxShadow = isDark
            ? `0 4px 24px rgba(77,186,150,0.30)`
            : `0 4px 24px rgba(26,53,120,0.25)`
          e.currentTarget.style.transform = ""
        }}
      >
        {loading ? (
          <>
            <Loader2 className="h-4 w-4 animate-spin" />
            {t("loading")}
          </>
        ) : (
          t("submit")
        )}
      </button>

      {/* Barre décorative sous le bouton */}
      <div className="flex items-center gap-2 pt-1">
        <div className="h-0.5 flex-1 rounded-full" style={{ background: `${TEAL}22` }} />
        <div className="h-1.5 w-1.5 rounded-full" style={{ backgroundColor: TEAL, opacity: 0.4 }} />
        <div className="h-0.5 flex-1 rounded-full" style={{ background: `${TEAL}22` }} />
      </div>
    </form>
  )
}
