"use client";

import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Database,
  ArrowLeft,
  Save,
  Languages,
  Settings2,
  PanelLeft,
  PanelLeftClose,
  PanelRight,
  PanelRightClose,
  AlignStartVertical,
  AlignCenterVertical,
  AlignEndVertical,
  AlignStartHorizontal,
  AlignCenterHorizontal,
  AlignEndHorizontal,
  AlignHorizontalSpaceAround,
  AlignVerticalSpaceAround,
  RulerIcon,
  Tag,
  Keyboard,
  Eye,
  Equal,
} from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { cn } from "@/lib/utils";
import { type ViewType } from "../ViewTabBar";
import { List, PlusCircle, Pencil } from "lucide-react";

type AlignMode = "left" | "centerX" | "right" | "top" | "centerY" | "bottom";
type DistributeDirection = "horizontal" | "vertical";
type MatchSizeMode = "width" | "height" | "both";

// View tab definitions (same as ViewTabBar)
const VIEW_TABS: { id: ViewType; label: string; icon: React.ReactNode }[] = [
  { id: "list", label: "목록 화면", icon: <List size={11} /> },
  { id: "create", label: "등록 팝업", icon: <PlusCircle size={11} /> },
  { id: "edit", label: "수정 팝업", icon: <Pencil size={11} /> },
];

interface SlimToolbarProps {
  screenName?: string;
  onBack: () => void;
  onSave: () => void;
  isSaving?: boolean;
  onPreview?: () => void;
  onGenerateMultilang?: () => void;
  isGeneratingMultilang?: boolean;
  onOpenMultilangSettings?: () => void;
  // Panel toggle
  isPanelOpen?: boolean;
  onTogglePanel?: () => void;
  // Align/distribute/match size
  selectedCount?: number;
  onAlign?: (mode: AlignMode) => void;
  onDistribute?: (direction: DistributeDirection) => void;
  onMatchSize?: (mode: MatchSizeMode) => void;
  onToggleLabels?: () => void;
  onShowShortcuts?: () => void;
  // Properties panel toggle
  isPropertiesOpen?: boolean;
  onToggleProperties?: () => void;
  // View tabs (merged from ViewTabBar)
  activeView?: ViewType;
  onViewChange?: (view: ViewType) => void;
  viewCounts?: Record<ViewType, number>;
  /**
   * 표시할 뷰 탭. 생략 시 전체 표시.
   * list 는 루트로 항상 포함. create/edit 는 목록 뷰에 해당
   * actionType(add/edit) 버튼이 배치됐을 때만 부모가 포함시킨다.
   */
  visibleViews?: ViewType[];
}

export const SlimToolbar: React.FC<SlimToolbarProps> = ({
  screenName,
  onBack,
  onSave,
  isSaving = false,
  onPreview,
  onGenerateMultilang,
  isGeneratingMultilang = false,
  onOpenMultilangSettings,
  isPanelOpen = false,
  onTogglePanel,
  selectedCount = 0,
  onAlign,
  onDistribute,
  onMatchSize,
  onToggleLabels,
  onShowShortcuts,
  isPropertiesOpen = true,
  onToggleProperties,
  activeView = "list",
  onViewChange,
  viewCounts,
  visibleViews,
}) => {
  const tabs = visibleViews
    ? VIEW_TABS.filter((t) => visibleViews.includes(t.id))
    : VIEW_TABS;
  return (
    <div className="slim-toolbar hdr">
      {/* Zone 1: Brand */}
      <div className="hdr-zone" style={{ padding: "0 14px" }}>
        <div className="ide-brand">
          <span className="ide-brand-text">INVYONE</span>
          <span className="ide-brand-badge">STUDIO</span>
        </div>
      </div>

      {/* Zone 2: Back + Panel toggle */}
      <div className="hdr-zone">
        <div className="hdr-gap-1">
          <button type="button" className="sq-btn" onClick={onBack} title="목록으로">
            <ArrowLeft size={15} />
          </button>
          {onTogglePanel && (
            <button
              type="button"
              className={cn("sq-btn", isPanelOpen && "active")}
              onClick={onTogglePanel}
              title="패널 열기/닫기 (P)"
            >
              {isPanelOpen ? <PanelLeftClose size={15} /> : <PanelLeft size={15} />}
            </button>
          )}
        </div>
      </div>

      {/* Zone 3: View tabs inline */}
      <div className="hdr-zone" style={{ padding: 0 }}>
        <div className="tab-group">
          {tabs.map((tab) => {
            const count = viewCounts?.[tab.id] ?? 0;
            const isActive = tab.id === activeView;
            return (
              <button
                key={tab.id}
                type="button"
                className={cn("tab-item", isActive && "active")}
                onClick={() => onViewChange?.(tab.id)}
              >
                {tab.icon}
                {tab.label}
                {count > 0 && <span className="tab-cnt">{count}</span>}
              </button>
            );
          })}
        </div>
      </div>

      {/* Zone 4: Template title (flex grow) */}
      <div className="hdr-zone grow">
        <span className="info-title">{screenName || "새 템플릿"}</span>
      </div>

      {/* Alignment tools (conditional, shown when multi-select) */}
      {selectedCount >= 2 && (onAlign || onDistribute || onMatchSize) && (
        <div className="hdr-zone">
          <div className="tb-align-tools">
            {onAlign && (
              <>
                <button type="button" className="sq-btn" onClick={() => onAlign("left")} title="좌측 정렬"><AlignStartVertical size={13} /></button>
                <button type="button" className="sq-btn" onClick={() => onAlign("centerX")} title="가로 중앙"><AlignCenterVertical size={13} /></button>
                <button type="button" className="sq-btn" onClick={() => onAlign("right")} title="우측 정렬"><AlignEndVertical size={13} /></button>
                <div className="tb-dot" />
                <button type="button" className="sq-btn" onClick={() => onAlign("top")} title="상단 정렬"><AlignStartHorizontal size={13} /></button>
                <button type="button" className="sq-btn" onClick={() => onAlign("centerY")} title="세로 중앙"><AlignCenterHorizontal size={13} /></button>
                <button type="button" className="sq-btn" onClick={() => onAlign("bottom")} title="하단 정렬"><AlignEndHorizontal size={13} /></button>
              </>
            )}
            {onDistribute && selectedCount >= 3 && (
              <>
                <div className="tb-dot" />
                <button type="button" className="sq-btn" onClick={() => onDistribute("horizontal")} title="가로 균등"><AlignHorizontalSpaceAround size={13} /></button>
                <button type="button" className="sq-btn" onClick={() => onDistribute("vertical")} title="세로 균등"><AlignVerticalSpaceAround size={13} /></button>
              </>
            )}
            {onMatchSize && (
              <>
                <div className="tb-dot" />
                <button type="button" className="sq-btn" onClick={() => onMatchSize("width")} title="너비 맞추기"><RulerIcon size={13} /></button>
                <button type="button" className="sq-btn" style={{ transform: "rotate(90deg)" }} onClick={() => onMatchSize("height")} title="높이 맞추기"><RulerIcon size={13} /></button>
                <button type="button" className="sq-btn" onClick={() => onMatchSize("both")} title="크기 모두"><Equal size={13} /></button>
              </>
            )}
            <span className="tb-sel-count">{selectedCount}</span>
          </div>
        </div>
      )}

      {/* Zone 5: Tool icon buttons */}
      <div className="hdr-zone">
        <div className="hdr-gap-1">
          {onToggleLabels && (
            <button type="button" className="sq-btn" onClick={onToggleLabels} title="라벨 표시/숨기기">
              <Tag size={13} />
            </button>
          )}
          {onShowShortcuts && (
            <button type="button" className="sq-btn" onClick={onShowShortcuts} title="단축키 (?)">
              <Keyboard size={13} />
            </button>
          )}
          {onPreview && (
            <button type="button" className="sq-btn" onClick={onPreview} title="미리보기">
              <Eye size={13} />
            </button>
          )}
          {onToggleProperties && (
            <button
              type="button"
              className={cn("sq-btn", isPropertiesOpen && "active")}
              onClick={onToggleProperties}
              title="속성 패널 (I)"
            >
              {isPropertiesOpen ? <PanelRightClose size={13} /> : <PanelRight size={13} />}
            </button>
          )}
        </div>
      </div>

      {/* Zone 6: Multilang + Save (end-aligned) */}
      <div className="hdr-zone end">
        <div className="hdr-gap-2">
          {onGenerateMultilang && (
            <button
              type="button"
              className="tool-btn"
              onClick={onGenerateMultilang}
              disabled={isGeneratingMultilang}
              title="다국어 키 자동 생성"
            >
              <Languages size={13} />
              {isGeneratingMultilang ? "생성 중..." : "다국어 생성"}
            </button>
          )}
          {onOpenMultilangSettings && (
            <button
              type="button"
              className="tool-btn"
              onClick={onOpenMultilangSettings}
              title="다국어 설정"
            >
              <Settings2 size={13} />
              다국어 설정
            </button>
          )}
          <button
            type="button"
            className="tb-save"
            onClick={onSave}
            disabled={isSaving}
          >
            <Save size={13} />
            {isSaving ? "저장 중..." : "저장"}
          </button>
        </div>
      </div>
    </div>
  );
};

export default SlimToolbar;
