"use client"

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

import { customerPortalLogin } from "@/src/lib/api/customer-portal-auth"

// Palette logo ACX — portail client (teal)
const TEAL      = "#3aaa87"
const TEAL_MID  = "#2d9073"
const TEAL_DEEP = "#1f7560"

export function ClientLoginForm() {
  const locale      = useLocale()
  const router      = useRouter()
  const pathname    = usePathname()
  const searchParams = useSearchParams()
  const t = useTranslations("clientPortalAuth")

  const [username, setUsername] = useState("")
  const [password, setPassword] = useState("")
  const [showPwd, setShowPwd]   = useState(false)
  const [busy, setBusy]         = useState(false)
  const [err, setErr]           = useState<string | null>(null)

  // Supprime ?reason=... de l'URL sans recharger la page
  function clearReasonParam() {
    if (!searchParams.get("reason")) return
    router.replace(pathname, { scroll: false })
  }

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

    const u = username.trim()
    if (!u || !password) {
      setErr(t("credentialsRequired"))
      return
    }

    setBusy(true)
    try {
      const result = await customerPortalLogin({ username: u, password })
      if (result.must_change_password) {
        router.replace(`/${locale}/client/change-password`)
      } else {
        router.replace(`/${locale}/client/dashboard`)
      }
    } catch (e: any) {
      setErr(e?.message || t("loginFailed"))
    } finally {
      setBusy(false)
    }
  }

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

      {/* Erreur */}
      {err && (
        <div className="flex items-start gap-3 rounded-2xl border border-red-100 bg-red-50 px-4 py-3.5 text-sm text-red-700">
          <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />
          <span className="leading-snug">{err}</span>
        </div>
      )}

      {/* Username */}
      <div className="space-y-2">
        <label
          htmlFor="cp-username"
          className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400"
        >
          {t("usernameLabel")}
        </label>
        <input
          id="cp-username"
          type="text"
          autoComplete="username"
          spellCheck={false}
          value={username}
          onChange={(e) => setUsername(e.target.value)}
          disabled={busy}
          placeholder={t("usernamePlaceholder")}
          className="
            w-full rounded-2xl border border-slate-200 bg-white
            px-4 py-3.5 text-[15px] text-slate-900
            placeholder:text-slate-400 outline-none
            transition-all duration-150
            hover:border-slate-300
            disabled:cursor-not-allowed disabled:opacity-50
          "
          onFocus={(e) => {
            e.currentTarget.style.borderColor = TEAL
            e.currentTarget.style.boxShadow = `0 0 0 4px rgba(58,170,135,0.14)`
          }}
          onBlur={(e) => {
            e.currentTarget.style.borderColor = ""
            e.currentTarget.style.boxShadow = ""
          }}
        />
      </div>

      {/* Password */}
      <div className="space-y-2">
        <label
          htmlFor="cp-password"
          className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400"
        >
          {t("passwordLabel")}
        </label>
        <div className="relative">
          <input
            id="cp-password"
            type={showPwd ? "text" : "password"}
            autoComplete="current-password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            disabled={busy}
            placeholder="••••••••"
            className="
              w-full rounded-2xl border border-slate-200 bg-white
              px-4 py-3.5 pr-14 text-[15px] text-slate-900
              placeholder:text-slate-400 outline-none
              transition-all duration-150
              hover:border-slate-300
              disabled:cursor-not-allowed disabled:opacity-50
            "
            onFocus={(e) => {
              e.currentTarget.style.borderColor = TEAL
              e.currentTarget.style.boxShadow = `0 0 0 4px rgba(58,170,135,0.14)`
            }}
            onBlur={(e) => {
              e.currentTarget.style.borderColor = ""
              e.currentTarget.style.boxShadow = ""
            }}
          />
          <button
            type="button"
            tabIndex={-1}
            onClick={() => setShowPwd((v) => !v)}
            aria-label={showPwd ? t("hidePassword") : t("showPassword")}
            className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 transition hover:text-slate-600 focus:outline-none"
          >
            {showPwd
              ? <EyeOff className="h-[18px] w-[18px]" />
              : <Eye    className="h-[18px] w-[18px]" />
            }
          </button>
        </div>
      </div>

      {/* Bouton */}
      <button
        type="submit"
        disabled={busy}
        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: `linear-gradient(135deg, ${TEAL_DEEP} 0%, ${TEAL_MID} 60%, ${TEAL} 100%)`,
          boxShadow: `0 4px 24px rgba(45,144,115,0.28)`,
        }}
        onMouseEnter={(e) => {
          e.currentTarget.style.boxShadow = `0 6px 28px rgba(45,144,115,0.42)`
          e.currentTarget.style.transform = "translateY(-1px)"
        }}
        onMouseLeave={(e) => {
          e.currentTarget.style.boxShadow = `0 4px 24px rgba(45,144,115,0.28)`
          e.currentTarget.style.transform = ""
        }}
      >
        {busy ? (
          <>
            <Loader2 className="h-4 w-4 animate-spin" />
            {t("signingIn")}
          </>
        ) : (
          t("signIn")
        )}
      </button>

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