import { useState, useEffect } from 'react';
import { sanitizeInput } from '@common/utils/sanitize';
import { fetchBoardPost, createBoardPost, updateBoardPost } from '../services/boardApi';

interface BoardWriteFormProps {
  postSn?: number | null;
  defaultCategoryCd: string;
  onSaveComplete: () => void;
  onCancel: () => void;
}

// DB 카테고리 코드 ↔ 표시명
const CATEGORY_OPTIONS: Array<{ code: string; label: string }> = [
  { code: 'NOTICE', label: '공지사항' },
  { code: 'DATA', label: '자료실' },
  { code: 'QNA', label: 'Q&A' },
];

// 허용된 파일 확장자
const ALLOWED_FILE_EXTENSIONS = [
  '.pdf',
  '.doc',
  '.docx',
  '.xls',
  '.xlsx',
  '.hwp',
  '.png',
  '.jpg',
  '.jpeg',
];
const MAX_FILE_SIZE_MB = 10;

export function BoardWriteForm({
  postSn,
  defaultCategoryCd,
  onSaveComplete,
  onCancel,
}: BoardWriteFormProps) {
  const isEditMode = postSn != null;

  const [categoryCd, setCategoryCd] = useState(defaultCategoryCd);
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isFetching, setIsFetching] = useState(false);

  // 수정 모드: 기존 게시글 데이터 로드
  useEffect(() => {
    if (!isEditMode) return;
    let cancelled = false;
    const load = async () => {
      setIsFetching(true);
      try {
        const post = await fetchBoardPost(postSn!);
        if (cancelled) return;
        setCategoryCd(post.categoryCd);
        setTitle(post.title);
        setContent(post.content || '');
      } catch {
        if (!cancelled) {
          alert('게시글을 불러오는데 실패했습니다.');
          onCancel();
        }
      } finally {
        if (!cancelled) setIsFetching(false);
      }
    };
    load();
    return () => {
      cancelled = true;
    };
  }, [postSn, isEditMode, onCancel]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // 입력값 살균 (XSS 방지)
    const safeTitle = sanitizeInput(title, 200);
    const safeContent = sanitizeInput(content, 10000);

    if (!safeTitle) {
      alert('제목을 입력해주세요.');
      return;
    }
    if (!safeContent) {
      alert('내용을 입력해주세요.');
      return;
    }

    setIsLoading(true);
    try {
      if (isEditMode) {
        await updateBoardPost(postSn!, { title: safeTitle, content: safeContent });
        alert('게시글이 수정되었습니다.');
      } else {
        await createBoardPost({ categoryCd, title: safeTitle, content: safeContent });
        alert('게시글이 등록되었습니다.');
      }
      onSaveComplete();
    } catch (err) {
      alert((err as { message?: string })?.message || '저장에 실패했습니다.');
    } finally {
      setIsLoading(false);
    }
  };

  // 파일 업로드 보안 검증
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files) return;
    for (const file of Array.from(files)) {
      if (file.size > MAX_FILE_SIZE_MB * 1024 * 1024) {
        alert(`파일 크기 초과: ${file.name} (최대 ${MAX_FILE_SIZE_MB}MB)`);
        e.target.value = '';
        return;
      }
      const ext = '.' + (file.name.split('.').pop()?.toLowerCase() || '');
      if (!ALLOWED_FILE_EXTENSIONS.includes(ext)) {
        alert(`허용되지 않는 파일 형식: ${file.name}`);
        e.target.value = '';
        return;
      }
    }
  };

  if (isFetching) {
    return (
      <div className="flex flex-col h-full bg-bg-base items-center justify-center">
        <p className="text-fg-disabled text-label-1">게시글을 불러오는 중...</p>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} className="flex flex-col h-full bg-bg-base">
      {/* 헤더 */}
      <div className="flex items-center justify-between px-8 py-4 border-b border-stroke bg-bg-surface">
        <h2 className="text-title-3 font-bold text-fg">
          {isEditMode ? '게시글 수정' : '게시글 작성'}
        </h2>
        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={onCancel}
            className="rounded-sm text-label-1 font-semibold cursor-pointer text-fg-sub px-4 py-2 bg-bg-elevated border border-stroke"
          >
            돌아가기
          </button>
          <button
            type="submit"
            disabled={isLoading}
            className="rounded-sm text-label-1 font-semibold cursor-pointer text-color-accent px-4 py-2 bg-[color-mix(in_srgb,var(--color-accent)_8%,transparent)] border border-[color-mix(in_srgb,var(--color-accent)_30%,transparent)] disabled:opacity-50"
          >
            {isLoading ? '저장 중...' : isEditMode ? '수정하기' : '등록하기'}
          </button>
        </div>
      </div>

      {/* 폼 */}
      <div className="flex-1 flex flex-col overflow-hidden">
        <div className="flex-1 overflow-auto px-8 py-6">
          <div className="max-w-4xl mx-auto space-y-6">
            {/* 분류 선택 */}
            <div>
              <label className="block text-label-1 font-semibold text-fg-sub mb-2">
                분류 <span className="text-color-danger">*</span>
              </label>
              <select
                value={categoryCd}
                onChange={(e) => setCategoryCd(e.target.value)}
                disabled={isEditMode}
                className="w-full px-4 py-2.5 text-label-1 bg-bg-elevated border border-stroke rounded text-fg focus:border-color-accent focus:outline-none disabled:opacity-50"
              >
                {CATEGORY_OPTIONS.map((opt) => (
                  <option key={opt.code} value={opt.code}>
                    {opt.label}
                  </option>
                ))}
              </select>
            </div>

            {/* 제목 */}
            <div>
              <label className="block text-label-1 font-semibold text-fg-sub mb-2">
                제목 <span className="text-color-danger">*</span>
              </label>
              <input
                type="text"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                maxLength={200}
                placeholder="제목을 입력하세요"
                className="w-full px-4 py-2.5 text-label-1 bg-bg-elevated border border-stroke rounded text-fg placeholder-fg-disabled focus:border-color-accent focus:outline-none"
              />
            </div>

            {/* 내용 */}
            <div>
              <label className="block text-label-1 font-semibold text-fg-sub mb-2">
                내용 <span className="text-color-danger">*</span>
              </label>
              <textarea
                value={content}
                onChange={(e) => setContent(e.target.value)}
                maxLength={10000}
                placeholder="내용을 입력하세요"
                rows={15}
                className="w-full px-4 py-3 text-label-1 bg-bg-elevated border border-stroke rounded text-fg placeholder-fg-disabled focus:border-color-accent focus:outline-none resize-none"
              />
            </div>

            {/* 파일 첨부 (향후 API 연동 예정) */}
            <div>
              <label className="block text-label-1 font-semibold text-fg-sub mb-2">첨부파일</label>
              <div className="flex items-center gap-3">
                <input
                  type="file"
                  multiple
                  accept={ALLOWED_FILE_EXTENSIONS.join(',')}
                  onChange={handleFileChange}
                  className="hidden"
                  id="file-upload"
                />
                <label
                  htmlFor="file-upload"
                  className="px-4 py-2 text-label-1 font-semibold rounded bg-bg-elevated text-fg border border-stroke hover:bg-bg-card cursor-pointer transition-colors"
                >
                  파일 선택
                </label>
                <span className="text-label-1 text-fg-disabled">선택된 파일 없음</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </form>
  );
}
