import * as React from "react";
import { Check, X } from "lucide-react";
import { Popover as PopoverPrimitive } from "@base-ui/react/popover";
import { cn } from "@/lib/utils";
import { useThemeVars } from "@/lib/theme-provider";

export type PasswordStrengthRule = {
  label: string;
  test: (p: string) => boolean;
};

export const PASSWORD_STRENGTH_RULES: PasswordStrengthRule[] = [
  { label: "Minimum 8 characters", test: (p) => p.length >= 8 },
  { label: "At least one uppercase letter", test: (p) => /[A-Z]/.test(p) },
  { label: "At least one lowercase letter", test: (p) => /[a-z]/.test(p) },
  { label: "At least one number", test: (p) => /\d/.test(p) },
  {
    label: "At least one special character",
    test: (p) => /[^A-Za-z0-9]/.test(p),
  },
];

export type PasswordStrengthTooltipProps = {
  open?: boolean;
  password: string;
  children: React.ReactNode;
  side?: "top" | "right" | "bottom" | "left";
  onRequestClose?: () => void;
};

export const PasswordStrengthTooltip = React.forwardRef<
  HTMLDivElement,
  PasswordStrengthTooltipProps
>(function PasswordStrengthTooltip(
  { open = false, password, children, side = "right" },
  forwardedRef
) {
  const themeVars = useThemeVars();
  // anchorRef is used by Positioner for popup placement.
  // forwardedRef (fieldRef from consumer) is used for contains() checks in dismiss logic.
  const anchorRef = React.useRef<HTMLDivElement>(null);

  const composedRef = React.useCallback(
    (node: HTMLDivElement | null) => {
      (anchorRef as React.MutableRefObject<HTMLDivElement | null>).current =
        node;
      if (typeof forwardedRef === "function") {
        forwardedRef(node);
      } else if (forwardedRef) {
        (
          forwardedRef as React.MutableRefObject<HTMLDivElement | null>
        ).current = node;
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [forwardedRef]
  );

  return (
    // PopoverPrimitive.Root with no Trigger — popup is fully controlled via `open` prop.
    // The wrapper div has no trigger behaviors injected, so clicking the input inside
    // works on the first click without interference.
    <PopoverPrimitive.Root open={open}>
      <div ref={composedRef}>{children}</div>
      <PopoverPrimitive.Portal>
        <PopoverPrimitive.Positioner
          anchor={anchorRef}
          side={side}
          align="start"
          sideOffset={8}
          className="z-[200]"
        >
          <PopoverPrimitive.Popup
            initialFocus={false}
            finalFocus={false}
            className={cn(
              "border border-border bg-popover shadow-md outline-hidden",
              "w-auto max-w-[280px] p-3 font-sans",
              "data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2",
              "data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
              "data-ending-style:animate-out data-ending-style:fade-out-0 data-ending-style:zoom-out-95 data-ending-style:fill-mode-forwards",
              "data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95"
            )}
            style={themeVars as React.CSSProperties}
          >
            <div className="flex flex-col gap-1.5">
              {PASSWORD_STRENGTH_RULES.map((rule) => {
                const valid = password ? rule.test(password) : false;
                return (
                  <div
                    key={rule.label}
                    className={cn(
                      "flex items-center gap-1.5 text-[13px] leading-[18px]",
                      valid ? "text-success" : "text-destructive"
                    )}
                  >
                    {valid ? (
                      <Check size={14} className="shrink-0" />
                    ) : (
                      <X size={14} className="shrink-0" />
                    )}
                    <span>{rule.label}</span>
                  </div>
                );
              })}
            </div>
          </PopoverPrimitive.Popup>
        </PopoverPrimitive.Positioner>
      </PopoverPrimitive.Portal>
    </PopoverPrimitive.Root>
  );
});
