"use client";

import { useState } from "react";
import { Eye, EyeOff, Lock } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

type PasswordStrength = { level: 0 | 1 | 2; label: "Weak" | "Fair" | "Strong" };

export function getPasswordStrength(pw: string): PasswordStrength {
  if (!pw || pw.length < 8) return { level: 0, label: "Weak" };
  const hasUpper = /[A-Z]/.test(pw);
  const hasLower = /[a-z]/.test(pw);
  const hasNumber = /\d/.test(pw);
  if (pw.length >= 12 && hasUpper && hasLower && hasNumber) {
    return { level: 2, label: "Strong" };
  }
  return { level: 1, label: "Fair" };
}

const strengthColors = ["bg-red-500", "bg-amber-500", "bg-emerald-500"];

type PasswordFieldsProps = {
  password: string;
  onPasswordChange: (value: string) => void;
  confirmPassword?: string;
  onConfirmChange?: (value: string) => void;
  passwordLabel?: string;
  confirmLabel?: string;
  passwordPlaceholder?: string;
  confirmPlaceholder?: string;
  passwordId?: string;
  confirmId?: string;
  disabled?: boolean;
  required?: boolean;
  showStrengthMeter?: boolean;
  showConfirmField?: boolean;
  autoComplete?: "new-password" | "current-password";
};

export function PasswordFields({
  password,
  onPasswordChange,
  confirmPassword = "",
  onConfirmChange,
  passwordLabel = "Password",
  confirmLabel = "Confirm Password",
  passwordPlaceholder = "Min 8 characters",
  confirmPlaceholder = "Confirm your password",
  passwordId = "password",
  confirmId = "confirmPassword",
  disabled = false,
  required = true,
  showStrengthMeter = true,
  showConfirmField = true,
  autoComplete = "new-password",
}: PasswordFieldsProps) {
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);

  const strength = getPasswordStrength(password);
  const showStrength = showStrengthMeter && password.length > 0;

  return (
    <>
      <div className="space-y-2">
        <Label htmlFor={passwordId}>{passwordLabel}</Label>
        <div className="relative">
          <Lock className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            id={passwordId}
            type={showPassword ? "text" : "password"}
            placeholder={passwordPlaceholder}
            value={password}
            onChange={(e) => onPasswordChange(e.target.value)}
            required={required}
            minLength={8}
            autoComplete={autoComplete}
            disabled={disabled}
            className="pl-10 pr-10"
          />
          <button
            type="button"
            tabIndex={-1}
            onClick={() => setShowPassword((v) => !v)}
            className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
            aria-label={showPassword ? "Hide password" : "Show password"}
          >
            {showPassword ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
          </button>
        </div>
        {showStrength && (
          <div className="flex items-center gap-2">
            <div className="flex flex-1 gap-1">
              {[0, 1, 2].map((i) => (
                <div
                  key={i}
                  className={`h-1 flex-1 rounded-full transition-colors ${
                    i <= strength.level ? strengthColors[strength.level] : "bg-muted"
                  }`}
                />
              ))}
            </div>
            <span className="text-[10px] text-muted-foreground">{strength.label}</span>
          </div>
        )}
      </div>

      {showConfirmField && (
        <div className="space-y-2">
          <Label htmlFor={confirmId}>{confirmLabel}</Label>
          <div className="relative">
            <Lock className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              id={confirmId}
              type={showConfirm ? "text" : "password"}
              placeholder={confirmPlaceholder}
              value={confirmPassword}
              onChange={(e) => onConfirmChange?.(e.target.value)}
              required={required}
              minLength={8}
              autoComplete="new-password"
              disabled={disabled}
              className="pl-10 pr-10"
            />
            <button
              type="button"
              tabIndex={-1}
              onClick={() => setShowConfirm((v) => !v)}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
              aria-label={showConfirm ? "Hide password" : "Show password"}
            >
              {showConfirm ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
            </button>
          </div>
        </div>
      )}
    </>
  );
}
