import { Metadata } from 'next';
import CharacterBasicInfo from './components/BasicInfo';
import Image from 'next/image';
import TabsNavigation from './components/TabsNavigation';
import { fetchCharacterDetail } from './service';

type CharacterDetailLayoutProps = {
  params: Promise<{
    id: string;
  }>;
};

// 动态生成 SEO metadata
export async function generateMetadata({
  params,
}: {
  params: Promise<{ id: string }>;
}): Promise<Metadata> {
  const { id } = await params;

  try {
    const characterDetail = await fetchCharacterDetail(id);

    const title = `${characterDetail.name || '角色'} - 角色详情 | Visual Novel`;
    const description = characterDetail.description
      ? `${characterDetail.description.substring(0, 160)}...`
      : `查看 ${characterDetail.name || '角色'} 的详细信息，包括角色背景、评分、标签等。`;

    const baseUrl =
      process.env.NEXT_PUBLIC_BASE_URL || 'https://yourdomain.com';
    const imageUrl = characterDetail.avatar
      ? characterDetail.avatar.startsWith('http')
        ? characterDetail.avatar
        : `${baseUrl}${characterDetail.avatar}`
      : `${baseUrl}/og-image.png`;

    const keywords = [
      characterDetail.name,
      characterDetail.role,
      ...(characterDetail.tags || []),
      '角色详情',
      'Visual Novel',
      '角色介绍',
    ].filter(Boolean);

    return {
      title,
      description,
      keywords: keywords.join(', '),
      openGraph: {
        title,
        description,
        type: 'website',
        url: `${baseUrl}/character/${id}`,
        siteName: 'Visual Novel',
        images: [
          {
            url: imageUrl,
            width: 1200,
            height: 630,
            alt: characterDetail.name || '角色头像',
          },
        ],
      },
      twitter: {
        card: 'summary_large_image',
        title,
        description,
        images: [imageUrl],
      },
      alternates: {
        canonical: `/character/${id}`,
      },
    };
  } catch (error) {
    // 如果获取失败，返回默认 metadata
    return {
      title: '角色详情 | Visual Novel',
      description: '查看角色详细信息',
    };
  }
}

export default async function CharacterDetail({
  params,
}: CharacterDetailLayoutProps) {
  const { id } = await params;
  const characterDetail = await fetchCharacterDetail(id);

  const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || 'https://yourdomain.com';
  const imageUrl = characterDetail.avatar
    ? characterDetail.avatar.startsWith('http')
      ? characterDetail.avatar
      : `${baseUrl}${characterDetail.avatar}`
    : `${baseUrl}/og-image.png`;

  // 结构化数据 - Person Schema
  const personSchema = {
    '@context': 'https://schema.org',
    '@type': 'Person',
    name: characterDetail.name,
    description: characterDetail.description,
    image: imageUrl,
    identifier: characterDetail.id,
    jobTitle: characterDetail.role,
    ...(characterDetail.rate && {
      aggregateRating: {
        '@type': 'AggregateRating',
        ratingValue: characterDetail.rate,
        bestRating: 10,
        worstRating: 1,
      },
    }),
    ...(characterDetail.tags &&
      characterDetail.tags.length > 0 && {
        keywords: characterDetail.tags.join(', '),
      }),
  };

  // 面包屑导航 Schema
  const breadcrumbSchema = {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    itemListElement: [
      {
        '@type': 'ListItem',
        position: 1,
        name: '首页',
        item: baseUrl,
      },
      {
        '@type': 'ListItem',
        position: 2,
        name: '角色列表',
        item: `${baseUrl}/character`,
      },
      {
        '@type': 'ListItem',
        position: 3,
        name: characterDetail.name,
        item: `${baseUrl}/character/${id}`,
      },
    ],
  };

  return (
    <>
      {/* 结构化数据 - Person */}
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{
          __html: JSON.stringify(personSchema),
        }}
      />
      {/* 结构化数据 - Breadcrumb */}
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{
          __html: JSON.stringify(breadcrumbSchema),
        }}
      />

      <div
        style={{
          background:
            'linear-gradient(90deg, rgba(44, 20, 65, 1) 1.08%, rgba(44, 20, 65, 0) 100%), linear-gradient(89.21deg, rgba(255, 255, 63, 0) 0.68%, rgba(255, 255, 63, 0.3) 111.9%)',
        }}
        className="flex min-h-full w-full flex-col items-center"
      >
        <div className="max-w-300 pt-7.5">
          <CharacterBasicInfo
            characterId={id}
            characterDetail={characterDetail}
          />
        </div>
        {/* 评分 */}
        <div className="bg-text-color/5 mt-20 flex h-20 w-full max-w-300 items-center justify-between rounded-full px-7.5">
          <div className="flex items-center gap-5">
            <Image
              src={'/character/figure.svg'}
              alt="评分图标"
              width={20}
              height={20}
            />
            <div className="font-bold">How Was this book ?</div>
          </div>
          <div className="flex flex-col items-end gap-1">
            <div
              className="flex gap-2"
              style={{ color: 'rgba(255, 225, 167, 1)' }}
            >
              Tap to Rate
              <Image
                src={'/character/figure.svg'}
                alt="评分图标"
                width={20}
                height={20}
              />
            </div>
            {/* <Rate /> */}
          </div>
        </div>

        {/* Tabs - 客户端组件，处理路由切换 */}
        <TabsNavigation />
      </div>
    </>
  );
}
