"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { BottomToast, type BottomToastNotice } from "@/components/bottom-toast";
import { MarkdownPreview } from "@/components/markdown-preview";
import { NotionBlogContentEditor } from "@/components/notion-blog-content-editor";
import type { MarketingBlogPost, MarketingBlogStatus } from "@/lib/marketing-blog";

type EditorDraft = {
  contentMarkdown: string;
  excerpt: string;
  id: number | null;
  keywordsText: string;
  seoDescription: string;
  slug: string;
  status: MarketingBlogStatus;
  title: string;
};

type BlogApiResponse = {
  message?: string;
  ok?: boolean;
  post?: MarketingBlogPost;
};

function formatDate(value: string | null) {
  if (!value) return "임시저장";

  return new Intl.DateTimeFormat("ko-KR", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  }).format(new Date(value));
}

function toDraft(post: MarketingBlogPost): EditorDraft {
  return {
    contentMarkdown: post.contentMarkdown,
    excerpt: post.excerpt,
    id: post.id,
    keywordsText: post.keywords.join(", "),
    seoDescription: post.seoDescription,
    slug: post.slug,
    status: post.status,
    title: post.title,
  };
}

function makeNewDraft(): EditorDraft {
  return {
    contentMarkdown: "",
    excerpt: "",
    id: null,
    keywordsText: "",
    seoDescription: "",
    slug: `new-guide-${new Date().toISOString().slice(0, 10).replaceAll("-", "")}`,
    status: "draft",
    title: "새 가이드 제목",
  };
}

function editorFieldClass() {
  return "h-10 w-full border-b border-[#dfe7f3] bg-transparent px-0 text-[14px] text-[#1a2943] outline-none transition-colors placeholder:text-[#9aa8bd] focus:border-[#8eb5ff]";
}

export function KavenixBlogEditor({ posts: initialPosts }: { posts: MarketingBlogPost[] }) {
  const router = useRouter();
  const [posts, setPosts] = useState(initialPosts);
  const [draft, setDraft] = useState<EditorDraft>(() => initialPosts[0] ? toDraft(initialPosts[0]) : makeNewDraft());
  const [isPreviewOpen, setIsPreviewOpen] = useState(false);
  const [saving, setSaving] = useState(false);
  const [toast, setToast] = useState<BottomToastNotice | null>(null);

  useEffect(() => {
    if (!toast) return undefined;
    const timer = window.setTimeout(() => setToast(null), 4200);
    return () => window.clearTimeout(timer);
  }, [toast]);

  function updateDraft<Key extends keyof EditorDraft>(key: Key, value: EditorDraft[Key]) {
    setDraft((current) => ({ ...current, [key]: value }));
  }

  function selectPost(post: MarketingBlogPost) {
    setDraft(toDraft(post));
    setIsPreviewOpen(false);
  }

  function startNewPost() {
    setDraft(makeNewDraft());
    setIsPreviewOpen(false);
  }

  async function save(nextStatus: MarketingBlogStatus) {
    setSaving(true);

    try {
      const payload = {
        contentMarkdown: draft.contentMarkdown,
        excerpt: draft.excerpt,
        keywords: draft.keywordsText,
        seoDescription: draft.seoDescription,
        slug: draft.slug,
        status: nextStatus,
        title: draft.title,
      };
      const response = await fetch(
        draft.id ? `/api/kavenix/blog/${draft.id}` : "/api/kavenix/blog",
        {
          method: draft.id ? "PATCH" : "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload),
        },
      );
      const result = (await response.json().catch(() => null)) as BlogApiResponse | null;

      if (!response.ok || !result?.ok || !result.post) {
        throw new Error(result?.message || "블로그 글 저장 중 오류가 발생했습니다.");
      }

      const savedPost = result.post;
      setPosts((current) => {
        const existingIndex = current.findIndex((post) => post.id === savedPost.id);
        return existingIndex < 0
          ? [savedPost, ...current]
          : current.map((post) => post.id === savedPost.id ? savedPost : post);
      });
      setDraft(toDraft(savedPost));
      setToast({ tone: "success", message: result.message || "저장했습니다." });
      router.refresh();
    } catch (error) {
      setToast({
        tone: "error",
        message: error instanceof Error ? error.message : "블로그 글 저장 중 오류가 발생했습니다.",
      });
    } finally {
      setSaving(false);
    }
  }

  async function deletePost() {
    if (!draft.id || !window.confirm("이 블로그 글을 삭제할까요? 공개된 글은 즉시 주소에서 사라집니다.")) {
      return;
    }

    const deletedPostId = draft.id;
    setSaving(true);

    try {
      const response = await fetch(`/api/kavenix/blog/${deletedPostId}`, { method: "DELETE" });
      const result = (await response.json().catch(() => null)) as BlogApiResponse | null;

      if (!response.ok || !result?.ok) {
        throw new Error(result?.message || "블로그 글 삭제 중 오류가 발생했습니다.");
      }

      const remainingPosts = posts.filter((post) => post.id !== deletedPostId);
      setPosts(remainingPosts);
      setDraft(remainingPosts[0] ? toDraft(remainingPosts[0]) : makeNewDraft());
      setToast({ tone: "success", message: result.message || "블로그 글을 삭제했습니다." });
      router.refresh();
    } catch (error) {
      setToast({
        tone: "error",
        message: error instanceof Error ? error.message : "블로그 글 삭제 중 오류가 발생했습니다.",
      });
    } finally {
      setSaving(false);
    }
  }

  const published = draft.status === "published";

  return (
    <div className="min-w-0 bg-white">
      <div className="grid min-h-[680px] lg:grid-cols-[280px_minmax(0,1fr)]">
        <aside className="min-w-0 border-b border-[#edf1f6] lg:border-b-0 lg:border-r">
          <div className="flex items-center justify-between gap-3 border-b border-[#edf1f6] px-3 py-3 sm:px-4 lg:px-5">
            <p className="text-[14px] font-semibold tracking-[-0.03em] text-[#16233c]">전체 글 {posts.length}</p>
            <button type="button" onClick={startNewPost} className="om-btn-primary h-8 rounded-[9px] px-3 text-[12px] shadow-none">새 글</button>
          </div>
          <div className="max-h-[380px] overflow-y-auto lg:max-h-[calc(100vh-255px)]">
            {posts.map((post) => {
              const active = post.id === draft.id;

              return (
                <button
                  key={post.id}
                  type="button"
                  onClick={() => selectPost(post)}
                  className={`block w-full border-b border-[#edf1f6] px-3 py-3 text-left transition-colors sm:px-4 lg:px-5 ${
                    active ? "bg-[#f6f9ff]" : "hover:bg-[#fafcff]"
                  }`}
                >
                  <div className="flex items-center justify-between gap-3">
                    <span className={`text-[11px] font-semibold ${post.status === "published" ? "text-[#2f6df6]" : "text-[#8492a8]"}`}>
                      {post.status === "published" ? "발행됨" : "임시저장"}
                    </span>
                    <time className="shrink-0 text-[11px] text-[#8b98ab]">{formatDate(post.publishedAt ?? post.updatedAt)}</time>
                  </div>
                  <p className="mt-1.5 truncate text-[13px] font-semibold tracking-[-0.03em] text-[#30425f]">{post.title}</p>
                  <p className="mt-1 truncate text-[11px] text-[#8391a6]">/blog/{post.slug}</p>
                </button>
              );
            })}
          </div>
        </aside>

        <section className="min-w-0">
          <div className="flex flex-wrap items-center justify-between gap-2 border-b border-[#edf1f6] px-3 py-3 sm:px-4 lg:px-5">
            <div className="flex items-center gap-2">
              <button type="button" onClick={() => setIsPreviewOpen(false)} className={`h-8 rounded-[9px] px-2.5 text-[12px] font-semibold transition-colors ${!isPreviewOpen ? "bg-[#edf4ff] text-[#2f6df6]" : "text-[#71819a] hover:text-[#2f6df6]"}`}>작성</button>
              <button type="button" onClick={() => setIsPreviewOpen(true)} className={`h-8 rounded-[9px] px-2.5 text-[12px] font-semibold transition-colors ${isPreviewOpen ? "bg-[#edf4ff] text-[#2f6df6]" : "text-[#71819a] hover:text-[#2f6df6]"}`}>미리보기</button>
              {published && draft.id ? (
                <a href={`/blog/${draft.slug}`} target="_blank" rel="noreferrer" className="ml-1 text-[12px] font-semibold text-[#70819d] hover:text-[#2f6df6]">공개 글 열기 ↗</a>
              ) : null}
            </div>
            <div className="flex items-center gap-2">
              {draft.id ? <button type="button" onClick={deletePost} disabled={saving} className="h-8 px-1 text-[12px] font-semibold text-[#8c9ab1] transition-colors hover:text-[#d24b63] disabled:cursor-not-allowed">삭제</button> : null}
              <button type="button" onClick={() => save("draft")} disabled={saving} className="om-btn-secondary h-8 rounded-[9px] px-3 text-[12px] shadow-none">{saving ? "저장 중..." : "임시저장"}</button>
              <button type="button" onClick={() => save("published")} disabled={saving} className="om-btn-primary h-8 rounded-[9px] px-3 text-[12px] shadow-none">{saving ? "저장 중..." : published ? "발행 내용 저장" : "발행하기"}</button>
            </div>
          </div>

          {isPreviewOpen ? (
            <div className="min-h-[620px] px-3 py-6 sm:px-4 lg:px-8 lg:py-9">
              <div className="mx-auto max-w-[820px]">
                <p className="text-[12px] font-semibold text-[#2f6df6]">미리보기</p>
                <h2 className="mt-3 text-[30px] font-semibold leading-[1.18] tracking-[-0.07em] text-[#16233c] sm:text-[42px]">{draft.title}</h2>
                <p className="mt-5 text-[16px] leading-8 text-[#667792]">{draft.seoDescription || draft.excerpt || "검색 결과에 표시할 설명을 입력하세요."}</p>
                <div className="mt-11 border-t border-[#e7edf7] pt-2"><MarkdownPreview content={draft.contentMarkdown} /></div>
              </div>
            </div>
          ) : (
            <div className="px-3 py-4 sm:px-4 lg:px-5">
              <div className="grid gap-x-8 gap-y-4 border-b border-[#edf1f6] pb-5 lg:grid-cols-2">
                <label className="block min-w-0"><span className="text-[12px] font-semibold text-[#7183a1]">글 제목</span><input value={draft.title} onChange={(event) => updateDraft("title", event.target.value)} className={editorFieldClass()} placeholder="검색어가 자연스럽게 들어간 제목" /></label>
                <label className="block min-w-0"><span className="text-[12px] font-semibold text-[#7183a1]">URL 슬러그</span><div className="flex items-center gap-1 border-b border-[#dfe7f3] focus-within:border-[#8eb5ff]"><span className="shrink-0 text-[13px] text-[#8b99ad]">/blog/</span><input value={draft.slug} onChange={(event) => updateDraft("slug", event.target.value.toLowerCase().replace(/\s+/g, "-"))} className="h-10 min-w-0 flex-1 bg-transparent text-[14px] text-[#1a2943] outline-none placeholder:text-[#9aa8bd]" placeholder="company-email-guide" /></div></label>
                <label className="block min-w-0 lg:col-span-2"><span className="text-[12px] font-semibold text-[#7183a1]">검색 설명</span><input value={draft.seoDescription} onChange={(event) => updateDraft("seoDescription", event.target.value)} className={editorFieldClass()} placeholder="검색 결과와 공유 카드에 보일 1~2문장 설명" /></label>
                <label className="block min-w-0 lg:col-span-2"><span className="text-[12px] font-semibold text-[#7183a1]">검색 키워드</span><input value={draft.keywordsText} onChange={(event) => updateDraft("keywordsText", event.target.value)} className={editorFieldClass()} placeholder="기업메일, 회사 이메일 주소 만들기, 도메인 메일" /></label>
              </div>

              <NotionBlogContentEditor value={draft.contentMarkdown} onChange={(value) => updateDraft("contentMarkdown", value)} />

              <label className="block border-t border-[#edf1f6] pt-4"><span className="text-[12px] font-semibold text-[#7183a1]">목록 요약</span><textarea value={draft.excerpt} onChange={(event) => updateDraft("excerpt", event.target.value)} className="mt-2 min-h-20 w-full resize-y border-b border-[#dfe7f3] bg-transparent py-2 text-[14px] leading-6 text-[#33445f] outline-none placeholder:text-[#9aa8bd] focus:border-[#8eb5ff]" placeholder="비워두면 본문에서 자동으로 요약합니다." /></label>
            </div>
          )}
        </section>
      </div>

      {toast ? <BottomToast notice={toast} onClose={() => setToast(null)} /> : null}
    </div>
  );
}
