"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
import { ReportDesignerToolbar } from "@/components/report/designer/ReportDesignerToolbar";
import { PageListPanel } from "@/components/report/designer/PageListPanel";
import { ReportDesignerLeftPanel } from "@/components/report/designer/ReportDesignerLeftPanel";
import { ReportDesignerCanvas } from "@/components/report/designer/ReportDesignerCanvas";
import { ReportDesignerRightPanel } from "@/components/report/designer/ReportDesignerRightPanel";
import { ReportDesignerProvider } from "@/contexts/ReportDesignerContext";
import { reportApi } from "@/lib/api/reportApi";
import { useToast } from "@/hooks/use-toast";
import { Loader2 } from "lucide-react";

export default function ReportDesignerPage() {
  const params = useParams();
  const router = useRouter();
  const reportId = params.reportId as string;
  const [isLoading, setIsLoading] = useState(true);
  const { toast } = useToast();

  useEffect(() => {
    const loadReport = async () => {
      // 'new'는 새 리포트 생성 모드
      if (reportId === "new") {
        setIsLoading(false);
        return;
      }

      try {
        const response = await reportApi.getReportById(reportId);
        if (!response.success) {
          toast({
            title: "오류",
            description: "리포트를 찾을 수 없습니다.",
            variant: "destructive",
          });
          router.push("/admin/screenMng/reportList");
        }
      } catch (error: any) {
        toast({
          title: "오류",
          description: error.message || "리포트를 불러오는데 실패했습니다.",
          variant: "destructive",
        });
        router.push("/admin/screenMng/reportList");
      } finally {
        setIsLoading(false);
      }
    };

    if (reportId) {
      loadReport();
    }
  }, [reportId, router, toast]);

  if (isLoading) {
    return (
      <div className="flex h-screen items-center justify-center">
        <Loader2 className="text-muted-foreground h-8 w-8 animate-spin" />
      </div>
    );
  }

  return (
    <DndProvider backend={HTML5Backend}>
      <ReportDesignerProvider reportId={reportId}>
        <div className="flex h-screen flex-col overflow-hidden bg-muted">
          {/* 상단 툴바 */}
          <ReportDesignerToolbar />

          {/* 메인 영역 */}
          <div className="flex flex-1 overflow-hidden">
            {/* 페이지 목록 패널 */}
            <PageListPanel />

            {/* 좌측 패널 (템플릿, 컴포넌트) */}
            <ReportDesignerLeftPanel />

            {/* 중앙 캔버스 */}
            <ReportDesignerCanvas />

            {/* 우측 패널 (속성) */}
            <ReportDesignerRightPanel />
          </div>
        </div>
      </ReportDesignerProvider>
    </DndProvider>
  );
}
