import { LogOut, Settings } from "lucide-react";
import type { ReactNode } from "react";
import { cn } from "../lib/cn";
import { initials } from "../lib/format";
import { NodeDcDropdown } from "./Dropdown";

interface NodeDcProfileMenuUser {
  name: string;
  email: string;
  avatarUrl?: string | null;
}

interface NodeDcProfileMenuProps {
  user: NodeDcProfileMenuUser;
  coverUrl?: string;
  trigger: (api: { open: boolean; toggle: () => void; setTriggerRef: (node: HTMLElement | null) => void }) => ReactNode;
  className?: string;
  onLogout?: () => void;
  onSettings?: () => void;
}

export function NodeDcProfileMenu({ user, coverUrl = "/storage/default.gif", trigger, className, onLogout, onSettings }: NodeDcProfileMenuProps) {
  return (
    <NodeDcDropdown
      className={className}
      placement="bottom-end"
      width={296}
      surfaceClassName="nodedc-ui-profile-menu"
      trigger={({ open, toggle, setTriggerRef }) => trigger({ open, toggle, setTriggerRef })}
    >
      {({ close }) => (
        <div className="nodedc-ui-profile-card">
          <div className="nodedc-ui-profile-card__cover" style={{ backgroundImage: `url(${coverUrl})` }}>
            <Avatar user={user} className="nodedc-ui-profile-card__avatar" />
            <strong>{user.name}</strong>
            <span>{user.email}</span>
          </div>
          <button
            className="nodedc-ui-profile-card__row"
            type="button"
            onClick={() => {
              close();
              onSettings?.();
            }}
          >
            <Settings size={15} strokeWidth={1.7} />
            <span>Настройки</span>
          </button>
          <button
            className="nodedc-ui-profile-card__row"
            type="button"
            onClick={() => {
              close();
              onLogout?.();
            }}
          >
            <LogOut size={15} strokeWidth={1.7} />
            <span>Выйти</span>
          </button>
        </div>
      )}
    </NodeDcDropdown>
  );
}

function Avatar({ user, className }: { user: NodeDcProfileMenuUser; className?: string }) {
  if (user.avatarUrl) {
    return <img className={cn("nodedc-ui-avatar", className)} src={user.avatarUrl} alt="" />;
  }

  return <span className={cn("nodedc-ui-avatar", className)}>{initials(user.name)}</span>;
}
