"use client";

import { useMemo, useState } from "react";
import { Eye, EyeOff } from "lucide-react";

type Strength = {
  key: "debil" | "aceptable" | "segura" | "muy-segura";
  label: string;
  score: number;
  hint: string;
};

export function passwordStrength(password: string): Strength {
  if (!password) {
    return { key: "debil", label: "Escribe una contraseña", score: 0, hint: "Mínimo 8 caracteres." };
  }
  const length = password.length;
  const hasLower = /[a-z]/.test(password);
  const hasUpper = /[A-Z]/.test(password);
  const hasNumber = /\d/.test(password);
  const hasSymbol = /[^A-Za-z0-9]/.test(password);
  const variety = [hasLower, hasUpper, hasNumber, hasSymbol].filter(Boolean).length;

  if (length >= 12 && variety >= 3) {
    return { key: "muy-segura", label: "Muy segura", score: 4, hint: "Excelente. Esta clave es fuerte." };
  }
  if (length >= 8 && variety >= 3) {
    return { key: "segura", label: "Segura", score: 3, hint: "Buena. Añade más caracteres para hacerla muy segura." };
  }
  if (length >= 8 && variety >= 2) {
    return { key: "aceptable", label: "Aceptable", score: 2, hint: "Mejor si mezclas mayúsculas, números y un símbolo." };
  }
  return {
    key: "debil",
    label: "Débil",
    score: 1,
    hint: length < 8 ? "Usa al menos 8 caracteres." : "Combina letras, números y un símbolo.",
  };
}

const barColor: Record<Strength["key"], string> = {
  debil: "bg-red-700",
  aceptable: "bg-ot-gold",
  segura: "bg-ot-green-soft",
  "muy-segura": "bg-ot-green",
};

const textColor: Record<Strength["key"], string> = {
  debil: "text-red-700",
  aceptable: "text-ot-gold",
  segura: "text-ot-green",
  "muy-segura": "text-ot-green",
};

export function PasswordField({
  name,
  placeholder,
  autoComplete,
  showStrength = false,
  value,
  onChange,
  inputClassName,
}: {
  name: string;
  placeholder: string;
  autoComplete?: string;
  showStrength?: boolean;
  value: string;
  onChange: (value: string) => void;
  inputClassName?: string;
}) {
  const [visible, setVisible] = useState(false);
  const strength = useMemo(() => passwordStrength(value), [value]);

  return (
    <div>
      <div className="relative">
        <input
          name={name}
          type={visible ? "text" : "password"}
          autoComplete={autoComplete}
          required
          minLength={8}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
          className={
            inputClassName
              ? `${inputClassName} pr-12`
              : "w-full border border-black/15 bg-white px-4 py-3 pr-12 text-sm outline-none focus:border-ot-green"
          }
        />
        <button
          type="button"
          onClick={() => setVisible((v) => !v)}
          className="absolute right-3 top-1/2 -translate-y-1/2 text-ot-muted hover:text-ot-green"
          aria-label={visible ? "Ocultar contraseña" : "Ver contraseña"}
        >
          {visible ? <EyeOff size={18} /> : <Eye size={18} />}
        </button>
      </div>
      {showStrength && value.length > 0 && (
        <div className="mt-2">
          <div className="flex gap-1">
            {[1, 2, 3, 4].map((n) => (
              <span
                key={n}
                className={`h-1 flex-1 ${n <= strength.score ? barColor[strength.key] : "bg-black/10"}`}
              />
            ))}
          </div>
          <p className={`mt-1.5 text-xs ${textColor[strength.key]}`}>
            {strength.label}. {strength.hint}
          </p>
        </div>
      )}
    </div>
  );
}
