/**
 * CMS Editor Page
 * Main page component for the content management editor
 */

"use client";

import React, { useEffect, useCallback } from "react";
import {
  EditorToolbar,
  SectionList,
  PreviewPanel,
  PropertyPanel,
  PublishingStatusBar,
} from "../editor/components";
import { useCMSEditor } from "../editor/store";
import type { BaseSection } from "../editor/types";

// Sample data with Korean content
const sampleSections: BaseSection[] = [
  {
    id: "hero-1",
    type: "hero",
    name: "메인 히어로 섹션",
    order: 0,
    isActive: true,
    content: {
      title: "혁신적인 웹사이트 빌더",
      subtitle: "코딩 없이 전문적인 웹사이트를 만드세요",
      description:
        "직관적인 드래그 앤 드롭 인터페이스로 누구나 쉽게 아름다운 웹사이트를 제작할 수 있습니다.",
      image: {
        url: "https://images.unsplash.com/photo-1460925895917-afdab827c52f?ixlib=rb-4.0.3",
        alt: "혁신적인 웹 개발 이미지",
      },
      buttons: [
        {
          text: "무료로 시작하기",
          url: "/signup",
          type: "primary",
          size: "large",
        },
        {
          text: "데모 보기",
          url: "/demo",
          type: "secondary",
          size: "large",
        },
      ],
    },
    styles: {
      background: {
        type: "gradient",
        gradient: {
          direction: 135,
          colors: [
            { color: "#667eea", position: 0 },
            { color: "#764ba2", position: 100 },
          ],
        },
      },
      spacing: {
        padding: { top: 80, right: 20, bottom: 80, left: 20 },
        margin: { top: 0, right: 0, bottom: 0, left: 0 },
      },
      typography: {
        fontFamily: "Inter",
        fontSize: 48,
        fontWeight: 700,
        lineHeight: 1.2,
        letterSpacing: -0.5,
        textAlign: "center",
        textDecoration: "none",
        textTransform: "none",
      },
      colors: {
        primary: "#667eea",
        secondary: "#764ba2",
        accent: "#f093fb",
        text: "#ffffff",
        textSecondary: "#e2e8f0",
        background: "#667eea",
        border: "transparent",
      },
      borders: {
        width: 0,
        style: "none",
        color: "transparent",
        radius: 0,
      },
      effects: {
        shadow: "0 25px 50px -12px rgba(0, 0, 0, 0.25)",
        blur: 0,
        opacity: 1,
        transform: "",
        transition: "all 0.3s ease",
        animation: "",
      },
      responsive: {
        mobile: {},
        tablet: {},
        desktop: {},
      },
    },
    settings: {
      isVisible: true,
      isLocked: false,
      animation: {
        enabled: true,
        type: "fade",
        duration: 1000,
        delay: 0,
        easing: "ease-out",
        trigger: "scroll",
      },
      seo: {
        title: "혁신적인 웹사이트 빌더 | 코딩 없이 웹사이트 제작",
        description:
          "직관적인 드래그 앤 드롭으로 전문적인 웹사이트를 만드세요. 무료 시작.",
        keywords: ["웹사이트 빌더", "노코드", "웹사이트 제작"],
      },
      accessibility: {
        ariaLabel: "메인 히어로 섹션",
        focusable: true,
      },
    },
    metadata: {
      createdAt: new Date("2024-01-01"),
      updatedAt: new Date(),
      createdBy: "admin",
      updatedBy: "admin",
      version: 1,
    },
  },
  {
    id: "features-1",
    type: "features",
    name: "주요 기능 섹션",
    order: 1,
    isActive: true,
    content: {
      title: "강력한 기능들",
      description: "웹사이트 제작에 필요한 모든 도구를 제공합니다",
      features: [
        {
          id: "feature-1",
          title: "드래그 앤 드롭",
          description: "직관적인 인터페이스로 쉽게 페이지를 구성하세요",
          icon: { name: "cursor-arrow-rays", library: "heroicons", size: 24 },
        },
        {
          id: "feature-2",
          title: "반응형 디자인",
          description: "모든 디바이스에서 완벽하게 표시되는 웹사이트",
          icon: { name: "device-phone-mobile", library: "heroicons", size: 24 },
        },
        {
          id: "feature-3",
          title: "실시간 미리보기",
          description: "변경사항을 즉시 확인하고 조정하세요",
          icon: { name: "eye", library: "heroicons", size: 24 },
        },
      ],
      layout: "grid",
      columns: 3,
    },
    styles: {
      background: { type: "color", color: "#ffffff" },
      spacing: {
        padding: { top: 60, right: 20, bottom: 60, left: 20 },
        margin: { top: 0, right: 0, bottom: 0, left: 0 },
      },
      typography: {
        fontFamily: "Inter",
        fontSize: 16,
        fontWeight: 400,
        lineHeight: 1.6,
        letterSpacing: 0,
        textAlign: "left",
        textDecoration: "none",
        textTransform: "none",
      },
      colors: {
        primary: "#3b82f6",
        secondary: "#6b7280",
        accent: "#f59e0b",
        text: "#1f2937",
        textSecondary: "#6b7280",
        background: "#ffffff",
        border: "#e5e7eb",
      },
      borders: {
        width: 0,
        style: "none",
        color: "transparent",
        radius: 8,
      },
      effects: {
        shadow: "",
        blur: 0,
        opacity: 1,
        transform: "",
        transition: "",
        animation: "",
      },
      responsive: {
        mobile: {},
        tablet: {},
        desktop: {},
      },
    },
    settings: {
      isVisible: true,
      isLocked: false,
      animation: {
        enabled: false,
        type: "fade",
        duration: 600,
        delay: 200,
        easing: "ease-out",
        trigger: "scroll",
      },
      seo: {
        title: "주요 기능",
        description: "웹사이트 빌더의 강력한 기능들을 살펴보세요",
      },
      accessibility: {
        ariaLabel: "주요 기능 섹션",
        focusable: true,
      },
    },
    metadata: {
      createdAt: new Date("2024-01-01"),
      updatedAt: new Date(),
      createdBy: "admin",
      updatedBy: "admin",
      version: 1,
    },
  },
];

export function CMSEditorPage() {
  const {
    sections,
    isLoading,
    error,
    setSections,
    enableAutoSave,
    validateSections,
  } = useCMSEditor();

  // Initialize with sample data
  useEffect(() => {
    if (sections.length === 0) {
      setSections(sampleSections);
    }
  }, [sections.length, setSections]);

  // Enable auto-save
  useEffect(() => {
    enableAutoSave();
  }, [enableAutoSave]);

  // Validate sections when they change
  useEffect(() => {
    validateSections();
  }, [sections, validateSections]);

  const handleKeyboardShortcuts = useCallback((e: KeyboardEvent) => {
    if (e.metaKey || e.ctrlKey) {
      switch (e.key) {
        case "s":
          e.preventDefault();
          // Save will be handled by auto-save
          break;
        case "z":
          if (e.shiftKey) {
            // Redo - handled by toolbar
          } else {
            // Undo - handled by toolbar
          }
          e.preventDefault();
          break;
      }
    }
  }, []);

  useEffect(() => {
    document.addEventListener("keydown", handleKeyboardShortcuts);
    return () =>
      document.removeEventListener("keydown", handleKeyboardShortcuts);
  }, [handleKeyboardShortcuts]);

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">에디터를 로딩 중...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center max-w-md mx-auto">
          <div className="text-red-500 text-6xl mb-4">⚠️</div>
          <h2 className="text-xl font-semibold text-gray-900 mb-2">
            오류가 발생했습니다
          </h2>
          <p className="text-gray-600 mb-4">{error}</p>
          <button
            onClick={() => window.location.reload()}
            className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
          >
            페이지 새로고침
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="h-screen bg-gray-50 flex flex-col overflow-hidden">
      {/* Toolbar */}
      <EditorToolbar className="flex-shrink-0" />

      {/* Publishing Status Bar */}
      <PublishingStatusBar />

      {/* Main Content */}
      <div className="flex-1 flex overflow-hidden">
        {/* Section List */}
        <SectionList className="flex-shrink-0" />

        {/* Preview Panel */}
        <div className="flex-1 flex flex-col overflow-hidden">
          <PreviewPanel className="flex-1" />
        </div>

        {/* Property Panel */}
        <PropertyPanel className="flex-shrink-0" />
      </div>

      {/* Status Bar */}
      <EditorStatusBar />
    </div>
  );
}

function EditorStatusBar() {
  const {
    sections,
    isDirty,
    isSaving,
    lastSaved,
    validationErrors,
    pendingUpdates,
  } = useCMSEditor();

  const totalErrors = Object.values(validationErrors).reduce(
    (total, errors) => total + errors.length,
    0
  );

  const pendingCount = pendingUpdates.size;

  return (
    <div className="bg-white border-t border-gray-200 px-4 py-2 flex items-center justify-between text-sm">
      <div className="flex items-center space-x-4">
        <span className="text-gray-600">
          섹션: <span className="font-medium">{sections.length}</span>
        </span>

        {totalErrors > 0 && (
          <span className="text-red-600 flex items-center">
            <svg
              className="w-4 h-4 mr-1"
              viewBox="0 0 20 20"
              fill="currentColor"
            >
              <path
                fillRule="evenodd"
                d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z"
                clipRule="evenodd"
              />
            </svg>
            오류: {totalErrors}
          </span>
        )}

        {pendingCount > 0 && (
          <span className="text-blue-600 flex items-center">
            <svg className="animate-spin w-4 h-4 mr-1" viewBox="0 0 24 24">
              <circle
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                strokeWidth="4"
                fill="none"
                opacity="0.25"
              />
              <path
                fill="currentColor"
                d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
              />
            </svg>
            업데이트 중: {pendingCount}
          </span>
        )}
      </div>

      <div className="flex items-center space-x-4">
        {isSaving && (
          <span className="text-blue-600 flex items-center">
            <svg className="animate-spin w-4 h-4 mr-1" viewBox="0 0 24 24">
              <circle
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                strokeWidth="4"
                fill="none"
                opacity="0.25"
              />
              <path
                fill="currentColor"
                d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
              />
            </svg>
            저장 중...
          </span>
        )}

        {!isSaving && isDirty && (
          <span className="text-orange-600 flex items-center">
            <svg
              className="w-4 h-4 mr-1"
              viewBox="0 0 20 20"
              fill="currentColor"
            >
              <path
                fillRule="evenodd"
                d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z"
                clipRule="evenodd"
              />
            </svg>
            저장되지 않은 변경사항
          </span>
        )}

        {!isSaving && !isDirty && lastSaved && (
          <span className="text-green-600 flex items-center">
            <svg
              className="w-4 h-4 mr-1"
              viewBox="0 0 20 20"
              fill="currentColor"
            >
              <path
                fillRule="evenodd"
                d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
                clipRule="evenodd"
              />
            </svg>
            저장됨 ({new Date(lastSaved).toLocaleTimeString()})
          </span>
        )}
      </div>
    </div>
  );
}

export default CMSEditorPage;
