"use client";

import React from "react";
import { LayoutRendererProps } from "../BaseLayoutRenderer";

/**
 * accordion 컴포넌트
 */
export interface AccordionLayoutProps extends LayoutRendererProps {
  renderer: any; // AccordionLayoutRenderer 타입
}

export const AccordionLayout: React.FC<AccordionLayoutProps> = ({
  layout,
  isDesignMode = false,
  isSelected = false,
  onClick,
  className = "",
  renderer,
  onZoneComponentDrop,
  onZoneClick,
  ...props
}) => {
  if (!layout.layoutConfig.accordion) {
    return (
      <div className="error-layout flex items-center justify-center rounded border-2 border-destructive/30 bg-destructive/10 p-4">
        <div className="text-center text-destructive">
          <div className="font-medium">accordion 설정이 없습니다.</div>
          <div className="mt-1 text-sm">layoutConfig.accordion가 필요합니다.</div>
        </div>
      </div>
    );
  }

  const accordionConfig = layout.layoutConfig.accordion || { defaultExpanded: [], multiple: false };
  const containerStyle = renderer.getLayoutContainerStyle();

  // accordion 컨테이너 스타일
  const accordionStyle: React.CSSProperties = {
    ...containerStyle,
    display: "flex",
    flexDirection: "column",
    height: "100%",
    width: "100%",
    overflow: "hidden",
  };

  // 디자인 모드 스타일
  if (isDesignMode) {
    accordionStyle.border = isSelected ? "2px solid #3b82f6" : "1px solid #e2e8f0";
    accordionStyle.borderRadius = "8px";
    accordionStyle.padding = "4px";
  }

  // DOM props만 추출 (React DOM에서 인식하는 props만)
  const {
    children: propsChildren,
    onUpdateLayout,
    onSelectComponent,
    isDesignMode: _isDesignMode,
    allComponents,
    onComponentDrop,
    onDragStart,
    onDragEnd,
    selectedScreen, // DOM에 전달하지 않도록 제외
    ...domProps
  } = props;

  return (
    <>
      <style jsx>{`
        .force-accordion-layout {
          display: flex !important;
          flex-direction: column !important;
          height: ${layout.size?.height ? `${layout.size.height}px` : "100%"} !important;
          min-height: ${layout.size?.height ? `${layout.size.height}px` : "200px"} !important;
          width: 100% !important;
        }
      `}</style>
      <div
        className={`accordion-layout force-accordion-layout ${isDesignMode ? "design-mode" : ""} ${className}`}
        style={accordionStyle}
        onClick={onClick}
        draggable={isDesignMode}
        onDragStart={onDragStart}
        onDragEnd={onDragEnd}
        {...domProps}
      >
        {layout.zones.map((zone: any, index: number) => {
          const zoneChildren = renderer.getZoneChildren(zone.id);
          const isExpanded = accordionConfig.defaultExpanded?.includes(zone.id) || index === 0;

          return (
            <AccordionSection
              key={zone.id}
              zone={zone}
              isExpanded={isExpanded}
              isDesignMode={isDesignMode}
              renderer={renderer}
              zoneChildren={zoneChildren}
              onComponentDrop={onComponentDrop}
              onZoneClick={onZoneClick}
            />
          );
        })}

        {/* 디자인 모드에서 빈 영역 표시 */}
        {layout.zones.length === 0 && (
          <div
            className="empty-accordion-container"
            style={{
              flex: 1,
              border: "2px dashed #cbd5e1",
              borderRadius: "8px",
              backgroundColor: "rgba(148, 163, 184, 0.05)",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              fontSize: "14px",
              color: "#64748b",
              minHeight: "100px",
              padding: "20px",
              textAlign: "center",
            }}
          >
            {isDesignMode ? "아코디언에 존을 추가하세요" : "빈 아코디언"}
          </div>
        )}
      </div>
    </>
  );
};

/**
 * 아코디언 섹션 컴포넌트
 */
const AccordionSection: React.FC<{
  zone: any;
  isExpanded: boolean;
  isDesignMode: boolean;
  renderer: any;
  zoneChildren: any;
  onComponentDrop?: (e: React.DragEvent, zoneId: string) => void;
  onZoneClick?: (zoneId: string) => void;
}> = ({ zone, isExpanded: initialExpanded, isDesignMode, renderer, zoneChildren, onComponentDrop, onZoneClick }) => {
  const [isExpanded, setIsExpanded] = React.useState(initialExpanded);

  const headerStyle: React.CSSProperties = {
    padding: "12px 16px",
    backgroundColor: isDesignMode ? "#3b82f6" : "hsl(var(--muted))",
    color: isDesignMode ? "white" : "hsl(var(--foreground))",
    border: "1px solid hsl(var(--border))",
    borderBottom: isExpanded ? "none" : "1px solid hsl(var(--border))",
    cursor: "pointer",
    userSelect: "none",
    display: "flex",
    alignItems: "center",
    justifyContent: "space-between",
    fontSize: "14px",
    fontWeight: 500,
    borderRadius: "8px 8px 0 0",
    margin: "2px",
    transition: "all 0.2s ease",
    boxShadow: "0 1px 3px 0 rgba(0, 0, 0, 0.1)",
  };

  const contentStyle: React.CSSProperties = {
    padding: isExpanded ? "12px 16px" : "0 16px",
    maxHeight: isExpanded ? zone.size?.height || "500px" : "0",
    overflow: "hidden",
    transition: "all 0.3s ease",
    backgroundColor: "hsl(var(--card))",
    border: "1px solid hsl(var(--border))",
    borderTop: "none",
    borderRadius: "0 0 8px 8px",
    margin: "2px",
    minHeight: isExpanded ? zone.size?.minHeight || "100px" : "0",
    boxShadow: "0 1px 3px 0 rgba(0, 0, 0, 0.1)",
  };

  return (
    <div className="accordion-section" style={{ borderRadius: isDesignMode ? "6px" : "0" }}>
      <div className="accordion-header" style={headerStyle} onClick={() => setIsExpanded(!isExpanded)}>
        <span>{zone.name}</span>
        <span
          style={{
            transform: isExpanded ? "rotate(180deg)" : "rotate(0deg)",
            transition: "transform 0.2s ease",
            fontSize: "12px",
          }}
        >
          ▼
        </span>
      </div>
      <div
        className="accordion-content"
        style={{
          ...contentStyle,
          position: "relative",
        }}
        onDragOver={(e) => {
          e.preventDefault();
          e.dataTransfer.dropEffect = "copy";
        }}
        onDrop={(e) => {
          e.preventDefault();
          e.stopPropagation();
          if (onComponentDrop) {
            onComponentDrop(e, zone.id, layout.id); // 존 ID와 레이아웃 ID를 함께 전달
          }
        }}
        onClick={(e) => {
          e.stopPropagation();
          if (onZoneClick) {
            onZoneClick(zone.id);
          }
        }}
      >
        {/* 존 안의 컴포넌트들을 절대 위치로 렌더링 */}
        {isExpanded &&
          zoneChildren.map((child: any) => (
            <div
              key={child.id}
              style={{
                position: "absolute",
                left: child.position?.x || 0,
                top: child.position?.y || 0,
                width: child.size?.width || "auto",
                height: child.size?.height || "auto",
                zIndex: child.position?.z || 1,
              }}
            >
              {renderer.renderChild(child)}
            </div>
          ))}
      </div>
    </div>
  );
};
