"use client";

import React, { useState, useEffect } from "react";
import {
  ResizableDialog,
  ResizableDialogContent,
  ResizableDialogHeader,
  ResizableDialogTitle,
  ResizableDialogDescription,
} from "@/components/ui/resizable-dialog";
import { InteractiveScreenViewerDynamic } from "@/components/screen/InteractiveScreenViewerDynamic";
import { screenApi } from "@/lib/api/screen";
import { ComponentData } from "@/types/screen";
import { toast } from "sonner";

interface ScreenModalState {
  isOpen: boolean;
  screenId: number | null;
  title: string;
  description?: string;
  size: "sm" | "md" | "lg" | "xl";
}

interface ScreenModalProps {
  className?: string;
}

export const ScreenModal: React.FC<ScreenModalProps> = ({ className }) => {
  const [modalState, setModalState] = useState<ScreenModalState>({
    isOpen: false,
    screenId: null,
    title: "",
    description: "",
    size: "md",
  });

  const [screenData, setScreenData] = useState<{
    components: ComponentData[];
    screenInfo: any;
  } | null>(null);

  const [loading, setLoading] = useState(false);
  const [screenDimensions, setScreenDimensions] = useState<{
    width: number;
    height: number;
    offsetX?: number;
    offsetY?: number;
  } | null>(null);

  // 폼 데이터 상태 추가
  const [formData, setFormData] = useState<Record<string, any>>({});

  // 화면의 실제 크기 계산 함수
  const calculateScreenDimensions = (components: ComponentData[]) => {
    if (components.length === 0) {
      return {
        width: 400,
        height: 300,
        offsetX: 0,
        offsetY: 0,
      };
    }

    // 모든 컴포넌트의 경계 찾기
    let minX = Infinity;
    let minY = Infinity;
    let maxX = -Infinity;
    let maxY = -Infinity;

    components.forEach((component) => {
      const x = parseFloat(component.position?.x?.toString() || "0");
      const y = parseFloat(component.position?.y?.toString() || "0");
      const width = parseFloat(component.size?.width?.toString() || "100");
      const height = parseFloat(component.size?.height?.toString() || "40");

      minX = Math.min(minX, x);
      minY = Math.min(minY, y);
      maxX = Math.max(maxX, x + width);
      maxY = Math.max(maxY, y + height);
    });

    // 실제 컨텐츠 크기 계산
    const contentWidth = maxX - minX;
    const contentHeight = maxY - minY;

    // 적절한 여백 추가
    const paddingX = 40;
    const paddingY = 40;

    const finalWidth = Math.max(contentWidth + paddingX, 400);
    const finalHeight = Math.max(contentHeight + paddingY, 300);

    return {
      width: Math.min(finalWidth, window.innerWidth * 0.95),
      height: Math.min(finalHeight, window.innerHeight * 0.9),
      offsetX: Math.max(0, minX - paddingX / 2), // 좌측 여백 고려
      offsetY: Math.max(0, minY - paddingY / 2), // 상단 여백 고려
    };
  };

  // 전역 모달 이벤트 리스너
  useEffect(() => {
    const handleOpenModal = (event: CustomEvent) => {
      const { screenId, title, description, size } = event.detail;
      setModalState({
        isOpen: true,
        screenId,
        title,
        description: description || "",
        size,
      });
    };

    const handleCloseModal = () => {
      setModalState({
        isOpen: false,
        screenId: null,
        title: "",
        description: "",
        size: "md",
      });
      setScreenData(null);
      setFormData({});
    };

    window.addEventListener("openScreenModal", handleOpenModal as EventListener);
    window.addEventListener("closeSaveModal", handleCloseModal);

    return () => {
      window.removeEventListener("openScreenModal", handleOpenModal as EventListener);
      window.removeEventListener("closeSaveModal", handleCloseModal);
    };
  }, []);

  // 화면 데이터 로딩
  useEffect(() => {
    if (modalState.isOpen && modalState.screenId) {
      loadScreenData(modalState.screenId);
    }
  }, [modalState.isOpen, modalState.screenId]);

  const loadScreenData = async (screenId: number) => {
    try {
      setLoading(true);

      console.log("화면 데이터 로딩 시작:", screenId);

      // 화면 정보와 레이아웃 데이터 로딩
      const [screenInfo, layoutData] = await Promise.all([
        screenApi.getScreen(screenId),
        screenApi.getLayout(screenId),
      ]);

      console.log("API 응답:", { screenInfo, layoutData });

      // screenApi는 직접 데이터를 반환하므로 .success 체크 불필요
      if (screenInfo && layoutData) {
        const components = layoutData.components || [];

        // 화면의 실제 크기 계산
        const dimensions = calculateScreenDimensions(components);
        setScreenDimensions(dimensions);

        setScreenData({
          components,
          screenInfo: screenInfo,
        });
        console.log("화면 데이터 설정 완료:", {
          componentsCount: components.length,
          dimensions,
          screenInfo,
        });
      } else {
        throw new Error("화면 데이터가 없습니다");
      }
    } catch (error) {
      console.error("화면 데이터 로딩 오류:", error);
      toast.error("화면을 불러오는 중 오류가 발생했습니다.");
      handleClose();
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    setModalState({
      isOpen: false,
      screenId: null,
      title: "",
      size: "md",
    });
    setScreenData(null);
    setFormData({}); // 폼 데이터 초기화
  };

  // 모달 크기 설정 - 화면 내용에 맞게 동적 조정
  const getModalStyle = () => {
    if (!screenDimensions) {
      return {
        className: "w-fit min-w-[400px] max-w-4xl max-h-[90vh] overflow-hidden p-0",
        style: {},
      };
    }

    // 헤더 높이를 최소화 (제목 영역만)
    const headerHeight = 60; // DialogHeader 최소 높이 (타이틀 + 최소 패딩)
    const totalHeight = screenDimensions.height + headerHeight;

    return {
      className: "overflow-hidden p-0",
      style: {
        width: `${Math.min(screenDimensions.width, window.innerWidth * 0.98)}px`,
        height: `${Math.min(totalHeight, window.innerHeight * 0.95)}px`,
        maxWidth: "98vw",
        maxHeight: "95vh",
      },
    };
  };

  const modalStyle = getModalStyle();

  return (
    <ResizableDialog open={modalState.isOpen} onOpenChange={handleClose}>
      <ResizableDialogContent 
        className={`${modalStyle.className} ${className || ""}`} 
        style={modalStyle.style}
        defaultWidth={800}
        defaultHeight={600}
        minWidth={600}
        minHeight={400}
        maxWidth={1400}
        maxHeight={1000}
        modalId={`screen-modal-${modalState.screenId}`}
      >
        <ResizableDialogHeader className="shrink-0 border-b px-4 py-3">
          <ResizableDialogTitle className="text-base">{modalState.title}</ResizableDialogTitle>
          {modalState.description && !loading && (
            <ResizableDialogDescription className="text-muted-foreground text-xs">{modalState.description}</ResizableDialogDescription>
          )}
          {loading && (
            <ResizableDialogDescription className="text-xs">{loading ? "화면을 불러오는 중입니다..." : ""}</ResizableDialogDescription>
          )}
        </ResizableDialogHeader>

        <div className="flex flex-1 items-center justify-center overflow-auto">
          {loading ? (
            <div className="flex h-full items-center justify-center">
              <div className="text-center">
                <div className="mx-auto mb-4 h-8 w-8 animate-spin rounded-full border-b-2 border-blue-600"></div>
                <p className="text-muted-foreground">화면을 불러오는 중...</p>
              </div>
            </div>
          ) : screenData ? (
            <div
              className="relative bg-white"
              style={{
                width: screenDimensions?.width || 800,
                height: screenDimensions?.height || 600,
                transformOrigin: "center center",
                maxWidth: "100%",
                maxHeight: "100%",
              }}
            >
              {screenData.components.map((component) => {
                // 컴포넌트 위치를 offset만큼 조정 (왼쪽 상단으로 정렬)
                const offsetX = screenDimensions?.offsetX || 0;
                const offsetY = screenDimensions?.offsetY || 0;

                const adjustedComponent = {
                  ...component,
                  position: {
                    ...component.position,
                    x: parseFloat(component.position?.x?.toString() || "0") - offsetX,
                    y: parseFloat(component.position?.y?.toString() || "0") - offsetY,
                  },
                };

                return (
                  <InteractiveScreenViewerDynamic
                    key={component.id}
                    component={adjustedComponent}
                    allComponents={screenData.components}
                    formData={formData}
                    onFormDataChange={(fieldName, value) => {
                      console.log(`🎯 ScreenModal onFormDataChange 호출: ${fieldName} = "${value}"`);
                      console.log("📋 현재 formData:", formData);
                      setFormData((prev) => {
                        const newFormData = {
                          ...prev,
                          [fieldName]: value,
                        };
                        console.log("📝 ScreenModal 업데이트된 formData:", newFormData);
                        return newFormData;
                      });
                    }}
                    screenInfo={{
                      id: modalState.screenId!,
                      tableName: screenData.screenInfo?.tableName,
                    }}
                  />
                );
              })}
            </div>
          ) : (
            <div className="flex h-full items-center justify-center">
              <p className="text-muted-foreground">화면 데이터가 없습니다.</p>
            </div>
          )}
        </div>
      </ResizableDialogContent>
    </ResizableDialog>
  );
};

export default ScreenModal;
