import { useEffect, useMemo, useState } from 'react'
import { Link } from 'react-router-dom'
import { Card } from 'antd'
import { AppstoreOutlined } from '@ant-design/icons'
import { SITEMAP_TITLE_TO_ID } from '../../menu'
import { fetchMyMenus } from '../../api/auth'

type SitemapChild = {
  label: string
  to?: string
  children?: { label: string; to: string }[]
}

type SitemapSection = {
  letter: string
  title: string
  to?: string
  items?: SitemapChild[]
}

/** 비즈케어홈즈 원본 전체보기(사이트맵) 구성 */
const SITEMAP_COLUMNS: SitemapSection[][] = [
  [
    { letter: 'A', title: '대시보드', to: '/care/main' },
    {
      letter: 'B',
      title: '상품관리',
      items: [
        {
          label: '인터넷상품',
          to: '/care/product/internet',
          children: [
            { label: '인터넷', to: '/care/product/internet?category=인터넷' },
            { label: 'TV', to: '/care/product/internet?category=TV' },
            { label: '전화', to: '/care/product/internet?category=전화' },
            { label: '와이파이', to: '/care/product/internet?category=와이파이' },
            { label: '스마트홈', to: '/care/product/internet?category=스마트홈' },
            { label: '기타', to: '/care/product/internet?category=기타' },
          ] },
        {
          label: '홈렌탈상품',
          to: '/care/product/home',
          children: [
            { label: '정수기', to: '/care/product/home?category=정수기' },
            { label: '공기청정기', to: '/care/product/home?category=공기청정기' },
            { label: '비데', to: '/care/product/home?category=비데' },
            { label: '매트리스', to: '/care/product/home?category=매트리스' },
            { label: '가전', to: '/care/product/home?category=가전' },
            { label: '기타', to: '/care/product/home?category=기타' },
          ] },
        { label: '상품이력', to: '/care/product/log' },
      ] },
  ],
  [
    {
      letter: 'C',
      title: '계약관리',
      items: [
        { label: '인터넷접수', to: '/care/contract/internet' },
        { label: '홈렌탈접수', to: '/care/contract/home' },
        { label: '계약이력', to: '/care/contract/log' },
      ] },
    {
      letter: 'R',
      title: '접수관리',
      items: [
        { label: '접수리스트', to: '/care/reception/list' },
      ] },
    {
      letter: 'D',
      title: '정산관리',
      items: [
        { label: '정산서발행', to: '/care/invoice/publish' },
        { label: '나의정산서', to: '/care/invoice/my' },
        { label: '정산서이력', to: '/care/invoice/log' },
      ] },
    {
      letter: 'E',
      title: '일정관리',
      items: [
        { label: '캘린더', to: '/care/pending/calendar' },
        { label: '일정관리', to: '/care/pending/pending' },
        { label: '일정이력', to: '/care/pending/log' },
      ] },
    {
      letter: 'F',
      title: '예약관리',
      items: [
        { label: '예약관리', to: '/care/booking/booking' },
        { label: '예약이력', to: '/care/booking/log' },
      ] },
  ],
  [
    {
      letter: 'G',
      title: '고객관리',
      items: [
        { label: '고객관리', to: '/care/customer/customer' },
        { label: '고객이력', to: '/care/customer/log' },
      ] },
    {
      letter: 'H',
      title: '장부관리',
      items: [
        {
          label: '간편장부',
          to: '/care/abooks/abooks-mon',
          children: [
            { label: '월별 간편장부', to: '/care/abooks/abooks-mon?view=month' },
            { label: '상세 간편장부', to: '/care/abooks/abooks-mon?view=detail' },
          ] },
        { label: '장부이력', to: '/care/abooks/log' },
      ] },
    {
      letter: 'I',
      title: '통계관리',
      items: [
        { label: '원클릭리포트', to: '/care/report/daily' },
        { label: '월간리포트', to: '/care/report/monthly' },
        { label: '인터넷통계', to: '/care/report/internet' },
        { label: '홈렌탈통계', to: '/care/report/home' },
        { label: '직원별통계', to: '/care/report/member' },
        { label: '거래처별통계', to: '/care/report/agency' },
      ] },
  ],
  [
    {
      letter: 'J',
      title: '환경설정',
      items: [
        { label: '거래처관리', to: '/care/setting/agency' },
        { label: '직원관리', to: '/care/setting/member' },
        { label: '기본설정', to: '/care/setting/preference' },
        { label: '권한설정', to: '/care/setting/level' },
        { label: '상부점관리', to: '/care/setting/partner1' },
        { label: '하부점관리', to: '/care/setting/partner2' },
      ] },
    {
      letter: 'L',
      title: '고객센터',
      items: [
        { label: '공지사항', to: '/care/cs/notice' },
        { label: '사용문의', to: '/care/cs/question' },
      ] },
    {
      letter: 'M',
      title: '게시판',
      items: [{ label: '사내게시판', to: '/care/bbs/bbs' }] },
  ],
]

function SectionTitle({ section }: { section: SitemapSection }) {
  const text = `${section.letter}. ${section.title}`
  if (section.to) {
    return (
      <h3 className="sitemap-section-title">
        <Link to={section.to}>{text}</Link>
      </h3>
    )
  }
  return <h3 className="sitemap-section-title">{text}</h3>
}

function SitemapItem({ item }: { item: SitemapChild }) {
  return (
    <li>
      {item.to ? (
        <Link to={item.to} className="sitemap-link">
          {item.label}
        </Link>
      ) : (
        <span className="sitemap-text">{item.label}</span>
      )}
      {item.children && item.children.length > 0 && (
        <ul className="sitemap-sub">
          {item.children.map((child) => (
            <li key={child.to} className="sitemap-nested">
              <span className="sitemap-dash">- </span>
              <Link to={child.to} className="sitemap-link">
                {child.label}
              </Link>
            </li>
          ))}
        </ul>
      )}
    </li>
  )
}

export default function SitemapPage() {
  const [allowedMenus, setAllowedMenus] = useState<string[] | null>(null)

  useEffect(() => {
    let cancelled = false
    fetchMyMenus()
      .then((res) => {
        if (!cancelled) setAllowedMenus(res.menus || [])
      })
      .catch(() => {
        if (cancelled) return
        try {
          const cached = localStorage.getItem('allowedMenus')
          if (cached) setAllowedMenus(JSON.parse(cached) as string[])
          else setAllowedMenus(null)
        } catch {
          setAllowedMenus(null)
        }
      })
    return () => { cancelled = true }
  }, [])

  const columns = useMemo(() => {
    if (!allowedMenus) return SITEMAP_COLUMNS
    const set = new Set(allowedMenus)
    return SITEMAP_COLUMNS.map((col) =>
      col.filter((section) => {
        const id = SITEMAP_TITLE_TO_ID[section.title]
        return !id || set.has(id)
      }),
    ).filter((col) => col.length > 0)
  }, [allowedMenus])

  return (
    <div className="stock-page sitemap-page">
      <div className="stock-title">
        <div>
          <h2>
            <AppstoreOutlined className="product-title-icon" />
            전체보기
          </h2>
          <p>비즈케어홈즈의 모든 서비스를 소개드립니다. 원하시는 메뉴를 클릭해주세요.</p>
        </div>
      </div>

      <Card className="stock-table-card sitemap-card" size="small">
        <div className="sitemap-grid">
          {columns.map((col, idx) => (
            <div key={idx} className="sitemap-col">
              {col.map((section) => (
                <div key={`${section.letter}-${section.title}`} className="sitemap-section">
                  <SectionTitle section={section} />
                  {section.items && section.items.length > 0 && (
                    <ul className="sitemap-list">
                      {section.items.map((item) => (
                        <SitemapItem key={`${section.letter}-${item.label}`} item={item} />
                      ))}
                    </ul>
                  )}
                </div>
              ))}
            </div>
          ))}
        </div>
      </Card>

      <footer className="sitemap-footer">
        <p>(주) 비즈케어 | 사업자등록번호 : 000-00-00000</p>
        <p>연락처 : 0000-0000</p>
        <p>Copyright @ 2025 BizCare All Right Reversed.</p>
      </footer>
    </div>
  )
}
