'use client';

import React, { useRef, useEffect, useState } from 'react';
import { formatNumberToKMB } from '@/lib/utils';
import { Tag } from '@/components/ui/tag';
import { Avatar, AvatarImage } from '@/components/ui/avatar';
import Link from 'next/link';
import { CharacterType } from '@/services/editor/type';

interface AIStandardCardProps {
  character: CharacterType;
  disableHover?: boolean;
}

const AIStandardCard: React.FC<AIStandardCardProps> = React.memo(
  ({ character, disableHover = false }) => {
    const { id, name, description, coverImage, headPortrait, tags } = character;

    const introContainerRef = useRef<HTMLDivElement>(null);
    const introTextRef = useRef<HTMLParagraphElement>(null);
    const [maxLines, setMaxLines] = useState<number>(6);

    // 动态计算可用空间的行数
    useEffect(() => {
      const calculateMaxLines = () => {
        if (introContainerRef.current) {
          const containerHeight = introContainerRef.current.offsetHeight;
          const lineHeight = 20; // 对应 leading-[20px]
          const calculatedLines = Math.floor(containerHeight / lineHeight);
          // 确保至少显示 1 行，最多不超过合理的行数
          const finalLines = Math.max(1, Math.min(calculatedLines, 12));
          setMaxLines(finalLines);
        }
      };

      calculateMaxLines();

      // 监听窗口大小变化
      window.addEventListener('resize', calculateMaxLines);
      return () => window.removeEventListener('resize', calculateMaxLines);
    }, []);

    // 获取显示的背景图片
    const displayImage = coverImage;

    return (
      <Link href={`/character/${id}`} className="h-full w-full" prefetch={false}>
        <div
          className={`relative flex shrink-0 grow basis-0 cursor-pointer flex-col content-stretch items-start justify-start gap-3 ${disableHover ? '' : 'group'}`}
        >
          <div
            className="relative aspect-[3/4] w-full shrink-0 overflow-hidden rounded-[16px] bg-cover bg-top bg-no-repeat transition-transform"
            style={{ backgroundImage: displayImage ? `url('${displayImage}')` : undefined }}
          >
            <div className="relative box-border flex aspect-[3/4] size-full flex-col content-stretch items-end justify-end overflow-clip p-[12px]">
              {/* 默认渐变遮罩层 */}
              <div
                className={`absolute right-0 bottom-[-0.33px] left-0 flex flex-col items-start justify-start gap-2 px-3 pt-6 pb-3 transition-opacity duration-300 ${disableHover ? '' : 'group-hover:opacity-0'}`}
              >
                <div
                  className="absolute inset-0 backdrop-blur-3xl"
                  style={{
                    background:
                      'var(--color-overlay-background, linear-gradient(180deg, rgba(33, 26, 43, 0.00) 0%, var(--sys-color-background-default, #211A2B) 100%))',
                    maskImage: 'linear-gradient(180deg, rgba(33, 26, 43, 0.00) 0%, #211A2B 100%)',
                  }}
                />
                <div className="relative">
                  {/* 角色信息区域 */}
                  <div className="relative flex w-full shrink-0 flex-col content-stretch items-start justify-start gap-2">
                    {/* 名称 */}
                    <div
                      className="txt-headline-s text-txt-primary-normal"
                      style={{ wordBreak: 'break-word' }}
                    >
                      {name}
                    </div>

                    <div className="flex flex-wrap gap-1">
                      {!!tags?.length && (
                        <div className="relative flex shrink-0 flex-wrap content-start items-start justify-start gap-1">
                          {tags?.slice(0, 2).map((tag, index) => (
                            <Tag key={index} size="small" className="backdrop-blur-[8px]">
                              {tag.name}
                            </Tag>
                          ))}
                        </div>
                      )}
                    </div>
                  </div>

                  {/* 点赞数 */}
                  <div className="flex items-center gap-1 rounded-xs px-1 py-0.5">
                    <i className="iconfont icon-Like-fill" />
                    <span className="txt-label-s text-txt-primary-specialmap-normal">
                      {formatNumberToKMB(1000)}
                    </span>
                  </div>
                </div>
              </div>

              {/* Hover 时显示的简介覆盖层 */}
              {!disableHover && (
                <div className="absolute inset-0 flex flex-col items-start justify-end gap-2 bg-black/65 px-3 pt-6 pb-3 opacity-0 backdrop-blur-[8px] transition-opacity duration-300 group-hover:opacity-100">
                  {/* 头像和名称 */}
                  <div className="flex w-full items-center gap-2">
                    <Avatar className="sh size-12">
                      <AvatarImage src={headPortrait} alt={name} />
                    </Avatar>
                    <div className="txt-title-s min-w-0 flex-1 truncate">{name}</div>
                  </div>

                  {/* 简介文本 */}
                  <div
                    ref={introContainerRef}
                    className="flex min-h-0 w-full flex-1 items-start justify-start gap-1"
                  >
                    <div
                      className="txt-body-m text-txt-secondary-normal w-full overflow-hidden"
                      style={{
                        display: '-webkit-box',
                        WebkitLineClamp: maxLines,
                        WebkitBoxOrient: 'vertical',
                      }}
                    >
                      <p ref={introTextRef} className="leading-[20px]">
                        {description || 'No description'}
                      </p>
                    </div>
                  </div>

                  {/* 点赞数 */}
                  <div className="flex items-center gap-1 rounded-xs px-1 py-0.5">
                    <i className="iconfont icon-Like-fill" />
                    <span className="txt-label-s text-txt-primary-specialmap-normal">
                      {formatNumberToKMB(100)}
                    </span>
                  </div>
                </div>
              )}
            </div>

            {/* 边框 */}
            <div
              aria-hidden="true"
              className="pointer-events-none absolute inset-0 rounded-[16px] border border-solid border-[rgba(251,222,255,0.2)]"
            />
          </div>
        </div>
      </Link>
    );
  }
);

export default AIStandardCard;
