/**
 * 管理后台子页统一顶栏
 *
 * 用于 /admin/me、/admin/ai-providers、/admin/system-health 等独立路由的子页，
 * 提供与主后台一致的视觉高度（49px）+ 面包屑 + 返回按钮。
 *
 * 返回逻辑：
 *  - 进入时优先读取 location.state.from（{ path, label }）
 *  - 否则读取 sessionStorage（key: admin-subpage-origin:{scope}）
 *  - 都没有则使用 fallback
 *  并自动写入 sessionStorage，便于刷新 / 多级跳转后仍能正确回退。
 */
import { useEffect, useMemo, ReactNode } from "react";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { Button } from "@/components/ui/button";
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from "@/components/ui/breadcrumb";
import { ArrowLeft } from "lucide-react";

export interface Origin {
  path: string;
  label: string;
}

interface Props {
  /** 当前页标题（面包屑末位） */
  title: string;
  /** sessionStorage 命名空间，避免多个子页串扰 */
  scope: string;
  /** 没有 state / cache 时的默认来源 */
  fallback?: Origin;
  /** 顶栏右侧自定义内容 */
  actions?: ReactNode;
}

const DEFAULT_FALLBACK: Origin = {
  path: "/admin/dashboard",
  label: "店长工作台",
};

export function useResolvedOrigin(scope: string, fallback: Origin = DEFAULT_FALLBACK): Origin {
  const location = useLocation();
  const cacheKey = `admin-subpage-origin:${scope}`;

  const origin = useMemo<Origin>(() => {
    const stateOrigin = (location.state as { from?: Origin } | null)?.from;
    if (stateOrigin?.path && stateOrigin?.label) return stateOrigin;
    try {
      const cached = sessionStorage.getItem(cacheKey);
      if (cached) {
        const parsed = JSON.parse(cached) as Origin;
        if (parsed?.path && parsed?.label) return parsed;
      }
    } catch {
      /* ignore */
    }
    return fallback;
  }, [location.state, cacheKey, fallback]);

  useEffect(() => {
    try {
      sessionStorage.setItem(cacheKey, JSON.stringify(origin));
    } catch {
      /* ignore */
    }
  }, [origin, cacheKey]);

  return origin;
}

export function AdminSubpageHeader({ title, scope, fallback, actions }: Props) {
  const navigate = useNavigate();
  const origin = useResolvedOrigin(scope, fallback);

  return (
    <header className="h-[49px] border-b bg-card flex items-center px-4 gap-3 shrink-0">
      <Button
        variant="ghost"
        size="sm"
        onClick={() => navigate(origin.path)}
        className="flex items-center gap-1.5"
        title={`返回${origin.label}`}
      >
        <ArrowLeft className="h-4 w-4" />
        <span className="hidden sm:inline">返回{origin.label}</span>
      </Button>
      <div className="h-5 w-px bg-border" />
      <Breadcrumb>
        <BreadcrumbList>
          <BreadcrumbItem>
            <BreadcrumbLink asChild>
              <Link to={origin.path}>{origin.label}</Link>
            </BreadcrumbLink>
          </BreadcrumbItem>
          <BreadcrumbSeparator />
          <BreadcrumbItem>
            <BreadcrumbPage>{title}</BreadcrumbPage>
          </BreadcrumbItem>
        </BreadcrumbList>
      </Breadcrumb>
      <div className="ml-auto flex items-center gap-2">{actions}</div>
    </header>
  );
}
