import { Avatar as AntdAvatar, AvatarProps } from "antd";
import clsx from "clsx";
import * as React from "react";
import { useMemo } from "react";

import default_group from "@/assets/images/contact/group.png";
import { avatarList, getDefaultAvatar } from "@/utils/avatar";

const default_avatars = avatarList.map((item) => item.name);

// 头像文字：与手机端一致，中文名取首字（王志远→王）；非中文取首字母大写
const getDisplayText = (text?: string) => {
  if (!text) return text;
  const trimmed = text.trim();
  if (trimmed.length <= 2) return trimmed;
  if (/^[一-龥]/.test(trimmed)) return trimmed[0];
  return trimmed[0].toUpperCase();
};

interface IOIMAvatarProps extends AvatarProps {
  text?: string;
  color?: string;
  bgColor?: string;
  isgroup?: boolean;
  isnotification?: boolean;
  size?: number;
}

const OIMAvatar: React.FC<IOIMAvatarProps> = (props) => {
  const {
    src,
    text,
    size = 42,
    color = "#fff",
    bgColor = "#3B87F5",
    isgroup = false,
    isnotification,
  } = props;
  const [errorHolder, setErrorHolder] = React.useState<string>();

  const getAvatarUrl = useMemo(() => {
    if (src) {
      if (default_avatars.includes(src as string))
        return getDefaultAvatar(src as string);

      return src;
    }
    return isgroup ? default_group : undefined;
  }, [src, isgroup, isnotification]);

  const avatarProps = { ...props, isgroup: undefined, isnotification: undefined };

  React.useEffect(() => {
    if (!isgroup) {
      setErrorHolder(undefined);
    }
  }, [isgroup]);

  const errorHandler = () => {
    if (isgroup) {
      setErrorHolder(default_group);
    }
  };

  // 群头像：与手机端一致，无真实头像（或加载失败）时用 2x2 蓝灰拼格（浅灰底 + 蓝/灰蓝交替小方块）
  const showGroupGrid = isgroup && (!src || errorHolder === default_group);
  if (showGroupGrid) {
    const cell = (size - 10) / 2;
    const gridColors = ["var(--primary)", "var(--avatar-gray)", "var(--avatar-gray)", "var(--primary)"];
    return (
      <div
        className={props.className}
        onClick={props.onClick}
        style={{
          width: `${size}px`,
          height: `${size}px`,
          backgroundColor: "var(--search-bg)",
          borderRadius: `${Math.round(size * 0.18)}px`,
          padding: "2px",
          display: "grid",
          gridTemplateColumns: `${cell}px ${cell}px`,
          gridTemplateRows: `${cell}px ${cell}px`,
          gap: "2px",
        }}
      >
        {gridColors.map((c, i) => (
          <div key={i} style={{ backgroundColor: c, borderRadius: "2px" }} />
        ))}
      </div>
    );
  }

  return (
    <AntdAvatar
      style={{
        backgroundColor: bgColor,
        minWidth: `${size}px`,
        minHeight: `${size}px`,
        lineHeight: `${size - 2}px`,
        borderRadius: `${Math.round(size * 0.18)}px`,
        color,
      }}
      shape="square"
      {...avatarProps}
      className={clsx(
        {
          "cursor-pointer": Boolean(props.onClick),
        },
        props.className,
      )}
      src={errorHolder ?? getAvatarUrl}
      onError={errorHandler as any}
    >
      {getDisplayText(text)}
    </AntdAvatar>
  );
};

export default OIMAvatar;
