"use client";

import { useEffect, useState, useCallback } from "react";
import { useParams } from "next/navigation";
import { DndProvider } from "react-dnd";
import { useTabStore } from "@/stores/tabStore";
import { useTabId } from "@/contexts/TabIdContext";
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, useReportDesigner } from "@/contexts/ReportDesignerContext";
import { ComponentSettingsModal } from "@/components/report/designer/modals/ComponentSettingsModal";
import { reportApi } from "@/lib/api/reportApi";
import { useToast } from "@/hooks/use-toast";
import { Loader2 } from "lucide-react";

const BREAKPOINT_COLLAPSE_LEFT = 1200;
const BREAKPOINT_COLLAPSE_ALL = 900;

function DesignerLayout() {
  const {
    setIsPageListCollapsed,
    setIsLeftPanelCollapsed,
    setIsRightPanelCollapsed,
  } = useReportDesigner();

  const handleResize = useCallback(() => {
    const w = window.innerWidth;
    if (w < BREAKPOINT_COLLAPSE_ALL) {
      setIsPageListCollapsed(true);
      setIsLeftPanelCollapsed(true);
      setIsRightPanelCollapsed(true);
    } else if (w < BREAKPOINT_COLLAPSE_LEFT) {
      setIsPageListCollapsed(true);
      setIsLeftPanelCollapsed(false);
      setIsRightPanelCollapsed(false);
    }
  }, [setIsPageListCollapsed, setIsLeftPanelCollapsed, setIsRightPanelCollapsed]);

  useEffect(() => {
    handleResize();
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, [handleResize]);

  return (
    <div className="flex h-screen min-w-[768px] flex-col overflow-hidden bg-gray-50">
      <ReportDesignerToolbar />

      <div className="flex min-h-0 flex-1 overflow-hidden">
        <PageListPanel />
        <ReportDesignerLeftPanel />
        <ReportDesignerCanvas />
        <ReportDesignerRightPanel />
      </div>

      <ComponentSettingsModal />
    </div>
  );
}

interface ReportDesignerPageProps {
  adminParams?: { reportId?: string };
}

export default function ReportDesignerPage({ adminParams }: ReportDesignerPageProps) {
  const routeParams = useParams();
  const reportId = adminParams?.reportId || (routeParams.reportId as string);
  const [isLoading, setIsLoading] = useState(true);
  const { toast } = useToast();
  const closeTab = useTabStore((s) => s.closeTab);
  const currentTabId = useTabId();

  const closeDesignerTab = useCallback(() => {
    if (currentTabId) {
      closeTab(currentTabId);
    }
  }, [currentTabId, closeTab]);

  useEffect(() => {
    const loadReport = async () => {
      if (reportId === "new") {
        setIsLoading(false);
        return;
      }

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

    if (reportId) {
      loadReport();
    }
  }, [reportId, closeDesignerTab, 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 (
    <div id="report-designer-dnd-root">
      <DndProvider backend={HTML5Backend}>
        <ReportDesignerProvider reportId={reportId}>
          <DesignerLayout />
        </ReportDesignerProvider>
      </DndProvider>
    </div>
  );
}
