"use client";

import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { DashboardHeader } from "./DashboardHeader";
import { NoticeBanner } from "./NoticeBanner";
import { KpiBar } from "./KpiBar";
import { MenuGrid } from "./MenuGrid";
import { ActivityList } from "./ActivityList";
import { NoticeList } from "./NoticeList";
import { DashboardFooter } from "./DashboardFooter";
import { MenuItem as DashboardMenuItem } from "./types";
import { menuApi, PopMenuItem } from "@/lib/api/menu";
import {
  KPI_ITEMS,
  MENU_ITEMS,
  ACTIVITY_ITEMS,
  NOTICE_ITEMS,
  NOTICE_MARQUEE_TEXT,
} from "./data";
import "./dashboard.css";

const CATEGORY_COLORS: DashboardMenuItem["category"][] = [
  "production",
  "material",
  "quality",
  "equipment",
  "safety",
];

function convertPopMenuToMenuItem(item: PopMenuItem, index: number): DashboardMenuItem {
  return {
    id: item.objid,
    title: item.menu_name_kor,
    count: 0,
    description: item.menu_desc?.replace("[POP]", "").trim() || "",
    status: "",
    category: CATEGORY_COLORS[index % CATEGORY_COLORS.length],
    href: item.menu_url || "#",
  };
}

export function PopDashboard() {
  const router = useRouter();
  const [theme, setTheme] = useState<"dark" | "light">("dark");
  const [menuItems, setMenuItems] = useState<DashboardMenuItem[]>(MENU_ITEMS);

  useEffect(() => {
    const savedTheme = localStorage.getItem("popTheme") as "dark" | "light" | null;
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);

  // API에서 POP 메뉴 로드
  useEffect(() => {
    const loadPopMenus = async () => {
      try {
        const response = await menuApi.getPopMenus();
        if (response.success && response.data && response.data.childMenus.length > 0) {
          const converted = response.data.childMenus.map(convertPopMenuToMenuItem);
          setMenuItems(converted);
        }
      } catch {
        // API 실패 시 기존 하드코딩 데이터 유지
      }
    };
    loadPopMenus();
  }, []);

  const handleThemeToggle = () => {
    const newTheme = theme === "dark" ? "light" : "dark";
    setTheme(newTheme);
    localStorage.setItem("popTheme", newTheme);
  };

  const handleUserClick = () => {
    if (confirm("로그아웃 하시겠습니까?")) {
      alert("로그아웃되었습니다.");
    }
  };

  const handlePcModeClick = () => {
    router.push("/");
  };

  const handleActivityMore = () => {
    alert("전체 활동 내역 화면으로 이동합니다.");
  };

  const handleNoticeMore = () => {
    alert("전체 공지사항 화면으로 이동합니다.");
  };

  return (
    <div className={`pop-dashboard-container ${theme === "light" ? "light" : ""}`}>
      <div className="pop-dashboard">
        <DashboardHeader
          theme={theme}
          weather={{ temp: "18°C", description: "맑음" }}
          user={{ name: "김철수", role: "생산1팀", avatar: "김" }}
          company={{ name: "탑씰", subTitle: "현장 관리 시스템" }}
          onThemeToggle={handleThemeToggle}
          onUserClick={handleUserClick}
          onPcModeClick={handlePcModeClick}
        />

        <NoticeBanner text={NOTICE_MARQUEE_TEXT} />

        <KpiBar items={KPI_ITEMS} />

        <MenuGrid items={menuItems} />

        <div className="pop-dashboard-bottom-section">
          <ActivityList items={ACTIVITY_ITEMS} onMoreClick={handleActivityMore} />
          <NoticeList items={NOTICE_ITEMS} onMoreClick={handleNoticeMore} />
        </div>

        <DashboardFooter
          companyName="탑씰"
          version="1.0.0"
          emergencyContact="042-XXX-XXXX"
        />
      </div>
    </div>
  );
}

