"use client";

// INVYONE 대시보드(=사용자 메뉴) 뷰
// - URL: /{seq}  (회사별 자동 시퀀스, 메뉴 그 자체)
// - menuSeq 로 사용자 대시보드 목록에서 매칭 → OBJID 획득 → DashboardLayout 렌더

import { use, useEffect, useState } from "react";
import { DashboardLayout } from "@/components/dash/DashboardLayout";
import { getDashboardList } from "@/lib/api/dashMenu";

interface PageProps {
  params: Promise<{ menuSeq: string }>;
}

export default function MenuSeqPage({ params }: PageProps) {
  const { menuSeq } = use(params);
  const isNumeric = /^\d+$/.test(menuSeq);

  const [objid, setObjid] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [missing, setMissing] = useState(false);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);

  useEffect(() => {
    if (!isNumeric) {
      setLoading(false);
      setMissing(true);
      return;
    }
    (async () => {
      try {
        console.log("[MenuSeq] 조회 시작:", menuSeq);
        const result = await getDashboardList();
        console.log("[MenuSeq] getDashboardList 응답:", result);
        const list: Record<string, any>[] = result?.list ?? [];
        const wanted = `/${menuSeq}`;
        const match = list.find((d) => (d.menu_url ?? d.MENU_URL) === wanted);
        console.log("[MenuSeq] 매칭:", { wanted, matched: match, listCount: list.length });
        if (match) {
          setObjid(String(match.objid ?? match.OBJID));
        } else {
          setMissing(true);
          setErrorMsg(`'/${menuSeq}' 에 해당하는 대시보드를 목록(${list.length}개)에서 찾지 못했습니다.`);
        }
      } catch (err: any) {
        console.error("[MenuSeq] 조회 실패:", err);
        setMissing(true);
        setErrorMsg(`대시보드 목록 조회 실패: ${err?.response?.status ?? ""} ${err?.message ?? err}`);
      } finally {
        setLoading(false);
      }
    })();
  }, [menuSeq, isNumeric]);

  if (loading) {
    return (
      <div className="flex h-full w-full items-center justify-center text-sm text-muted-foreground">
        대시보드 로드 중...
      </div>
    );
  }

  if (missing || !objid) {
    return (
      <div className="flex h-full w-full flex-col items-center justify-center gap-3 p-8 text-center">
        <div className="text-4xl">📋</div>
        <div className="text-base font-semibold text-foreground">
          대시보드를 찾을 수 없습니다
        </div>
        <div className="max-w-md text-xs text-muted-foreground">
          경로: <code className="rounded bg-muted px-1.5 py-0.5">/{menuSeq}</code>
          {errorMsg ? <div className="mt-2">{errorMsg}</div> : null}
        </div>
      </div>
    );
  }

  return <DashboardLayout dashboardId={objid} />;
}
