import { useRef, useEffect, useState } from 'react';
import { Link, LinkProps } from 'react-router-dom';
import { useCreation, useMemoizedFn } from 'ahooks';
import { Box, BoxProps, useTheme } from '@mui/material';
import SubItemGroup from './sub-item-group';
import { Item } from './nav-menu';
import { styled } from '../Theme';
import { useNavMenuContext } from './nav-menu-context';
import { translate } from '../Locale/util';
import { useLocaleContext } from '../Locale/context';
// Arcblock Icons
import NftStudioSvg from './images/nft-studio.svg?react';
import CreatorStudioSvg from './images/creator-studio.svg?react';
import BlockletLauncherSvg from './images/blocklet-launcher.svg?react';
import BlockletStoreSvg from './images/blocklet-store.svg?react';
import Web3KitSvg from './images/web3-kit.svg?react';
import BlockletFrameworkSvg from './images/blocklet-framework.svg?react';
import AbtNetworkSvg from './images/abt-network.svg?react';
import BlockletServerSvg from './images/blocklet-server.svg?react';
import OCAPSvg from './images/OCAP.svg?react';
import DidSvg from './images/did.svg?react';
import DidWalletSvg from './images/did-wallet.svg?react';
import VCSvg from './images/vc.svg?react';
import PaymentKitPng from './images/payment-kit.png';
// AIGNE Icons
import AigneSvg from './images/aigne.svg?react';
import ArcSphereSvg from './images/arcsphere.svg?react';
import AistroPng from './images/aistro.png';

const MIN_ITEM_CONTENT_WIDTH = 260;

const translations = {
  en: {
    groups: {
      applications: 'Applications',
      components: 'Components',
      computeStorage: 'Compute/Storage',
      identity: 'Identity',
      frameworkTools: 'Framework & tools',
      modelsAdapters: 'Models adapters',
    },
    products: {
      nftStudio: {
        description: 'Mint and manage NFTs',
      },
      creatorStudio: {
        description: 'All-in-one creator tool',
      },
      aigne: {
        description: 'The Agentic Ecosystem for AI Apps',
      },
      arcsphere: {
        description: 'AI native browser',
      },
      aistro: {
        description: 'AI-powered astrology',
      },
      blockletLauncher: {
        description: 'One-click app launcher',
      },
      aiKit: {
        description: 'Boost apps with AI',
      },
      paymentKit: {
        description: 'Effortless Crypto & Card Payments',
      },
      blockletStore: {
        description: 'Discover & deploy apps',
      },
      web3Kit: {
        description: 'Web3 dev toolkit',
      },
      blockletFramework: {
        description: 'Build and run blocklets',
      },
      didSpaces: {
        description: 'Secure personal storage',
      },
      abtNetwork: {
        description: 'Fast blockchain network',
      },
      blockletServer: {
        description: 'Host your apps easily',
      },
      ocap: {
        description: 'Multi-chain connector',
      },
      did: {
        description: 'Self-sovereign ID',
      },
      didWallet: {
        description: 'Smart digital wallet',
      },
      didNameService: {
        description: 'Web3 domain names',
      },
      vc: {
        description: 'Verifiable Credentials',
      },
      didConnect: {
        description: 'Passwordless login',
      },
      aigneCodeSmith: {
        description: 'Review and improve your code with AI',
      },
      aigneDocSmith: {
        description: 'Generate and update docs with AI',
      },
      aigneWebSmith: {
        description: 'Build and deploy AI-powered web apps',
      },
      aigneCLI: {
        description: 'Develop agents from the command line',
      },
      aigneObservability: {
        description: 'Understand and inspect agent behavior',
      },
      aigneStudio: {
        description: 'Create agents visually, no code needed',
      },
      aigneFramework: {
        description: 'The functional core of agentic AI',
      },
      aigneHub: {
        description: 'One API. Any Model',
      },
    },
  },
  zh: {
    groups: {
      applications: '应用',
      components: '组件',
      computeStorage: '计算/存储',
      identity: '身份',
      frameworkTools: '框架与工具',
      modelsAdapters: '模型适配器',
    },
    products: {
      nftStudio: {
        description: '铸造和管理 NFT',
      },
      creatorStudio: {
        description: '一体化创作工具',
      },
      aigne: {
        description: 'AI 应用的代理生态系统',
      },
      arcsphere: {
        description: 'AI 原生浏览器',
      },
      aistro: {
        description: 'AI 占星术',
      },
      blockletLauncher: {
        description: '一键启动应用程序',
      },
      aiKit: {
        description: 'AI 赋能应用',
      },
      paymentKit: {
        description: '便捷的加密货币和银行卡支付',
      },
      blockletStore: {
        description: '发现和部署应用程序',
      },
      web3Kit: {
        description: 'Web3 开发工具包',
      },
      blockletFramework: {
        description: '构建并运行 Blocklet',
      },
      didSpaces: {
        description: '安全的个人存储',
      },
      abtNetwork: {
        description: '快速区块链网络',
      },
      blockletServer: {
        description: '轻松托管应用程序',
      },
      ocap: {
        description: '多链连接器',
      },
      did: {
        description: '自主身份',
      },
      didWallet: {
        description: '智能数字钱包',
      },
      didNameService: {
        description: 'Web3 域名',
      },
      vc: {
        description: '可验证凭证',
      },
      didConnect: {
        description: '无密码登录',
      },
      aigneCodeSmith: {
        description: '使用 AI 审查并优化你的代码',
      },
      aigneDocSmith: {
        description: '用 AI 生成和更新项目文档',
      },
      aigneWebSmith: {
        description: '构建并部署 AI 驱动的 Web 应用',
      },
      aigneCLI: {
        description: '通过命令行开发 Agent',
      },
      aigneObservability: {
        description: '理解并分析 Agent 的行为',
      },
      aigneStudio: {
        description: '零代码构建 Agent',
      },
      aigneFramework: {
        description: 'Agent AI 的功能核心框架',
      },
      aigneHub: {
        description: '一套 API，连接所有模型',
      },
    },
  },
};

const Wrapper = styled(Box)`
  padding: 8px;
  background: ${({ theme }) => theme.palette.grey[100]};
  border-radius: 8px;

  &.is-inline {
    width: 100%;
    max-width: 100%;
    border-radius: 0;
    .nav-menu-sub-item-group {
      padding: 8px 16px;
      border-radius: 0;
    }
  }

  .nav-menu-sub-item-group + .nav-menu-sub-item-group {
    margin-top: 8px;
  }
  .MuiGrid-container + .MuiGrid-container {
    margin-top: 0px;
  }
`;

const GridBox = styled(Box, { shouldForwardProp: (prop) => prop !== 'maxContent' })<{ maxContent: number }>(
  ({ theme, maxContent }) => ({
    display: 'grid',
    gap: theme.spacing(1),
    gridTemplateColumns: `repeat(1, ${maxContent}px)`,

    [theme.breakpoints.up('md')]: {
      gridTemplateColumns: `repeat(2, ${maxContent}px)`,
    },

    [theme.breakpoints.up('lg')]: {
      gridTemplateColumns: `repeat(3, ${maxContent}px)`,
    },
  })
);

interface IconWrapperProps {
  color?: string;
  backgroundColor?: string;
  children: React.ReactNode;
}
function IconWrapper({ color = 'black', backgroundColor = 'transparent', children }: IconWrapperProps) {
  return (
    <Box
      component="span"
      sx={{
        display: 'inline-flex',
        alignItems: 'center',
        justifyContent: 'center',
        color,
        backgroundColor,
        borderRadius: '4px',
      }}>
      {children}
    </Box>
  );
}

function DIDIcon({ color = 'black', backgroundColor = 'transparent' }: { color?: string; backgroundColor?: string }) {
  return (
    <IconWrapper color={color} backgroundColor={backgroundColor}>
      <DidSvg style={{ width: '100%' }} />
    </IconWrapper>
  );
}

function AigneIcon({ color = 'black', backgroundColor = 'transparent' }: { color?: string; backgroundColor?: string }) {
  return (
    <IconWrapper color={color} backgroundColor={backgroundColor}>
      <AigneSvg style={{ width: '100%', height: '100%' }} />
    </IconWrapper>
  );
}

const isExternal = (to: string) => {
  try {
    const url = new URL(to);
    return url.origin !== window.location.origin;
  } catch {
    // 如果 to 不是有效的 URL，则认为是内部链接
    return false;
  }
};

// 智能 Link 组件，根据 URL origin 决定是否在新标签页打开
interface SmartLinkProps extends LinkProps {
  to: string;
  children: React.ReactNode;
  className?: string;
}
function SmartLink({ to, children, className = '', ...restProps }: SmartLinkProps) {
  if (isExternal(to)) {
    return (
      <Link to={to} target="_blank" rel="noreferrer noopener" className={className} {...restProps}>
        {children}
      </Link>
    );
  }

  return (
    <Link to={to} className={className} {...restProps}>
      {children}
    </Link>
  );
}

export type ProductsType = 'AIGNE' | 'ARCBLOCK';
export interface ProductsProps extends BoxProps {
  type: ProductsType;
}
export default function Products({ className = '', type, ...rest }: ProductsProps) {
  const { mode } = useNavMenuContext();
  const theme = useTheme();
  const { locale = 'en' } = useLocaleContext() || {};
  const wrapperRef = useRef<HTMLDivElement>(null);

  const { palette } = theme;
  const t = useMemoizedFn((key, data = {}) => translate(translations, key, locale, 'en', data));

  // 添加状态来存储最大内容宽度
  const [maxContentWidth, setMaxContentWidth] = useState(MIN_ITEM_CONTENT_WIDTH);

  // 计算 item 最大宽度
  const calculateMaxContentWidth = useMemoizedFn(() => {
    if (!wrapperRef.current) return;

    const contentElements = wrapperRef.current.querySelectorAll('.navmenu-item__content');
    let maxWidth = MIN_ITEM_CONTENT_WIDTH; // 默认最小宽度

    contentElements.forEach((element) => {
      const curWidth = element.getBoundingClientRect().width + 64; // 增加 icon 以及 padding 的宽度
      if (curWidth > maxWidth) {
        maxWidth = curWidth;
      }
    });

    setMaxContentWidth(maxWidth);
  });

  // 监听主题、语言、类型变化时重新计算最大宽度
  useEffect(() => {
    calculateMaxContentWidth();
  }, [theme, locale, type, calculateMaxContentWidth]);

  // 监听 navmenu-item__content 元素宽度变化
  useEffect(() => {
    if (!wrapperRef.current) return;

    const itemContent = wrapperRef.current.querySelector('.navmenu-item__content');
    if (!itemContent) return;

    const resizeObserver = new ResizeObserver(() => {
      calculateMaxContentWidth();
    });

    // 监听 item 内容宽度变化（字体改变引起）
    resizeObserver.observe(itemContent);

    // eslint-disable-next-line consistent-return
    return () => {
      resizeObserver.disconnect();
    };
  }, [calculateMaxContentWidth]);

  const groups = useCreation(() => {
    if (type === 'ARCBLOCK') {
      return [
        {
          type: 'Group',
          label: t('groups.applications'),
          children: [
            {
              label: <SmartLink to={`https://www.nftstudio.rocks/${locale}`}>NFT Studio</SmartLink>,
              description: t('products.nftStudio.description'),
              icon: <NftStudioSvg />,
            },
            {
              label: (
                <Link
                  to={`https://www.arcblock.io/content/collections/${locale}/creator-studio`}
                  target="_blank"
                  rel="noreferrer noopener">
                  Creator Studio
                </Link>
              ),
              description: t('products.creatorStudio.description'),
              icon: <CreatorStudioSvg />,
            },
            {
              label: <SmartLink to="https://www.aigne.io/">AIGNE</SmartLink>,
              description: t('products.aigne.description'),
              icon: <AigneIcon color={palette.mode === 'dark' ? 'white' : 'black'} />,
            },
            {
              label: <SmartLink to={`https://www.arcsphere.io/${locale}`}>ArcSphere</SmartLink>,
              description: t('products.arcsphere.description'),
              icon: <ArcSphereSvg />,
            },
          ],
        },
        {
          type: 'Group',
          label: t('groups.components'),
          children: [
            {
              label: <SmartLink to={`https://launcher.arcblock.io/${locale}`}>Blocklet Launcher</SmartLink>,
              description: t('products.blockletLauncher.description'),
              icon: <BlockletLauncherSvg />,
            },
            {
              label: <SmartLink to={`https://www.blocklet.io/${locale}/payment-kit`}>Payment Kit</SmartLink>,
              description: t('products.paymentKit.description'),
              icon: <img src={PaymentKitPng} alt="Payment Kit" />,
            },
            {
              label: <SmartLink to={`https://store.blocklet.dev/?locale=${locale}`}>Blocklet Store</SmartLink>,
              description: t('products.blockletStore.description'),
              icon: <BlockletStoreSvg />,
            },
            {
              label: <SmartLink to={`https://www.web3kit.rocks/${locale}`}>Web3 Kit</SmartLink>,
              description: t('products.web3Kit.description'),
              icon: <Web3KitSvg />,
            },
          ],
        },
        {
          type: 'Group',
          label: t('groups.computeStorage'),
          children: [
            {
              label: (
                <Link
                  to={`https://www.arcblock.io/content/collections/${locale}/blocklet`}
                  target="_blank"
                  rel="noreferrer noopener">
                  Blocklet Framework
                </Link>
              ),
              description: t('products.blockletFramework.description'),
              icon: <BlockletFrameworkSvg />,
            },
            {
              label: (
                <Link to={`https://www.didspaces.com/${locale}`} target="_blank" rel="noreferrer noopener">
                  DID Spaces
                </Link>
              ),
              description: t('products.didSpaces.description'),
              icon: <DIDIcon color="#876bf4" />,
            },
            {
              label: (
                <Link to="https://main.abtnetwork.io/" target="_blank" rel="noreferrer noopener">
                  ABT Network
                </Link>
              ),
              description: t('products.abtNetwork.description'),
              icon: <AbtNetworkSvg />,
            },
            {
              label: <SmartLink to={`https://www.blocklet.io/${locale}/blocklet-server`}>Blocklet Server</SmartLink>,
              description: t('products.blockletServer.description'),
              icon: <BlockletServerSvg />,
            },
            {
              label: <SmartLink to={`https://www.arcblock.io/content/collections/${locale}/ocap`}>ОСАР</SmartLink>,
              description: t('products.ocap.description'),
              icon: <OCAPSvg />,
            },
          ],
        },
        {
          type: 'Group',
          label: t('groups.identity'),
          children: [
            {
              label: <SmartLink to={`https://www.arcblock.io/content/collections/${locale}/did`}>DID</SmartLink>,
              description: t('products.did.description'),
              icon: <DIDIcon color="#5b96f3" />,
            },
            {
              label: <SmartLink to={`https://www.didwallet.io/${locale}`}>DID Wallet</SmartLink>,
              description: t('products.didWallet.description'),
              icon: <DidWalletSvg />,
            },
            {
              label: (
                <Link to={`https://www.didnames.io/${locale}`} target="_blank" rel="noreferrer noopener">
                  DID Names
                </Link>
              ),
              description: t('products.didNameService.description'),
              icon: <DIDIcon color="#678ab0" />,
            },
            {
              label: (
                <SmartLink to={`https://www.arcblock.io/content/collections/${locale}/verifiable-credential`}>
                  VC
                </SmartLink>
              ),
              description: t('products.vc.description'),
              icon: <VCSvg />,
            },
            {
              label: <SmartLink to={`https://www.didconnect.io/${locale}`}>DID Connect</SmartLink>,
              description: t('products.didConnect.description'),
              icon: <DIDIcon color="#5bbec5" />,
            },
          ],
        },
      ];
    }

    if (type === 'AIGNE') {
      // aigne 相关页面，不能使用 react dom 自己的 navigate 跳转，因为没有对应的页面数据
      const aigneLinkBaseProps = {
        onClick: (e: React.MouseEvent<HTMLAnchorElement>) => {
          e.preventDefault();

          const url = e.currentTarget.href;
          const target = isExternal(url) ? '_blank' : '_self';
          window.open(url, target);
        },
      };

      return [
        {
          type: 'Group',
          label: t('groups.applications'),
          children: [
            {
              label: <SmartLink to={`https://www.arcsphere.io/${locale}`}>ArcSphere</SmartLink>,
              description: t('products.arcsphere.description'),
              icon: <ArcSphereSvg />,
            },
            {
              label: <SmartLink to={`https://www.aistro.io/${locale}`}>Aistro</SmartLink>,
              description: t('products.aistro.description'),
              icon: <img src={AistroPng} alt="Aistro" />,
            },
            {
              label: (
                <SmartLink to="https://www.aigne.io/code-smith" {...aigneLinkBaseProps}>
                  AIGNE CodeSmith
                </SmartLink>
              ),
              description: t('products.aigneCodeSmith.description'),
              icon: <AigneIcon color="#56a596" backgroundColor="#e9fcf6" />,
            },
            {
              label: (
                <SmartLink to="https://www.aigne.io/doc-smith" {...aigneLinkBaseProps}>
                  AIGNE DocSmith
                </SmartLink>
              ),
              description: t('products.aigneDocSmith.description'),
              icon: <AigneIcon color="#e46f38" backgroundColor="#f7e0d7" />,
            },
            {
              label: (
                <SmartLink to="https://www.aigne.io/web-smith" {...aigneLinkBaseProps}>
                  AIGNE WebSmith
                </SmartLink>
              ),
              description: t('products.aigneWebSmith.description'),
              icon: <AigneIcon color="#7c45eb" backgroundColor="#f0e9ff" />,
            },
          ],
        },
        {
          type: 'Group',
          label: t('groups.frameworkTools'),
          children: [
            {
              label: (
                <SmartLink to="https://www.aigne.io/cli" {...aigneLinkBaseProps}>
                  AIGNE CLI
                </SmartLink>
              ),
              description: t('products.aigneCLI.description'),
              icon: <AigneIcon color="#d05d4e" backgroundColor="#faeaea" />,
            },
            {
              label: (
                <SmartLink to="https://www.aigne.io/observability" {...aigneLinkBaseProps}>
                  AIGNE Observability
                </SmartLink>
              ),
              description: t('products.aigneObservability.description'),
              icon: <AigneIcon color="#6ba456" backgroundColor="#edfae8" />,
            },
            {
              label: (
                <SmartLink to="https://www.aigne.io/studio" {...aigneLinkBaseProps}>
                  AIGNE Studio
                </SmartLink>
              ),
              description: t('products.aigneStudio.description'),
              icon: <AigneIcon color="#676cbf" backgroundColor="#edeeff" />,
            },
            {
              label: (
                <SmartLink to="https://www.aigne.io/framework" {...aigneLinkBaseProps}>
                  AIGNE Framework
                </SmartLink>
              ),
              description: t('products.aigneFramework.description'),
              icon: <AigneIcon color="#5086d0" backgroundColor="#eef4ff" />,
            },
          ],
        },
        {
          type: 'Group',
          label: t('groups.modelsAdapters'),
          children: [
            {
              label: (
                <SmartLink to="https://www.aigne.io/hub" {...aigneLinkBaseProps}>
                  AIGNE Hub
                </SmartLink>
              ),
              description: t('products.aigneHub.description'),
              icon: <AigneIcon color="#e4930b" backgroundColor="#fbf4d4" />,
            },
          ],
        },
      ];
    }

    return [];
  }, [t, locale, palette]);

  return (
    <Wrapper ref={wrapperRef} className={`nav-menu-products is-${mode} ${className}`} {...rest}>
      {groups.map((group) => (
        <SubItemGroup key={group.label} label={group.label}>
          <GridBox maxContent={maxContentWidth}>
            {group.children.map((item) => (
              <Item variant="panel" style={{ padding: '8px' }} {...item} />
            ))}
          </GridBox>
        </SubItemGroup>
      ))}
    </Wrapper>
  );
}
