'use client';
import { useState, useRef, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useTranslations } from 'next-intl';

type InitialPost = {
  id: number;
  slug: string;
  title: string;
  titleEn: string | null;
  contentMd: string;
  contentMdEn: string | null;
  coverImage: string;
  tags: string | null;
  status: string | null;
  publishDate: string | null;
} | null | undefined;

/** 从 Markdown 中解析标题与正文：
 *  - 优先读取 YAML frontmatter 中的 title 字段
 *  - 否则取第一个 H1 标题作为标题
 *  - 其余内容作为正文返回 */
function parseMarkdownTitle(content: string): { title: string; body: string } {
  let rest = content;
  const fmMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
  if (fmMatch) {
    const fm = fmMatch[1];
    rest = content.slice(fmMatch[0].length);
    const titleMatch = fm.match(/^title:\s*(.+)$/m);
    if (titleMatch) {
      const title = titleMatch[1].trim().replace(/^['"]|['"]$/g, '');
      return { title, body: rest.trim() };
    }
  }
  const h1Match = rest.match(/^#\s+(.+)$/m);
  if (h1Match) {
    const title = h1Match[1].trim();
    const body = rest.replace(/^#\s+.+\r?\n?/m, '').trim();
    return { title, body };
  }
  const lines = rest.split(/\r?\n/);
  const firstIdx = lines.findIndex(l => l.trim());
  if (firstIdx >= 0) {
    return { title: lines[firstIdx].trim(), body: lines.slice(firstIdx + 1).join('\n').trim() };
  }
  return { title: 'Untitled', body: rest.trim() };
}

export function PostEditor({ initialPost }: { initialPost: InitialPost }) {
  const t = useTranslations('editor');
  const router = useRouter();
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const textareaEnRef = useRef<HTMLTextAreaElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const coverInputRef = useRef<HTMLInputElement>(null);
  const folderInputRef = useRef<HTMLInputElement>(null);

  // 文件夹选择需要非标准属性 webkitdirectory / directory，通过 ref 设置以规避 TS 类型限制
  useEffect(() => {
    const el = folderInputRef.current;
    if (el) {
      el.setAttribute('webkitdirectory', '');
      el.setAttribute('directory', '');
    }
  }, []);

  const [title, setTitle] = useState(initialPost?.title || '');
  const [titleEn, setTitleEn] = useState(initialPost?.titleEn || '');
  const [slug, setSlug] = useState(initialPost?.slug || '');
  const [coverImage, setCoverImage] = useState(initialPost?.coverImage || '');
  const [tags, setTags] = useState(initialPost?.tags || '');
  const [contentMd, setContentMd] = useState(initialPost?.contentMd || '');
  const [contentMdEn, setContentMdEn] = useState(initialPost?.contentMdEn || '');
  const [status, setStatus] = useState<'draft' | 'published'>(initialPost?.status === 'published' ? 'published' : 'draft');
  const [saving, setSaving] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [coverUploading, setCoverUploading] = useState(false);
  const [importing, setImporting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const successTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  /** 显示成功提示，3 秒后自动消失 */
  const showSuccess = (msg: string) => {
    setSuccess(msg);
    if (successTimer.current) clearTimeout(successTimer.current);
    successTimer.current = setTimeout(() => {
      setSuccess(null);
      successTimer.current = null;
    }, 3000);
  };

  /** 显示错误提示，3 秒后自动消失 */
  const showError = (msg: string) => {
    setError(msg);
    if (successTimer.current) clearTimeout(successTimer.current);
    successTimer.current = setTimeout(() => {
      setError(null);
      successTimer.current = null;
    }, 3000);
  };

  /** 在指定 textarea 光标处插入文本 */
  const insertAtCursor = (
    ta: HTMLTextAreaElement,
    text: string,
    content: string,
    setContent: (v: string) => void,
  ) => {
    const start = ta.selectionStart;
    const end = ta.selectionEnd;
    const newContent = content.slice(0, start) + text + content.slice(end);
    setContent(newContent);
    setTimeout(() => {
      ta.focus();
      ta.selectionStart = ta.selectionEnd = start + text.length;
    }, 0);
  };

  const insertBreakpoint = () => {
    const ta = textareaRef.current;
    if (!ta) return;
    insertAtCursor(ta, '\n\n<!--break-->\n\n', contentMd, setContentMd);
  };

  /** 上传图片到服务端，返回 URL */
  const uploadImage = async (file: File): Promise<string | null> => {
    if (!file.type.startsWith('image/')) {
      showError('仅支持图片文件');
      return null;
    }
    setUploading(true);
    setError(null);
    try {
      const fd = new FormData();
      fd.append('file', file);
      const res = await fetch('/api/upload', { method: 'POST', body: fd });
      const data = await res.json();
      if (!res.ok) {
        showError(data.error || '上传失败');
        return null;
      }
      return data.url as string;
    } catch {
      showError('上传失败');
      return null;
    } finally {
      setUploading(false);
    }
  };

  /** 上传图片并插入 Markdown 到指定 textarea */
  const uploadAndInsert = async (
    file: File,
    ta: HTMLTextAreaElement,
    content: string,
    setContent: (v: string) => void,
  ) => {
    const url = await uploadImage(file);
    if (url) {
      const alt = file.name.replace(/\.[^.]+$/, '');
      insertAtCursor(ta, `\n\n![${alt}](${url})\n\n`, content, setContent);
    }
  };

  /** 工具栏按钮触发文件选择 */
  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    const ta = textareaRef.current;
    if (file && ta) {
      uploadAndInsert(file, ta, contentMd, setContentMd);
    }
    // 重置 input 以便重复选择同一文件
    e.target.value = '';
  };

  /** 封面图上传：上传后写入 URL 输入框 */
  const handleCoverSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setCoverUploading(true);
    const url = await uploadImage(file);
    if (url) setCoverImage(url);
    setCoverUploading(false);
    e.target.value = '';
  };

  /** 导入文件夹：读取 Markdown，并行上传所有图片，替换引用后填充英文标题与正文 */
  const handleFolderSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    e.target.value = '';
    if (!files.length) return;

    const mdFiles = files.filter(f => f.name.toLowerCase().endsWith('.md'));
    const imageFiles = files.filter(f => f.type.startsWith('image/'));

    if (!mdFiles.length) {
      showError('文件夹中未找到 Markdown 文件');
      return;
    }

    setImporting(true);
    setError(null);
    try {
      // 1. 并行上传所有图片，建立「原文件名 -> 上传后 URL」映射
      const urlMap: Record<string, string> = {};
      await Promise.all(imageFiles.map(async (file) => {
        const fd = new FormData();
        fd.append('file', file);
        try {
          const res = await fetch('/api/upload', { method: 'POST', body: fd });
          const data = await res.json().catch(() => ({}));
          if (res.ok && data.url) urlMap[file.name] = data.url as string;
        } catch {
          // 单张图片失败不中断整体导入
        }
      }));

      // 2. 读取 Markdown 内容
      let content = await mdFiles[0].text();

      // 3. 将正文中的本地图片引用替换为上传后的 URL（按文件名匹配）
      content = content.replace(/(!\[[^\]]*\]\()([^)]+)(\))/g, (match, prefix: string, path: string, suffix: string) => {
        const basename = path.split('/').pop() || path;
        return urlMap[basename] ? `${prefix}${urlMap[basename]}${suffix}` : match;
      });

      // 4. 解析标题与正文
      const { title, body } = parseMarkdownTitle(content);

      // 5. 填充字段：英文标题、英文正文、状态默认草稿；封面与标签留给用户填写
      setTitleEn(title);
      setContentMdEn(body);
      setStatus('draft');
      showSuccess('文件夹导入成功，请补充封面图与标签');
    } catch {
      showError('文件夹导入失败，请重试');
    } finally {
      setImporting(false);
    }
  };

  /** 拖拽图片到 textarea */
  const handleDrop = (e: React.DragEvent<HTMLTextAreaElement>, isEn: boolean) => {
    const file = e.dataTransfer.files?.[0];
    if (!file || !file.type.startsWith('image/')) return;
    e.preventDefault();
    const ta = isEn ? textareaEnRef.current : textareaRef.current;
    if (!ta) return;
    const content = isEn ? contentMdEn : contentMd;
    const setContent = isEn ? setContentMdEn : setContentMd;
    uploadAndInsert(file, ta, content, setContent);
  };

  /** 粘贴图片到 textarea */
  const handlePaste = (e: React.ClipboardEvent<HTMLTextAreaElement>, isEn: boolean) => {
    const items = e.clipboardData?.items;
    if (!items) return;
    for (const item of items) {
      if (item.type.startsWith('image/')) {
        const file = item.getAsFile();
        if (!file) continue;
        e.preventDefault();
        const ta = isEn ? textareaEnRef.current : textareaRef.current;
        if (!ta) return;
        const content = isEn ? contentMdEn : contentMd;
        const setContent = isEn ? setContentMdEn : setContentMd;
        uploadAndInsert(file, ta, content, setContent);
        return;
      }
    }
  };

  const handleSave = async (publish: boolean) => {
    setError(null);
    setSuccess(null);
    if (!titleEn || !contentMdEn || !coverImage) {
      showError('请填写英文标题、封面图、英文正文');
      return;
    }
    setSaving(true);
    try {
      const targetStatus = publish ? 'published' : status;
      const body = {
        id: initialPost?.id,
        title, titleEn: titleEn || undefined,
        slug: slug || undefined,
        coverImage, tags: tags || undefined,
        contentMd, contentMdEn: contentMdEn || undefined,
        status: targetStatus,
      };

      const url = initialPost ? `/api/blog/${slug}` : '/api/blog';
      const method = initialPost ? 'PUT' : 'POST';
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        showError(data.error || '保存失败');
        return;
      }
      setStatus(targetStatus);
      showSuccess(publish ? '发布成功！' : '保存成功！');

      // 新建博文：延迟跳转到编辑页，让用户看到成功提示
      if (!initialPost && data.post?.slug) {
        setTimeout(() => {
          router.push(`/admin/editor/${data.post.slug}`);
        }, 1500);
      }
    } catch {
      showError('保存失败，请重试');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="editor-form">
      {/* 新建博文时支持从文件夹导入 Markdown 与图片 */}
      {!initialPost && (
        <div className="editor-toolbar" style={{ marginBottom: '1rem' }}>
          <button type="button" onClick={() => folderInputRef.current?.click()} disabled={importing}>
            {importing ? '导入中...' : '📁 从文件夹导入'}
          </button>
          <input
            ref={folderInputRef}
            type="file"
            multiple
            onChange={handleFolderSelect}
            style={{ display: 'none' }}
          />
          <span style={{ fontSize: '0.8rem', color: '#888' }}>
            选择包含 .md 与图片的文件夹，自动填充英文标题与正文
          </span>
        </div>
      )}

      <div className="editor-field">
        <label>{t('title')}</label>
        <input value={title} onChange={e => setTitle(e.target.value)} placeholder="博文标题" />
      </div>

      <div className="editor-field">
        <label>{t('titleEn')}</label>
        <input value={titleEn} onChange={e => setTitleEn(e.target.value)} placeholder="English Title" />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
        <div className="editor-field">
          <label>{t('slug')}</label>
          <input value={slug} onChange={e => setSlug(e.target.value)} placeholder="url-slug" disabled={!!initialPost} />
        </div>
        <div className="editor-field">
          <label>{t('status')}</label>
          <select value={status} onChange={e => setStatus(e.target.value as 'draft' | 'published')}>
            <option value="draft">{t('draft')}</option>
            <option value="published">{t('published')}</option>
          </select>
        </div>
      </div>

      <div className="editor-field">
        <label>{t('coverImage')}</label>
        <div style={{ display: 'flex', gap: '0.5rem' }}>
          <input value={coverImage} onChange={e => setCoverImage(e.target.value)} placeholder="https://..." style={{ flex: 1 }} />
          <button type="button" onClick={() => coverInputRef.current?.click()} disabled={coverUploading} className="header-btn">
            {coverUploading ? '上传中...' : '📷 上传封面'}
          </button>
          <input
            ref={coverInputRef}
            type="file"
            accept="image/jpeg,image/png,image/gif,image/webp,image/svg+xml"
            onChange={handleCoverSelect}
            style={{ display: 'none' }}
          />
        </div>
        {coverImage && (
          <img src={coverImage} alt="" style={{ marginTop: '0.5rem', width: '100%', maxHeight: '200px', objectFit: 'cover', borderRadius: '8px' }} />
        )}
      </div>

      <div className="editor-field">
        <label>{t('tags')}</label>
        <input value={tags} onChange={e => setTags(e.target.value)} placeholder="tech, design, life" />
      </div>

      <div className="editor-field">
        <label>{t('contentMd')}</label>
        <div className="editor-toolbar">
          <button type="button" onClick={insertBreakpoint}>{t('insertBreakpoint')} &lt;!--break--&gt;</button>
          <button type="button" onClick={() => fileInputRef.current?.click()} disabled={uploading}>
            {uploading ? '上传中...' : '📷 上传图片'}
          </button>
          <input
            ref={fileInputRef}
            type="file"
            accept="image/jpeg,image/png,image/gif,image/webp,image/svg+xml"
            onChange={handleFileSelect}
            style={{ display: 'none' }}
          />
        </div>
        <textarea
          ref={textareaRef}
          value={contentMd}
          onChange={e => setContentMd(e.target.value)}
          onDrop={e => handleDrop(e, false)}
          onPaste={e => handlePaste(e, false)}
          onDragOver={e => e.preventDefault()}
          placeholder={'## 引言\n\n这里是断点之前的内容...\n\n<!--break-->\n\n## 正文\n\n这里是断点之后的内容...\n\n支持拖拽或粘贴图片自动上传'}
          style={{ minHeight: '300px' }}
        />
      </div>

      <div className="editor-field">
        <label>{t('contentMdEn')}</label>
        <textarea
          ref={textareaEnRef}
          value={contentMdEn}
          onChange={e => setContentMdEn(e.target.value)}
          onDrop={e => handleDrop(e, true)}
          onPaste={e => handlePaste(e, true)}
          onDragOver={e => e.preventDefault()}
          placeholder="## Introduction\n\n... (drag & paste images supported)"
          style={{ minHeight: '200px' }}
        />
      </div>

      {(error || success) && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem', marginBottom: '0.5rem' }}>
          {error && <div className="modal-error">{error}</div>}
          {success && <div className="modal-success">{success}</div>}
        </div>
      )}

      <div style={{ display: 'flex', gap: '0.5rem' }}>
        <button onClick={() => handleSave(false)} disabled={saving} className="header-btn">
          {saving ? '...' : t('save')}
        </button>
        <button onClick={() => handleSave(true)} disabled={saving} className="header-btn primary">
          {t('publish')}
        </button>
      </div>
    </div>
  );
}
