"use client";

import React, { useState } from "react";
import clsx from "clsx";
import {
  ServiceTier,
  ComponentType,
  type BaseTemplate,
  type BaseComponent,
} from "../../../types/template-system";

// =============================================================================
// Types
// =============================================================================

interface ComponentConfig {
  [componentId: string]: {
    visible: boolean;
    settings: Record<string, unknown>;
  };
}

interface ThemeConfig {
  primaryColor: string;
  secondaryColor: string;
  accentColor: string;
  fontFamily: string;
  borderRadius: number;
}

interface LayoutConfig {
  containerWidth: "full" | "contained" | "narrow";
  spacing: "compact" | "normal" | "spacious";
  headerStyle: "simple" | "standard" | "advanced";
  footerStyle: "minimal" | "standard" | "comprehensive";
}

interface TemplateConfig {
  theme: ThemeConfig;
  layout: LayoutConfig;
  components: ComponentConfig;
  globalSettings: {
    animations: boolean;
    showBranding: boolean;
    mobileOptimized: boolean;
    seoOptimized: boolean;
  };
}

interface TemplateCustomizerProps {
  template: BaseTemplate;
  onUpdate: (config: TemplateConfig) => void;
  tier: ServiceTier;
}

// =============================================================================
// Default Configuration
// =============================================================================

const defaultTemplateConfig: TemplateConfig = {
  theme: {
    primaryColor: "#3b82f6",
    secondaryColor: "#64748b",
    accentColor: "#f59e0b",
    fontFamily: "Inter",
    borderRadius: 8,
  },
  layout: {
    containerWidth: "contained",
    spacing: "normal",
    headerStyle: "standard",
    footerStyle: "standard",
  },
  components: {},
  globalSettings: {
    animations: true,
    showBranding: true,
    mobileOptimized: true,
    seoOptimized: true,
  },
};

// =============================================================================
// Color Presets
// =============================================================================

const colorPresets = [
  { name: "블루", primary: "#3b82f6", secondary: "#64748b", accent: "#f59e0b" },
  { name: "그린", primary: "#10b981", secondary: "#6b7280", accent: "#f59e0b" },
  { name: "퍼플", primary: "#8b5cf6", secondary: "#6b7280", accent: "#f59e0b" },
  { name: "핑크", primary: "#ec4899", secondary: "#6b7280", accent: "#f59e0b" },
];

// =============================================================================
// Font Options
// =============================================================================

const fontOptions = [
  { name: "Inter", value: "Inter" },
  { name: "Pretendard", value: "Pretendard" },
  { name: "Noto Sans KR", value: "Noto Sans KR" },
  { name: "맑은 고딕", value: "Malgun Gothic" },
];

// =============================================================================
// Main Component
// =============================================================================

export function TemplateCustomizer({
  template,
  onUpdate,
  tier,
}: TemplateCustomizerProps) {
  const [templateConfig, setTemplateConfig] = useState<TemplateConfig>(
    defaultTemplateConfig
  );
  const [activeTab, setActiveTab] = useState<string>("theme");

  const updateComponentSettings = (
    componentId: string,
    settings: Record<string, unknown>
  ) => {
    const newConfig = {
      ...templateConfig,
      components: {
        ...templateConfig.components,
        [componentId]: {
          ...templateConfig.components[componentId],
          settings,
        },
      },
    };
    setTemplateConfig(newConfig);
    onUpdate(newConfig);
  };

  const updateTheme = (themeUpdates: Partial<ThemeConfig>) => {
    const newConfig = {
      ...templateConfig,
      theme: {
        ...templateConfig.theme,
        ...themeUpdates,
      },
    };
    setTemplateConfig(newConfig);
    onUpdate(newConfig);
  };

  const updateLayout = (layoutUpdates: Partial<LayoutConfig>) => {
    const newConfig = {
      ...templateConfig,
      layout: {
        ...templateConfig.layout,
        ...layoutUpdates,
      },
    };
    setTemplateConfig(newConfig);
    onUpdate(newConfig);
  };

  const updateGlobalSettings = (
    globalUpdates: Partial<TemplateConfig["globalSettings"]>
  ) => {
    const newConfig = {
      ...templateConfig,
      globalSettings: {
        ...templateConfig.globalSettings,
        ...globalUpdates,
      },
    };
    setTemplateConfig(newConfig);
    onUpdate(newConfig);
  };

  const tabs = [
    { id: "theme", label: "테마 설정", icon: "🎨" },
    { id: "layout", label: "레이아웃", icon: "📐" },
    { id: "components", label: "컴포넌트", icon: "🧩" },
    { id: "global", label: "전역 설정", icon: "⚙️" },
  ];

  return (
    <div className="bg-white border border-gray-200 rounded-lg shadow-sm">
      {/* Header */}
      <div className="px-6 py-4 border-b border-gray-200">
        <h3 className="text-lg font-medium text-gray-900">
          템플릿 커스터마이징
        </h3>
        <p className="mt-1 text-sm text-gray-500">
          {tier} 티어 - {template.name}
        </p>
      </div>

      {/* Tabs */}
      <div className="border-b border-gray-200">
        <nav className="flex space-x-8 px-6" aria-label="Tabs">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={clsx(
                "py-4 px-1 border-b-2 font-medium text-sm transition-colors",
                activeTab === tab.id
                  ? "border-blue-500 text-blue-600"
                  : "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
              )}
            >
              <span className="mr-2">{tab.icon}</span>
              {tab.label}
            </button>
          ))}
        </nav>
      </div>

      {/* Content */}
      <div className="p-6">
        {/* Theme Settings */}
        {activeTab === "theme" && (
          <div className="space-y-6">
            <div>
              <h4 className="text-lg font-medium text-gray-900 mb-4">
                색상 설정
              </h4>

              {/* Color Presets */}
              <div className="mb-6">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  프리셋 색상
                </label>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                  {colorPresets.map((preset) => (
                    <button
                      key={preset.name}
                      onClick={() =>
                        updateTheme({
                          primaryColor: preset.primary,
                          secondaryColor: preset.secondary,
                          accentColor: preset.accent,
                        })
                      }
                      className="p-3 border border-gray-200 rounded-lg hover:border-blue-500 transition-colors"
                    >
                      <div className="flex space-x-1 mb-2">
                        <div
                          className="w-4 h-4 rounded"
                          style={{ backgroundColor: preset.primary }}
                        />
                        <div
                          className="w-4 h-4 rounded"
                          style={{ backgroundColor: preset.secondary }}
                        />
                        <div
                          className="w-4 h-4 rounded"
                          style={{ backgroundColor: preset.accent }}
                        />
                      </div>
                      <div className="text-xs text-gray-600">{preset.name}</div>
                    </button>
                  ))}
                </div>
              </div>

              {/* Custom Colors */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    기본 색상
                  </label>
                  <input
                    type="color"
                    value={templateConfig.theme.primaryColor}
                    onChange={(e) =>
                      updateTheme({ primaryColor: e.target.value })
                    }
                    className="w-full h-10 border border-gray-300 rounded-md"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    보조 색상
                  </label>
                  <input
                    type="color"
                    value={templateConfig.theme.secondaryColor}
                    onChange={(e) =>
                      updateTheme({ secondaryColor: e.target.value })
                    }
                    className="w-full h-10 border border-gray-300 rounded-md"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    강조 색상
                  </label>
                  <input
                    type="color"
                    value={templateConfig.theme.accentColor}
                    onChange={(e) =>
                      updateTheme({ accentColor: e.target.value })
                    }
                    className="w-full h-10 border border-gray-300 rounded-md"
                  />
                </div>
              </div>
            </div>

            {/* Typography */}
            <div>
              <h4 className="text-lg font-medium text-gray-900 mb-4">
                타이포그래피
              </h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    폰트 패밀리
                  </label>
                  <select
                    value={templateConfig.theme.fontFamily}
                    onChange={(e) =>
                      updateTheme({ fontFamily: e.target.value })
                    }
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                  >
                    {fontOptions.map((font) => (
                      <option key={font.value} value={font.value}>
                        {font.name}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    모서리 둥글기
                  </label>
                  <input
                    type="range"
                    min="0"
                    max="20"
                    value={templateConfig.theme.borderRadius}
                    onChange={(e) =>
                      updateTheme({ borderRadius: parseInt(e.target.value) })
                    }
                    className="w-full"
                  />
                  <div className="text-sm text-gray-500 mt-1">
                    {templateConfig.theme.borderRadius}px
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Layout Settings */}
        {activeTab === "layout" && (
          <div className="space-y-6">
            <div>
              <h4 className="text-lg font-medium text-gray-900 mb-4">
                레이아웃 설정
              </h4>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    컨테이너 너비
                  </label>
                  <select
                    value={templateConfig.layout.containerWidth}
                    onChange={(e) =>
                      updateLayout({
                        containerWidth: e.target
                          .value as LayoutConfig["containerWidth"],
                      })
                    }
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                  >
                    <option value="full">전체 너비</option>
                    <option value="contained">제한된 너비</option>
                    <option value="narrow">좁은 너비</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    간격 설정
                  </label>
                  <select
                    value={templateConfig.layout.spacing}
                    onChange={(e) =>
                      updateLayout({
                        spacing: e.target.value as LayoutConfig["spacing"],
                      })
                    }
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                  >
                    <option value="compact">촘촘한 간격</option>
                    <option value="normal">일반 간격</option>
                    <option value="spacious">넉넉한 간격</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    헤더 스타일
                  </label>
                  <select
                    value={templateConfig.layout.headerStyle}
                    onChange={(e) =>
                      updateLayout({
                        headerStyle: e.target
                          .value as LayoutConfig["headerStyle"],
                      })
                    }
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                  >
                    <option value="simple">간단한 헤더</option>
                    <option value="standard">표준 헤더</option>
                    <option value="advanced">고급 헤더</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    푸터 스타일
                  </label>
                  <select
                    value={templateConfig.layout.footerStyle}
                    onChange={(e) =>
                      updateLayout({
                        footerStyle: e.target
                          .value as LayoutConfig["footerStyle"],
                      })
                    }
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                  >
                    <option value="minimal">최소 푸터</option>
                    <option value="standard">표준 푸터</option>
                    <option value="comprehensive">종합 푸터</option>
                  </select>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Component Settings */}
        {activeTab === "components" && (
          <div className="space-y-6">
            <div>
              <h4 className="text-lg font-medium text-gray-900 mb-4">
                컴포넌트 관리
              </h4>

              <div className="space-y-4">
                {template.components.map((component) => (
                  <div
                    key={component.id}
                    className="flex items-center justify-between p-4 border border-gray-200 rounded-lg"
                  >
                    <div>
                      <h5 className="font-medium text-gray-900">
                        {component.title}
                      </h5>
                      <p className="text-sm text-gray-500">
                        {component.description}
                      </p>
                    </div>
                    <div className="flex items-center space-x-4">
                      <label className="flex items-center">
                        <input
                          type="checkbox"
                          checked={component.settings.visible}
                          onChange={(e) =>
                            updateComponentSettings(component.id, {
                              ...component.settings,
                              visible: e.target.checked,
                            })
                          }
                          className="mr-2"
                        />
                        <span className="text-sm text-gray-700">표시</span>
                      </label>
                      <button className="text-blue-600 hover:text-blue-800 text-sm font-medium">
                        설정
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* Global Settings */}
        {activeTab === "global" && (
          <div className="space-y-6">
            <div>
              <h4 className="text-lg font-medium text-gray-900 mb-4">
                전역 설정
              </h4>

              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <div>
                    <h4 className="font-medium">애니메이션 효과</h4>
                    <p className="text-sm text-gray-600">
                      페이지 로딩과 스크롤 시 애니메이션 효과
                    </p>
                  </div>
                  <input
                    type="checkbox"
                    checked={templateConfig.globalSettings.animations}
                    onChange={(e) =>
                      updateGlobalSettings({ animations: e.target.checked })
                    }
                    className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                  />
                </div>

                <div className="flex items-center justify-between">
                  <div>
                    <h4 className="font-medium">AgentC 브랜딩 표시</h4>
                    <p className="text-sm text-gray-600">
                      사이트 하단에 &ldquo;Powered by AgentC&rdquo; 표시
                    </p>
                  </div>
                  <input
                    type="checkbox"
                    checked={templateConfig.globalSettings.showBranding}
                    onChange={(e) =>
                      updateGlobalSettings({ showBranding: e.target.checked })
                    }
                    className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                    disabled={tier === ServiceTier.STARTER}
                  />
                </div>

                <div className="flex items-center justify-between">
                  <div>
                    <h4 className="font-medium">모바일 최적화</h4>
                    <p className="text-sm text-gray-600">
                      모바일 디바이스에 최적화된 레이아웃
                    </p>
                  </div>
                  <input
                    type="checkbox"
                    checked={templateConfig.globalSettings.mobileOptimized}
                    onChange={(e) =>
                      updateGlobalSettings({
                        mobileOptimized: e.target.checked,
                      })
                    }
                    className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                  />
                </div>

                <div className="flex items-center justify-between">
                  <div>
                    <h4 className="font-medium">SEO 최적화</h4>
                    <p className="text-sm text-gray-600">
                      검색엔진 최적화를 위한 메타 태그 및 구조화된 데이터
                    </p>
                  </div>
                  <input
                    type="checkbox"
                    checked={templateConfig.globalSettings.seoOptimized}
                    onChange={(e) =>
                      updateGlobalSettings({ seoOptimized: e.target.checked })
                    }
                    className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                  />
                </div>

                {tier === ServiceTier.PLUS && (
                  <div className="mt-6 p-4 bg-gradient-to-r from-purple-50 to-blue-50 rounded-lg border border-purple-200">
                    <h4 className="font-medium text-purple-900 mb-2">
                      Plus 티어 전용 기능
                    </h4>
                    <div className="space-y-2 text-sm text-purple-700">
                      <div>• 화이트라벨링 (AgentC 브랜딩 제거)</div>
                      <div>• 고급 SEO 도구</div>
                      <div>• 무제한 커스터마이징</div>
                      <div>• 우선 고객 지원</div>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Footer */}
      <div className="px-6 py-4 bg-gray-50 border-t border-gray-200 rounded-b-lg">
        <div className="flex items-center justify-between">
          <div className="text-sm text-gray-500">
            변경사항은 실시간으로 미리보기에 반영됩니다.
          </div>
          <div className="flex space-x-3">
            <button className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
              초기화
            </button>
            <button className="px-4 py-2 text-sm font-medium text-white bg-blue-600 border border-transparent rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
              저장
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
