/**
 * 팝업관리 상세 페이지 설정
 * IntegratedDetailTemplate V2 마이그레이션
 */

import { Megaphone } from 'lucide-react';
import type { DetailConfig, FieldDefinition, SectionDefinition } from '@/components/templates/IntegratedDetailTemplate/types';
import type { Popup, PopupFormData, PopupTarget, PopupStatus } from './types';
import { RichTextEditor } from '@/components/board/RichTextEditor';
import { createElement } from 'react';
import { sanitizeHTML } from '@/lib/sanitize';

// ===== 대상 옵션 =====
const TARGET_OPTIONS = [
  { value: 'all', label: '전사' },
  { value: 'department', label: '부서별' },
];

// ===== 상태 옵션 =====
const STATUS_OPTIONS = [
  { value: 'inactive', label: '사용안함' },
  { value: 'active', label: '사용함' },
];

// ===== 필드 정의 =====
export const popupFields: FieldDefinition[] = [
  {
    key: 'target',
    label: '대상',
    type: 'select',
    required: true,
    options: TARGET_OPTIONS,
    placeholder: '대상을 선택해주세요',
    validation: [
      { type: 'required', message: '대상을 선택해주세요.' },
    ],
  },
  {
    key: 'startDate',
    label: '시작일',
    type: 'date',
    required: true,
    validation: [
      { type: 'required', message: '시작일을 선택해주세요.' },
    ],
  },
  {
    key: 'endDate',
    label: '종료일',
    type: 'date',
    required: true,
    validation: [
      { type: 'required', message: '종료일을 선택해주세요.' },
      {
        type: 'custom',
        message: '종료일은 시작일 이후여야 합니다.',
        validate: (value, formData) => {
          const startDate = formData.startDate as string;
          const endDate = value as string;
          if (!startDate || !endDate) return true;
          return endDate >= startDate;
        },
      },
    ],
  },
  {
    key: 'title',
    label: '제목',
    type: 'text',
    required: true,
    placeholder: '제목을 입력해주세요',
    gridSpan: 2,
    validation: [
      { type: 'required', message: '제목을 입력해주세요.' },
    ],
  },
  {
    key: 'content',
    label: '내용',
    type: 'custom',
    required: true,
    gridSpan: 2,
    validation: [
      {
        type: 'custom',
        message: '내용을 입력해주세요.',
        validate: (value) => {
          const content = value as string;
          return !!content && content.trim() !== '' && content !== '<p></p>';
        },
      },
    ],
    renderField: ({ value, onChange, mode, disabled }) => {
      if (mode === 'view') {
        // View 모드: HTML 렌더링
        return createElement('div', {
          className: 'border border-gray-200 rounded-md p-4 bg-gray-50 min-h-[100px] prose prose-sm max-w-none',
          dangerouslySetInnerHTML: { __html: sanitizeHTML((value as string) || '') },
        });
      }
      // Edit/Create 모드: RichTextEditor
      return createElement(RichTextEditor, {
        value: (value as string) || '',
        onChange: onChange,
        placeholder: '내용을 입력해주세요',
        minHeight: '200px',
        disabled: disabled,
      });
    },
    formatValue: (value) => {
      if (!value) return '-';
      return createElement('div', {
        className: 'border border-gray-200 rounded-md p-4 bg-gray-50 min-h-[100px] prose prose-sm max-w-none',
        dangerouslySetInnerHTML: { __html: sanitizeHTML(value as string) },
      });
    },
  },
  {
    key: 'status',
    label: '상태',
    type: 'radio',
    options: STATUS_OPTIONS,
    defaultValue: 'inactive',
  },
  {
    key: 'author',
    label: '작성자',
    type: 'text',
    disabled: true,
    hideInForm: false,
  },
  {
    key: 'createdAt',
    label: '등록일시',
    type: 'text',
    disabled: true,
    hideInForm: false,
  },
];

// ===== 섹션 정의 =====
export const popupSections: SectionDefinition[] = [
  {
    id: 'basicInfo',
    title: '팝업 정보',
    description: '팝업의 기본 정보를 입력해주세요',
    fields: ['target', 'startDate', 'endDate', 'title', 'content', 'status', 'author', 'createdAt'],
  },
];

// ===== 설정 =====
export const popupDetailConfig: DetailConfig<Popup> = {
  title: '팝업관리',
  description: '팝업 목록을 관리합니다',
  icon: Megaphone,
  basePath: '/ko/settings/popup-management',
  fields: popupFields,
  sections: popupSections,
  gridColumns: 2,
  actions: {
    submitLabel: '저장',
    cancelLabel: '취소',
    showDelete: true,
    deleteLabel: '삭제',
    showEdit: true,
    editLabel: '수정',
    showBack: true,
    backLabel: '목록',
    deleteConfirmMessage: {
      title: '팝업 삭제',
      description: '이 팝업을 삭제하시겠습니까? 삭제된 데이터는 복구할 수 없습니다.',
    },
  },
  transformInitialData: (data: Popup) => ({
    target: data.target || 'all',
    startDate: data.startDate || '',
    endDate: data.endDate || '',
    title: data.title || '',
    content: data.content || '',
    status: data.status || 'inactive',
    author: data.author || '',
    createdAt: data.createdAt || '',
  }),
  transformSubmitData: (formData): Partial<PopupFormData> => ({
    target: formData.target as PopupTarget,
    title: formData.title as string,
    content: formData.content as string,
    status: formData.status as PopupStatus,
    startDate: formData.startDate as string,
    endDate: formData.endDate as string,
  }),
};
