"use client";

import React, { useState, useCallback } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { useAuth } from "@/hooks/useAuth";
import { uploadFilesAndCreateData } from "@/lib/api/file";
import { toast } from "sonner";
import { ComponentData, WidgetComponent, DataTableComponent, FileComponent, ButtonTypeConfig } from "@/types/screen";
import { InteractiveDataTable } from "./InteractiveDataTable";
import { DynamicWebTypeRenderer } from "@/lib/registry";
import { dynamicFormApi, DynamicFormData } from "@/lib/api/dynamicForm";
import { useParams } from "next/navigation";
import { screenApi } from "@/lib/api/screen";

interface InteractiveScreenViewerProps {
  component: ComponentData;
  allComponents: ComponentData[];
  formData?: Record<string, any>;
  onFormDataChange?: (fieldName: string, value: any) => void;
  hideLabel?: boolean;
  screenInfo?: {
    id: number;
    tableName?: string;
  };
}

export const InteractiveScreenViewerDynamic: React.FC<InteractiveScreenViewerProps> = ({
  component,
  allComponents,
  formData: externalFormData,
  onFormDataChange,
  hideLabel = false,
  screenInfo,
}) => {
  const { userName, user } = useAuth();
  const [localFormData, setLocalFormData] = useState<Record<string, any>>({});
  const [dateValues, setDateValues] = useState<Record<string, Date | undefined>>({});

  // 팝업 화면 상태
  const [popupScreen, setPopupScreen] = useState<{
    screenId: number;
    title: string;
    size: string;
  } | null>(null);

  // 팝업 화면 레이아웃 상태
  const [popupLayout, setPopupLayout] = useState<ComponentData[]>([]);
  const [popupLoading, setPopupLoading] = useState(false);
  const [popupScreenResolution, setPopupScreenResolution] = useState<{ width: number; height: number } | null>(null);
  const [popupScreenInfo, setPopupScreenInfo] = useState<{ id: number; tableName?: string } | null>(null);

  // 팝업 전용 formData 상태
  const [popupFormData, setPopupFormData] = useState<Record<string, any>>({});

  // formData 결정 (외부에서 전달받은 것이 있으면 우선 사용)
  const formData = externalFormData || localFormData;

  // 자동값 생성 함수
  const generateAutoValue = useCallback(
    (autoValueType: string): string => {
      const now = new Date();
      switch (autoValueType) {
        case "current_datetime":
          return now.toISOString().slice(0, 19).replace("T", " ");
        case "current_date":
          return now.toISOString().slice(0, 10);
        case "current_time":
          return now.toTimeString().slice(0, 8);
        case "current_user":
          return userName || "사용자";
        case "uuid":
          return crypto.randomUUID();
        case "sequence":
          return `SEQ_${Date.now()}`;
        default:
          return "";
      }
    },
    [userName],
  );

  // 팝업 화면 레이아웃 로드
  React.useEffect(() => {
    if (popupScreen?.screenId) {
      loadPopupScreen(popupScreen.screenId);
    }
  }, [popupScreen?.screenId]);

  const loadPopupScreen = async (screenId: number) => {
    try {
      setPopupLoading(true);
      const response = await screenApi.getScreenLayout(screenId);

      if (response.success && response.data) {
        const screenData = response.data;
        setPopupLayout(screenData.components || []);
        setPopupScreenResolution({
          width: screenData.screenResolution?.width || 1200,
          height: screenData.screenResolution?.height || 800,
        });
        setPopupScreenInfo({
          id: screenData.id,
          tableName: screenData.tableName,
        });
      } else {
        toast.error("팝업 화면을 불러올 수 없습니다.");
        setPopupScreen(null);
      }
    } catch (error) {
      console.error("팝업 화면 로드 오류:", error);
      toast.error("팝업 화면 로드 중 오류가 발생했습니다.");
      setPopupScreen(null);
    } finally {
      setPopupLoading(false);
    }
  };

  // 폼 데이터 변경 핸들러
  const handleFormDataChange = (fieldName: string, value: any) => {
    if (onFormDataChange) {
      onFormDataChange(fieldName, value);
    } else {
      setLocalFormData((prev) => ({ ...prev, [fieldName]: value }));
    }
  };

  // 동적 대화형 위젯 렌더링
  const renderInteractiveWidget = (comp: ComponentData) => {
    // 데이터 테이블 컴포넌트 처리
    if (comp.type === "datatable") {
      return (
        <InteractiveDataTable
          component={comp as DataTableComponent}
          className="h-full w-full"
          style={{
            width: "100%",
            height: "100%",
          }}
        />
      );
    }

    // 버튼 컴포넌트 처리
    if (comp.type === "button") {
      return renderButton(comp);
    }

    // 파일 컴포넌트 처리
    if (comp.type === "file") {
      return renderFileComponent(comp as FileComponent);
    }

    // 위젯 컴포넌트가 아닌 경우
    if (comp.type !== "widget") {
      return <div className="text-sm text-gray-500">지원되지 않는 컴포넌트 타입</div>;
    }

    const widget = comp as WidgetComponent;
    const { widgetType, label, placeholder, required, readonly, columnName } = widget;
    const fieldName = columnName || comp.id;
    const currentValue = formData[fieldName] || "";

    // 스타일 적용
    const applyStyles = (element: React.ReactElement) => {
      if (!comp.style) return element;

      return React.cloneElement(element, {
        style: {
          ...element.props.style,
          ...comp.style,
          width: "100%",
          height: "100%",
          minHeight: "100%",
          maxHeight: "100%",
          boxSizing: "border-box",
        },
      });
    };

    // 동적 웹타입 렌더링 사용
    if (widgetType) {
      try {
        const dynamicElement = (
          <DynamicWebTypeRenderer
            webType={widgetType}
            props={{
              component: widget,
              value: currentValue,
              onChange: (value: any) => handleFormDataChange(fieldName, value),
              readonly: readonly,
              required: required,
              placeholder: placeholder,
              className: "w-full h-full",
            }}
            config={widget.webTypeConfig}
            onEvent={(event: string, data: any) => {
              // 이벤트 처리
              console.log(`Widget event: ${event}`, data);
            }}
          />
        );

        return applyStyles(dynamicElement);
      } catch (error) {
        console.error(`웹타입 "${widgetType}" 대화형 렌더링 실패:`, error);
        // 오류 발생 시 폴백으로 기본 input 렌더링
        const fallbackElement = (
          <Input
            type="text"
            value={currentValue}
            onChange={(e) => handleFormDataChange(fieldName, e.target.value)}
            placeholder={`${widgetType} (렌더링 오류)`}
            disabled={readonly}
            required={required}
            className="h-full w-full"
          />
        );
        return applyStyles(fallbackElement);
      }
    }

    // 웹타입이 없는 경우 기본 input 렌더링 (하위 호환성)
    const defaultElement = (
      <Input
        type="text"
        value={currentValue}
        onChange={(e) => handleFormDataChange(fieldName, e.target.value)}
        placeholder={placeholder || "입력하세요"}
        disabled={readonly}
        required={required}
        className="h-full w-full"
      />
    );
    return applyStyles(defaultElement);
  };

  // 버튼 렌더링
  const renderButton = (comp: ComponentData) => {
    const config = (comp as any).webTypeConfig as ButtonTypeConfig | undefined;
    const { label } = comp;

    // 버튼 액션 핸들러들
    const handleSaveAction = async () => {
      if (!screenInfo?.tableName) {
        toast.error("테이블명이 설정되지 않았습니다.");
        return;
      }

      try {
        const saveData: DynamicFormData = {
          tableName: screenInfo.tableName,
          data: formData,
        };

        console.log("💾 저장 액션 실행:", saveData);
        const response = await dynamicFormApi.saveData(saveData);

        if (response.success) {
          toast.success("데이터가 성공적으로 저장되었습니다.");
        } else {
          toast.error(response.message || "저장에 실패했습니다.");
        }
      } catch (error) {
        console.error("저장 오류:", error);
        toast.error("저장 중 오류가 발생했습니다.");
      }
    };

    const handleDeleteAction = async () => {
      if (!config?.confirmationEnabled || window.confirm(config.confirmationMessage || "정말 삭제하시겠습니까?")) {
        console.log("🗑️ 삭제 액션 실행");
        toast.success("삭제가 완료되었습니다.");
      }
    };

    const handlePopupAction = () => {
      if (config?.popupScreenId) {
        setPopupScreen({
          screenId: config.popupScreenId,
          title: config.popupTitle || "팝업 화면",
          size: config.popupSize || "medium",
        });
      }
    };

    const handleNavigateAction = () => {
      const navigateType = config?.navigateType || "url";

      if (navigateType === "screen" && config?.navigateScreenId) {
        const screenPath = `/screens/${config.navigateScreenId}`;

        if (config.navigateTarget === "_blank") {
          window.open(screenPath, "_blank");
        } else {
          window.location.href = screenPath;
        }
      } else if (navigateType === "url" && config?.navigateUrl) {
        if (config.navigateTarget === "_blank") {
          window.open(config.navigateUrl, "_blank");
        } else {
          window.location.href = config.navigateUrl;
        }
      }
    };

    const handleCustomAction = async () => {
      if (config?.customAction) {
        try {
          const result = eval(config.customAction);
          if (result instanceof Promise) {
            await result;
          }
          console.log("⚡ 커스텀 액션 실행 완료");
        } catch (error) {
          throw new Error(`커스텀 액션 실행 실패: ${error.message}`);
        }
      }
    };

    const handleClick = async () => {
      try {
        const actionType = config?.actionType || "save";

        switch (actionType) {
          case "save":
            await handleSaveAction();
            break;
          case "delete":
            await handleDeleteAction();
            break;
          case "popup":
            handlePopupAction();
            break;
          case "navigate":
            handleNavigateAction();
            break;
          case "custom":
            await handleCustomAction();
            break;
          default:
            console.log("🔘 기본 버튼 클릭");
        }
      } catch (error) {
        console.error("버튼 액션 오류:", error);
        toast.error(error.message || "액션 실행 중 오류가 발생했습니다.");
      }
    };

    return (
      <Button
        onClick={handleClick}
        variant={(config?.variant as any) || "default"}
        size={(config?.size as any) || "default"}
        disabled={config?.disabled}
        className="h-full w-full"
        style={{
          backgroundColor: config?.backgroundColor,
          color: config?.textColor,
          ...comp.style,
        }}
      >
        {label || "버튼"}
      </Button>
    );
  };

  // 파일 컴포넌트 렌더링
  const renderFileComponent = (comp: FileComponent) => {
    const { label, readonly } = comp;
    const fieldName = comp.columnName || comp.id;

    const handleFileUpload = async (files: File[]) => {
      if (!screenInfo?.tableName) {
        toast.error("테이블명이 설정되지 않았습니다.");
        return;
      }

      try {
        const uploadData = {
          files,
          tableName: screenInfo.tableName,
          fieldName,
          recordId: formData.id || undefined,
        };

        const response = await uploadFilesAndCreateData(uploadData);

        if (response.success) {
          toast.success("파일이 성공적으로 업로드되었습니다.");
          handleFormDataChange(fieldName, response.data);
        } else {
          toast.error("파일 업로드에 실패했습니다.");
        }
      } catch (error) {
        console.error("파일 업로드 오류:", error);
        toast.error("파일 업로드 중 오류가 발생했습니다.");
      }
    };

    return (
      <div className="h-full w-full">
        {/* 파일 업로드 컴포넌트는 기존 구현 사용 */}
        <div className="rounded border border-dashed p-2 text-sm text-gray-500">
          파일 업로드 영역 (동적 렌더링 예정)
        </div>
      </div>
    );
  };

  // 메인 렌더링
  const { type, position, size, style = {} } = component;

  const componentStyle = {
    position: "absolute" as const,
    left: position?.x || 0,
    top: position?.y || 0,
    width: size?.width || 200,
    height: size?.height || 40,
    zIndex: position?.z || 1,
    ...style,
  };

  return (
    <>
      <div className="absolute" style={componentStyle}>
        <div className="h-full w-full">
          {/* 라벨 표시 */}
          {!hideLabel && component.label && (
            <div className="mb-1">
              <label className="text-sm font-medium text-gray-700">
                {component.label}
                {(component as WidgetComponent).required && <span className="ml-1 text-red-500">*</span>}
              </label>
            </div>
          )}

          {/* 위젯 렌더링 */}
          <div className="flex-1">{renderInteractiveWidget(component)}</div>
        </div>
      </div>

      {/* 팝업 화면 렌더링 */}
      {popupScreen && (
        <Dialog open={!!popupScreen} onOpenChange={() => setPopupScreen(null)}>
          <DialogContent
            className={` ${
              popupScreen.size === "small" ? "max-w-md" : popupScreen.size === "large" ? "max-w-6xl" : "max-w-4xl"
            } max-h-[90vh] overflow-y-auto`}
          >
            <DialogHeader>
              <DialogTitle>{popupScreen.title}</DialogTitle>
            </DialogHeader>

            {popupLoading ? (
              <div className="flex items-center justify-center p-8">
                <div className="text-gray-500">로딩 중...</div>
              </div>
            ) : (
              <div
                className="relative overflow-auto"
                style={{
                  width: popupScreenResolution?.width || 1200,
                  height: popupScreenResolution?.height || 600,
                  maxWidth: "100%",
                  maxHeight: "70vh",
                }}
              >
                {popupLayout.map((popupComponent) => (
                  <InteractiveScreenViewerDynamic
                    key={popupComponent.id}
                    component={popupComponent}
                    allComponents={popupLayout}
                    formData={popupFormData}
                    onFormDataChange={(fieldName, value) => {
                      setPopupFormData((prev) => ({ ...prev, [fieldName]: value }));
                    }}
                    screenInfo={popupScreenInfo}
                  />
                ))}
              </div>
            )}
          </DialogContent>
        </Dialog>
      )}
    </>
  );
};

// 기존 InteractiveScreenViewer와의 호환성을 위한 export
export { InteractiveScreenViewerDynamic as InteractiveScreenViewer };

InteractiveScreenViewerDynamic.displayName = "InteractiveScreenViewerDynamic";


