import React, { useEffect, useMemo, useState } from 'react';
import { Tour, type TourProps } from 'antd';
import { getRoleDomains } from '../../auth/menu-policy';

const STORAGE_KEY = 'onboarding_seen_v1';

export interface RoleTourProps {
  roles: readonly string[];
  permissions: readonly string[];
  enabled?: boolean;
}

interface TourStep {
  target: () => HTMLElement;
  title: string;
  description: string;
}

/** 按 antd Menu 渲染的菜单项查找目标元素（菜单项 title 属性即菜单文案） */
function menuTarget(label: string): () => HTMLElement {
  return () => document.querySelector<HTMLElement>(`[title="${label}"]`) as HTMLElement;
}

/** 右上角 AI 助手按钮 */
const aiTarget = (): HTMLElement =>
  document.querySelector<HTMLElement>('button[aria-label="打开 AI 助理"]') as HTMLElement;

/** 各角色的引导步骤（声明式，按角色域组装） */
const TEACHER_STEPS: TourStep[] = [
  {
    target: menuTarget('今日教学'),
    title: '今日教学',
    description: '在这里查看今天的课程安排。课程开始后可以拉取钉钉考勤并点名。',
  },
  {
    target: menuTarget('课程考勤'),
    title: '课程考勤',
    description: '查看历史考勤记录，课程截止后系统会自动结算缺勤。',
  },
];

const ACADEMIC_STEPS: TourStep[] = [
  {
    target: menuTarget('学生管理'),
    title: '学生管理',
    description: '管理学生档案：可单个录入、Excel 批量导入，或用 AI 助手帮你录入。',
  },
  {
    target: menuTarget('班级管理'),
    title: '班级管理',
    description: '学生入学后先分班，再排课、考勤，形成完整教学闭环。',
  },
];

const ACCOMMODATION_STEPS: TourStep[] = [
  {
    target: menuTarget('住宿总览'),
    title: '住宿总览',
    description: '可视化查看各宿舍入住情况，支持历史日期回溯和查寝。',
  },
  {
    target: menuTarget('入住管理'),
    title: '入住管理',
    description: '学生入住/退宿/换宿都在这里办理。入住后再录费用、生成账单。',
  },
  {
    target: menuTarget('账单管理'),
    title: '账单管理',
    description: '每月生成账单、确认并标记已付，完成「住宿→计费」闭环。',
  },
];

const CLASSROOM_STEPS: TourStep[] = [
  {
    target: menuTarget('教室排期'),
    title: '教室排期',
    description: '查看教室占用与排期，避免时间冲突。',
  },
  {
    target: menuTarget('租赁订单'),
    title: '租赁订单',
    description: '管理教室租赁订单与合同，跟踪租期与状态。',
  },
];

const SYSTEM_STEPS: TourStep[] = [
  {
    target: menuTarget('账号管理'),
    title: '账号管理',
    description: '管理系统账号、角色与权限，为不同岗位分配对应能力。',
  },
];

const SUPER_STEPS: TourStep[] = [
  {
    target: menuTarget('数据面板'),
    title: '数据面板',
    description: '全局经营概览：入住率、收入、待办都在这里。',
  },
];

const AI_STEPS: TourStep[] = [
  {
    target: aiTarget,
    title: 'AI 助手',
    description:
      '有任何问题都可以问我。我可以帮你查询数据、录入学生、生成批量导入预览——写操作都会先经你确认。',
  },
];

function buildSteps(domains: Set<string>): TourStep[] {
  const steps: TourStep[] = [];
  const has = (key: string) => domains.has(key);

  if (has('super')) steps.unshift(...SUPER_STEPS);
  if (has('teacher')) steps.push(...TEACHER_STEPS);
  if (has('academic')) steps.push(...ACADEMIC_STEPS);
  if (has('accommodation')) steps.push(...ACCOMMODATION_STEPS);
  if (has('classroom')) steps.push(...CLASSROOM_STEPS);
  if (has('system') || has('super')) steps.push(...SYSTEM_STEPS);
  steps.push(...AI_STEPS);

  return steps;
}

/**
 * 首次登录角色引导：按用户角色展示核心业务闭环的 Tour。
 * 只对桌面端展示一次（localStorage 标记），可随时关闭。
 */
export const RoleTour: React.FC<RoleTourProps> = ({ roles, permissions, enabled = true }) => {
  const [open, setOpen] = useState(false);

  const domains = useMemo(() => getRoleDomains(roles, permissions), [roles, permissions]);
  const steps = useMemo(() => buildSteps(domains), [domains]);

  useEffect(() => {
    if (!enabled) return;
    if (window.localStorage.getItem(STORAGE_KEY)) return;
    if (window.innerWidth < 992) return; // 仅桌面端
    // 等菜单渲染完成后再弹引导
    const timer = window.setTimeout(() => setOpen(true), 600);
    return () => window.clearTimeout(timer);
  }, [enabled]);

  const handleFinish = () => {
    window.localStorage.setItem(STORAGE_KEY, '1');
    setOpen(false);
  };

  const config: TourProps = {
    open,
    onClose: handleFinish,
    // target 函数运行时返回 HTMLElement | null，与 antd 类型（不接受联合返回）做一次断言
    steps: steps as TourProps['steps'],
    placement: 'right',
    mask: true,
  };

  return <Tour {...config} />;
};

export default RoleTour;
