import React, { useEffect, useState } from 'react';
import Link from '@docusaurus/Link';
import { useLocation } from '@docusaurus/router';
import { useAllDocsData } from '@docusaurus/plugin-content-docs/client';
import styles from './styles.module.css';

/**
 * Derive the title from a doc's id.
 * Docusaurus client data only provides {id, path, sidebar} for each doc,
 * so we extract a readable name from the last segment of the doc id.
 * Example: "代码库管理/仓库创建" -> "仓库创建"
 */
function deriveTitle(id) {
  if (!id) return '';
  const segments = id.split('/');
  return segments[segments.length - 1];
}

/**
 * Derive the source directory name from a doc's id.
 * Example: "代码库管理/仓库创建" -> "代码库管理"
 * Example: "快速开始" -> "" (root-level doc)
 */
function deriveSourceDir(id) {
  if (!id) return '';
  const segments = id.split('/');
  if (segments.length <= 1) return '';
  return segments.slice(0, -1).join('/');
}

export default function RelatedDocuments() {
  const location = useLocation();
  const allDocsData = useAllDocsData();
  const [relatedDocs, setRelatedDocs] = useState(null);

  useEffect(() => {
    if (!allDocsData) return;

    const pluginIds = Object.keys(allDocsData);
    if (pluginIds.length === 0) return;

    const plugin = allDocsData[pluginIds[0]];

    // Find the version matching the current pathname
    let activeVersion = null;
    for (const version of plugin.versions) {
      if (!version.docs) continue;
      const docs = Object.values(version.docs);
      const found = docs.find(
        (doc) => doc.path && location.pathname.endsWith(doc.path)
      );
      if (found) {
        activeVersion = version;
        break;
      }
    }

    if (!activeVersion) {
      activeVersion = plugin.versions.find((v) => v.isLast) || plugin.versions[0];
    }

    if (!activeVersion || !activeVersion.docs) return;

    const docs = Object.values(activeVersion.docs);

    const currentDoc = docs.find(
      (doc) => doc.path && location.pathname.endsWith(doc.path)
    );
    if (!currentDoc) return;

    const currentDir = deriveSourceDir(currentDoc.id);

    const related = docs
      .filter((doc) => {
        if (doc.path === currentDoc.path) return false;
        if (!currentDir) return false;
        return deriveSourceDir(doc.id) === currentDir;
      })
      .sort((a, b) => (a.path || '').localeCompare(b.path || ''));

    setRelatedDocs(related.length > 0 ? related.map(doc => ({
      ...doc,
      title: deriveTitle(doc.id),
    })) : null);
  }, [location.pathname, allDocsData]);

  if (!relatedDocs || relatedDocs.length === 0) return null;

  return (
    <div className={styles.container}>
      <h3 className={styles.heading}>相关文档</h3>
      <div className={styles.grid}>
        {relatedDocs.map((doc) => (
          <Link key={doc.path} to={doc.path} className={styles.card}>
            <div className={styles.cardTitle}>{doc.title}</div>
          </Link>
        ))}
      </div>
    </div>
  );
}
