"use client";

import { useEffect, useState } from "react";

import { getCustomerInfo } from "@/app/lib/astrologer";

function initialsOf(name?: string) {
  return (
    (name || "?")
      .trim()
      .split(/\s+/)
      .slice(0, 2)
      .map((part) => part.charAt(0).toUpperCase())
      .join("") || "?"
  );
}

/*
 * A customer's avatar on the astrologer side: their real profile photo
 * from GET /astrologer/get-customer-by-id, falling back to initials
 * while it loads, when the customer has no photo, or when the id isn't
 * known. `className` is the existing avatar wrapper class of whichever
 * list/card this sits in, so its size and look are untouched.
 */
export default function CustomerAvatar({
  userId,
  name,
  className,
  initialsOverride,
}: {
  userId?: number | string | null;
  name?: string;
  className?: string;
  initialsOverride?: string;
}) {
  const [image, setImage] = useState("");

  useEffect(() => {
    let cancelled = false;

    getCustomerInfo(userId).then((info) => {
      if (!cancelled) setImage(info?.profile_image || "");
    });

    return () => {
      cancelled = true;
    };
  }, [userId]);

  return (
    <div className={className} style={image ? { overflow: "hidden", padding: 0 } : undefined}>
      {image ? (
        // eslint-disable-next-line @next/next/no-img-element
        <img
          src={image}
          alt={name || "Customer"}
          style={{ width: "100%", height: "100%", borderRadius: "50%", objectFit: "cover" }}
          onError={() => setImage("")}
        />
      ) : (
        initialsOverride ?? initialsOf(name)
      )}
    </div>
  );
}
