import { HomeOutlined, LeftOutlined } from '@ant-design/icons';
import { PageContainer, PageContainerProps } from '@ant-design/pro-components';
import { useLocation, useNavigate } from '@umijs/max';
import { Breadcrumb, Button, Space, Tooltip } from 'antd';
import { useCallback, useEffect, useRef, useState } from 'react';

interface BreadcrumbItem {
  title: string;
  path: string;
}

export interface MyPageContainerProps extends PageContainerProps {
  /* 多标签页功能已废弃，此参数不再生效，保留以避免破坏现有调用方 */
  enableTabs?: boolean;
  /* 多标签页功能已废弃，此参数不再生效，保留以避免破坏现有调用方 */
  tabKey?: string;
  /* 多标签页功能已废弃，此参数不再生效，保留以避免破坏现有调用方 */
  tabLabel?: string;
  /* 多标签页功能已废弃，此参数不再生效，保留以避免破坏现有调用方 */
  onTabChange?: (activeKey: string) => void;
}

export function MyPageContainer({
  title,
  children,
  enableTabs: _enableTabs,
  tabKey: _tabKey,
  tabLabel: _tabLabel,
  onTabChange: _onTabChange,
  ...rest
}: MyPageContainerProps) {
  const navigate = useNavigate();
  const location = useLocation();
  const [dataBre, setDataBre] = useState<BreadcrumbItem[]>(
    JSON.parse(sessionStorage.getItem('breadcrumbs') || '[]'),
  );
  const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const canGoBack = location.pathname !== '/';

  const handleGoBack = useCallback(() => {
    navigate(-1);
  }, [navigate]);

  const updateBreadcrumbs = useCallback(() => {
    try {
      const currentPath = location.pathname + location.search;
      const currentTitle =
        typeof title === 'string'
          ? title
          : String(
              (title as { props?: { children?: unknown } })?.props?.children ??
                '',
            );

      const newBreadcrumbs: BreadcrumbItem[] = [];

      if (currentPath && currentTitle) {
        newBreadcrumbs.push({
          title: currentTitle,
          path: currentPath,
        });
      }

      try {
        sessionStorage.setItem('breadcrumbs', JSON.stringify(newBreadcrumbs));
      } catch (storageError) {
        console.error('存储到sessionStorage失败:', storageError);
      }

      setDataBre(newBreadcrumbs);
    } catch (error) {
      console.error('更新面包屑时出错:', error);
      setDataBre([]);
    }
  }, [location.pathname, location.search, title]);

  useEffect(() => {
    timeoutRef.current = setTimeout(() => {
      updateBreadcrumbs();
    }, 250);

    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, [updateBreadcrumbs]);

  return (
    <PageContainer
      fixedHeader
      header={{
        breadcrumb: {},
        title: (
          <Space style={{ fontSize: '12px', cursor: 'pointer', color: '#999' }}>
            {canGoBack && (
              <Tooltip title="返回上级">
                <Button
                  type="text"
                  size="small"
                  icon={<LeftOutlined />}
                  onClick={handleGoBack}
                  style={{ marginRight: 8, color: '#999' }}
                />
              </Tooltip>
            )}
            <Breadcrumb
              items={[
                {
                  title: <HomeOutlined />,
                  onClick: () => navigate('/'),
                },
                ...dataBre.map((res) => ({
                  title: res.title || '',
                  onClick: () => {
                    navigate(res.path);
                  },
                })),
              ]}
            />
          </Space>
        ),
        style: {
          backgroundColor: '#FFF',
          boxShadow: '10px 2px 10px 0 rgba(0, 0, 0, 0.1)',
        },
      }}
      token={{
        paddingBlockPageContainerContent: 0,
        paddingInlinePageContainerContent: 0,
      }}
      {...rest}
    >
      <Space
        direction="vertical"
        size="middle"
        style={{
          width: '100%',
        }}
      >
        {children}
      </Space>
    </PageContainer>
  );
}
