"use client";

import React, { useEffect, useState } from "react";
import { useParams, useSearchParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Loader2, ArrowLeft, Smartphone, Tablet, RotateCcw, RotateCw } from "lucide-react";
import { screenApi } from "@/lib/api/screen";
import { ScreenDefinition } from "@/types/screen";
import { useRouter } from "next/navigation";
import { showErrorToast } from "@/lib/utils/toastUtils";
import { ScreenPreviewProvider } from "@/contexts/ScreenPreviewContext";
import { useAuth } from "@/hooks/useAuth";
import { TableOptionsProvider } from "@/contexts/TableOptionsContext";
import { TableSearchWidgetHeightProvider } from "@/contexts/TableSearchWidgetHeightContext";
import { ScreenContextProvider } from "@/contexts/ScreenContext";
import { SplitPanelProvider } from "@/lib/registry/components/split-panel-layout/SplitPanelContext";
import { ActiveTabProvider } from "@/contexts/ActiveTabContext";
import {
  PopLayoutData,
  GridMode,
  isPopLayout,
  createEmptyLayout,
  BLOCK_GAP,
  BLOCK_PADDING,
  detectGridMode,
} from "@/components/pop/designer/types/pop-layout";
import { loadLegacyLayout } from "@/components/pop/designer/utils/legacyLoader";
// POP 컴포넌트 자동 등록 (레지스트리 초기화 - PopRenderer보다 먼저 import)
import "@/lib/registry/pop-components";
import PopViewerWithModals from "@/components/pop/viewer/PopViewerWithModals";
import { 
  useResponsiveModeWithOverride,
  type DeviceType,
} from "@/hooks/useDeviceOrientation";

// 디바이스별 크기 (너비만, 높이는 콘텐츠 기반)
const DEVICE_SIZES: Record<DeviceType, Record<"landscape" | "portrait", { width: number; label: string }>> = {
  mobile: {
    landscape: { width: 600, label: "모바일 가로" },
    portrait: { width: 375, label: "모바일 세로" },
  },
  tablet: {
    landscape: { width: 1024, label: "태블릿 가로" },
    portrait: { width: 820, label: "태블릿 세로" },
  },
};

// 모드 키 변환
const getModeKey = (device: DeviceType, isLandscape: boolean): GridMode => {
  if (device === "tablet") {
    return isLandscape ? "tablet_landscape" : "tablet_portrait";
  }
  return isLandscape ? "mobile_landscape" : "mobile_portrait";
};

// ========================================
// 메인 컴포넌트 (v5 그리드 시스템 전용)
// ========================================

function PopScreenViewPage() {
  const params = useParams();
  const searchParams = useSearchParams();
  const router = useRouter();
  const screenId = parseInt(params.screenId as string, 10);
  const isValidScreenId = !isNaN(screenId) && screenId > 0;

  const isPreviewMode = searchParams.get("preview") === "true";

  // 반응형 모드 감지 (화면 크기에 따라 tablet/mobile, landscape/portrait 자동 전환)
  // 프리뷰 모드에서는 수동 전환 가능
  const { mode, setDevice, setOrientation, isAutoDetect } = useResponsiveModeWithOverride(
    isPreviewMode ? "tablet" : undefined,
    isPreviewMode ? true : undefined
  );

  // 현재 모드 정보
  const deviceType = mode.device;
  const isLandscape = mode.isLandscape;

  const { user } = useAuth();

  const [screen, setScreen] = useState<ScreenDefinition | null>(null);
  const [layout, setLayout] = useState<PopLayoutData>(createEmptyLayout());
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 실제 브라우저 너비 (모드 감지용)
  const [rawWidth, setRawWidth] = useState(1024);
  
  useEffect(() => {
    const updateWidth = () => setRawWidth(window.innerWidth);
    updateWidth();
    window.addEventListener("resize", updateWidth);
    return () => window.removeEventListener("resize", updateWidth);
  }, []);

  // 모드 결정
  const currentModeKey = isPreviewMode 
    ? getModeKey(deviceType, isLandscape)
    : detectGridMode(rawWidth);

  // 디자이너와 동일한 기준 너비 사용 (모드별 고정 너비)
  const MODE_REFERENCE_WIDTH: Record<GridMode, number> = {
    mobile_portrait: 375,
    mobile_landscape: 600,
    tablet_portrait: 820,
    tablet_landscape: 1024,
  };
  const viewportWidth = isPreviewMode
    ? DEVICE_SIZES[deviceType][isLandscape ? "landscape" : "portrait"].width
    : MODE_REFERENCE_WIDTH[currentModeKey];

  // 화면 및 POP 레이아웃 로드
  useEffect(() => {
    const loadScreen = async () => {
      try {
        setLoading(true);
        setError(null);

        const screenData = await screenApi.getScreen(screenId);
        setScreen(screenData);

        try {
          const popLayout = await screenApi.getLayoutPop(screenId);

          if (popLayout && isPopLayout(popLayout)) {
            const v6Layout = loadLegacyLayout(popLayout);
            setLayout(v6Layout);
          } else if (popLayout) {
            setLayout(createEmptyLayout());
          } else {
            setLayout(createEmptyLayout());
          }
        } catch {
          setLayout(createEmptyLayout());
        }
      } catch (error) {
        setError("화면을 불러오는데 실패했습니다.");
        showErrorToast("POP 화면을 불러오는 데 실패했습니다", error, { guidance: "화면 설정을 확인하거나 잠시 후 다시 시도해 주세요." });
      } finally {
        setLoading(false);
      }
    };

    if (isValidScreenId) {
      loadScreen();
    } else if (params.screenId) {
      setError("유효하지 않은 화면 ID입니다.");
      setLoading(false);
    }
  }, [screenId, isValidScreenId]);

  // 뷰어 모드에서도 컴포넌트 크기 변경 지원 (더보기 등)
  const handleRequestResize = React.useCallback((componentId: string, newRowSpan: number, newColSpan?: number) => {
    setLayout((prev) => {
      const comp = prev.components[componentId];
      if (!comp) return prev;
      return {
        ...prev,
        components: {
          ...prev.components,
          [componentId]: {
            ...comp,
            position: {
              ...comp.position,
              rowSpan: newRowSpan,
              ...(newColSpan !== undefined ? { colSpan: newColSpan } : {}),
            },
          },
        },
      };
    });
  }, []);

  const currentDevice = DEVICE_SIZES[deviceType][isLandscape ? "landscape" : "portrait"];
  const hasComponents = Object.keys(layout.components).length > 0;

  if (loading) {
    return (
      <div className="flex h-screen w-full items-center justify-center bg-muted">
        <div className="text-center">
          <Loader2 className="mx-auto h-10 w-10 animate-spin text-primary" />
          <p className="mt-4 text-muted-foreground">POP 화면 로딩 중...</p>
        </div>
      </div>
    );
  }

  if (error || !screen) {
    return (
      <div className="flex h-screen w-full items-center justify-center bg-muted">
        <div className="text-center max-w-md p-6">
          <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-destructive/10">
            <span className="text-2xl">!</span>
          </div>
          <h2 className="mb-2 text-xl font-bold text-foreground">화면을 찾을 수 없습니다</h2>
          <p className="mb-4 text-muted-foreground">{error || "요청하신 POP 화면이 존재하지 않습니다."}</p>
          <Button onClick={() => router.back()} variant="outline">
            <ArrowLeft className="mr-2 h-4 w-4" />
            돌아가기
          </Button>
        </div>
      </div>
    );
  }

  return (
    <ScreenPreviewProvider isPreviewMode={isPreviewMode}>
      <ActiveTabProvider>
        <TableOptionsProvider>
          <div className="h-screen bg-muted flex flex-col">
            {/* 상단 툴바 (프리뷰 모드에서만) */}
            {isPreviewMode && (
              <div className="sticky top-0 z-50 bg-white border-b shadow-sm">
                <div className="flex items-center justify-between px-4 py-2">
                  <div className="flex items-center gap-2">
                    <Button variant="ghost" size="sm" onClick={() => window.close()}>
                      <ArrowLeft className="h-4 w-4 mr-1" />
                      닫기
                    </Button>
                    <span className="text-sm font-medium">{screen.screenName}</span>
                    <span className="text-xs text-muted-foreground/70">
                      ({currentModeKey.replace("_", " ")})
                    </span>
                  </div>

                  <div className="flex items-center gap-2">
                    <div className="flex items-center gap-1 bg-muted rounded-lg p-1">
                      <Button
                        variant={deviceType === "mobile" ? "default" : "ghost"}
                        size="sm"
                        onClick={() => setDevice("mobile")}
                        className="gap-1"
                      >
                        <Smartphone className="h-4 w-4" />
                        모바일
                      </Button>
                      <Button
                        variant={deviceType === "tablet" ? "default" : "ghost"}
                        size="sm"
                        onClick={() => setDevice("tablet")}
                        className="gap-1"
                      >
                        <Tablet className="h-4 w-4" />
                        태블릿
                      </Button>
                    </div>

                    <div className="flex items-center gap-1 bg-muted rounded-lg p-1">
                      <Button
                        variant={isLandscape ? "default" : "ghost"}
                        size="sm"
                        onClick={() => setOrientation(true)}
                        className="gap-1"
                      >
                        <RotateCw className="h-4 w-4" />
                        가로
                      </Button>
                      <Button
                        variant={!isLandscape ? "default" : "ghost"}
                        size="sm"
                        onClick={() => setOrientation(false)}
                        className="gap-1"
                      >
                        <RotateCcw className="h-4 w-4" />
                        세로
                      </Button>
                    </div>

                    {/* 자동 감지 모드 버튼 */}
                    <Button
                      variant={isAutoDetect ? "default" : "outline"}
                      size="sm"
                      onClick={() => {
                        setDevice(undefined);
                        setOrientation(undefined);
                      }}
                      className="gap-1"
                    >
                      자동
                    </Button>
                  </div>

                  <Button variant="ghost" size="sm" onClick={() => window.location.reload()}>
                    <RotateCcw className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            )}

            {/* 일반 모드 네비게이션 바 제거 (프로필 컴포넌트에서 PC 모드 전환 가능) */}

            {/* POP 화면 컨텐츠 */}
            <div className={`flex-1 flex flex-col overflow-auto ${isPreviewMode ? "py-4 items-center" : "bg-background"}`}>

              <div
                className={`bg-background transition-all duration-300 ${isPreviewMode ? "shadow-2xl rounded-3xl overflow-auto border-8 border-foreground" : "w-full min-h-full"}`}
                style={isPreviewMode ? {
                  width: currentDevice.width,
                  maxHeight: "80vh",
                  flexShrink: 0,
                } : undefined}
              >
                {/* v5 그리드 렌더러 */}
                {hasComponents ? (
                  <div 
                    className="min-h-full"
                    style={isPreviewMode ? { maxWidth: currentDevice.width, margin: "0 auto" } : undefined}
                  >
                    {(() => {
                      const adjustedGap = BLOCK_GAP;
                      const adjustedPadding = BLOCK_PADDING;
                      
                      return (
                        <PopViewerWithModals
                          layout={layout}
                          viewportWidth={isPreviewMode ? currentDevice.width : viewportWidth}
                          screenId={String(screenId)}
                          currentMode={currentModeKey}
                          overrideGap={adjustedGap}
                          overridePadding={adjustedPadding}
                          onRequestResize={handleRequestResize}
                          currentScreenId={screenId}
                        />
                      );
                    })()}
                  </div>
                ) : (
                  // 빈 화면
                  <div className="flex flex-col items-center justify-center min-h-[400px] p-8 text-center">
                    <div className="w-16 h-16 rounded-full bg-muted flex items-center justify-center mb-4">
                      <Smartphone className="h-8 w-8 text-muted-foreground/70" />
                    </div>
                    <h3 className="text-lg font-semibold text-foreground mb-2">
                      화면이 비어있습니다
                    </h3>
                    <p className="text-sm text-muted-foreground max-w-xs">
                      POP 화면 디자이너에서 컴포넌트를 추가하여 화면을 구성하세요.
                    </p>
                  </div>
                )}
              </div>
            </div>
          </div>
        </TableOptionsProvider>
      </ActiveTabProvider>
    </ScreenPreviewProvider>
  );
}

// Provider 래퍼
export default function PopScreenViewPageWrapper() {
  return (
    <TableSearchWidgetHeightProvider>
      <ScreenContextProvider>
        <SplitPanelProvider>
          <PopScreenViewPage />
        </SplitPanelProvider>
      </ScreenContextProvider>
    </TableSearchWidgetHeightProvider>
  );
}
