// frontend/src/pages/Admin.tsx
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import rehypeRaw from "rehype-raw";

interface Post {
  id: number;
  title: string;
  content: string;
  published: boolean;
  created_at: string;
}

function Admin() {
  const [posts, setPosts] = useState<Post[]>([]);
  const [selectedPost, setSelectedPost] = useState<Post | null>(null);
  const [title, setTitle] = useState("");
  const [content, setContent] = useState("");
  const [published, setPublished] = useState(false);
  const [showPreview, setShowPreview] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const navigate = useNavigate();

  useEffect(() => {
    checkAuth();
    fetchPosts();
  }, []);

  const checkAuth = async () => {
    const token = localStorage.getItem("auth_token");
    if (!token) {
      navigate("/login");
      return;
    }

    try {
      const response = await fetch("/api/v1/session", {
        headers: { Authorization: `Bearer ${token}` },
      });

      if (!response.ok) {
        localStorage.removeItem("auth_token");
        navigate("/login");
      }
    } catch (error) {
      console.error("Auth check failed:", error);
      navigate("/login");
    }
  };

  const fetchPosts = async () => {
    const token = localStorage.getItem("auth_token");

    try {
      const response = await fetch("/api/v1/admin/posts", {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });

      if (response.ok) {
        const data = await response.json();
        setPosts(data.data || []);
      } else if (response.status === 401) {
        localStorage.removeItem("auth_token");
        navigate("/login");
      }
    } catch (error) {
      console.error("Failed to fetch posts:", error);
    }
  };

  const handleCreate = async () => {
    if (!title.trim() || !content.trim()) {
      alert("Title and content are required");
      return;
    }

    setIsLoading(true);
    const token = localStorage.getItem("auth_token");

    try {
      const response = await fetch("/api/v1/posts/", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          title,
          content,
          published,
        }),
      });

      if (response.ok) {
        setTitle("");
        setContent("");
        setPublished(false);
        setSelectedPost(null);
        fetchPosts();
        alert("Post created successfully!");
      } else {
        const error = await response.text();
        alert("Failed to create post: " + error);
      }
    } catch (error) {
      console.error("Failed to create post:", error);
      alert("Network error");
    } finally {
      setIsLoading(false);
    }
  };

  const handleUpdate = async () => {
    if (!selectedPost || !title.trim() || !content.trim()) {
      alert("Title and content are required");
      return;
    }

    setIsLoading(true);
    const token = localStorage.getItem("auth_token");

    try {
      const response = await fetch(`/api/v1/posts/${selectedPost.id}`, {
        method: "PUT",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          title,
          content,
          published,
        }),
      });

      if (response.ok) {
        setTitle("");
        setContent("");
        setPublished(false);
        setSelectedPost(null);
        fetchPosts();
        alert("Post updated successfully!");
      } else {
        const error = await response.text();
        alert("Failed to update post: " + error);
      }
    } catch (error) {
      console.error("Failed to update post:", error);
      alert("Network error");
    } finally {
      setIsLoading(false);
    }
  };

  const handleDelete = async (id: number) => {
    if (!confirm("Delete this post? This action cannot be undone.")) return;

    const token = localStorage.getItem("auth_token");

    try {
      const response = await fetch(`/api/v1/posts/${id}`, {
        method: "DELETE",
        headers: { Authorization: `Bearer ${token}` },
      });

      if (response.ok) {
        fetchPosts();
        if (selectedPost?.id === id) {
          setSelectedPost(null);
          setTitle("");
          setContent("");
          setPublished(false);
        }
        alert("Post deleted successfully!");
      } else {
        alert("Failed to delete post");
      }
    } catch (error) {
      console.error("Failed to delete post:", error);
      alert("Network error");
    }
  };

  const selectPost = (post: Post) => {
    setSelectedPost(post);
    setTitle(post.title);
    setContent(post.content);
    setPublished(post.published);
    setShowPreview(false);
  };

  const clearForm = () => {
    setSelectedPost(null);
    setTitle("");
    setContent("");
    setPublished(false);
    setShowPreview(false);
  };

  // Markdown shortcut helpers
  const insertMarkdown = (syntax: string, placeholder: string = "") => {
    const textarea = document.querySelector("textarea");
    if (!textarea) return;

    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const selectedText = content.substring(start, end) || placeholder;
    const beforeText = content.substring(0, start);
    const afterText = content.substring(end);

    let newText = "";
    let cursorPosition = start;

    if (syntax === "link") {
      newText = `${beforeText}[${selectedText}](url)${afterText}`;
      cursorPosition = start + selectedText.length + 3;
    } else if (syntax === "image") {
      newText = `${beforeText}![${selectedText}](image-url)${afterText}`;
      cursorPosition = start + selectedText.length + 4;
    } else if (syntax === "code") {
      newText = `${beforeText}\`\`\`\n${selectedText}\n\`\`\`${afterText}`;
      cursorPosition = start + 4;
    } else if (syntax === "bold") {
      newText = `${beforeText}**${selectedText}**${afterText}`;
      cursorPosition = start + 2 + selectedText.length;
    } else if (syntax === "italic") {
      newText = `${beforeText}*${selectedText}*${afterText}`;
      cursorPosition = start + 1 + selectedText.length;
    } else if (syntax === "h1") {
      newText = `${beforeText}# ${selectedText}${afterText}`;
      cursorPosition = start + 2 + selectedText.length;
    } else if (syntax === "h2") {
      newText = `${beforeText}## ${selectedText}${afterText}`;
      cursorPosition = start + 3 + selectedText.length;
    } else if (syntax === "list") {
      newText = `${beforeText}- ${selectedText}${afterText}`;
      cursorPosition = start + 2 + selectedText.length;
    }

    setContent(newText);
    setTimeout(() => {
      textarea.focus();
      textarea.setSelectionRange(cursorPosition, cursorPosition);
    }, 0);
  };

  return (
    <div className="min-h-screen bg-black text-white font-['Commit_Mono',monospace]">
      <div className="max-w-[2000px] mx-auto px-2 sm:px-4">
        {/* Header */}
        <div className="pt-6 pb-4 border-b border-gray-800">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-xl sm:text-2xl font-bold text-[hsl(270,73%,63%)]">
                Admin Panel
              </h1>
              <p className="text-gray-500 text-xs sm:text-sm mt-1">
                Blog Editor
              </p>
            </div>
            <div className="flex gap-2 sm:gap-3">
              <button
                onClick={() => navigate("/admin/upload")}
                className="px-3 py-1.5 sm:px-4 sm:py-2 border border-gray-700 rounded hover:border-[hsl(270,73%,63%)] transition-colors text-xs sm:text-sm"
              >
                Upload
              </button>
              <button
                onClick={() => {
                  localStorage.removeItem("auth_token");
                  navigate("/");
                }}
                className="px-3 py-1.5 sm:px-4 sm:py-2 border border-gray-700 rounded hover:border-red-500 hover:text-red-500 transition-colors text-xs sm:text-sm"
              >
                Logout
              </button>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-12 gap-3 sm:gap-4 mt-4">
          {/* Sidebar - Posts List - Адаптивная ширина */}
          <div className="col-span-12 xl:col-span-2">
            <div className="xl:sticky xl:top-6">
              <div className="flex items-center justify-between mb-3">
                <h2 className="text-base sm:text-lg font-semibold">
                  Posts ({posts.length})
                </h2>
                <button
                  onClick={clearForm}
                  className="px-2 py-1 sm:px-3 sm:py-1 bg-[hsl(270,73%,63%)] text-white rounded text-xs sm:text-sm hover:bg-[hsl(270,73%,70%)] transition-colors"
                >
                  + New
                </button>
              </div>

              <div className="space-y-2 max-h-[300px] xl:max-h-[calc(100vh-200px)] overflow-y-auto custom-scrollbar">
                {posts.map((post) => (
                  <div
                    key={post.id}
                    onClick={() => selectPost(post)}
                    className={`p-2 sm:p-3 rounded border cursor-pointer transition-all ${
                      selectedPost?.id === post.id
                        ? "border-[hsl(270,73%,63%)] bg-[hsl(270,73%,63%)]/10"
                        : "border-gray-800 hover:border-gray-700"
                    }`}
                  >
                    <div className="flex items-start justify-between mb-1">
                      <h3 className="font-medium text-xs sm:text-sm truncate flex-1">
                        {post.title}
                      </h3>
                      <div className="flex items-center gap-1 sm:gap-2">
                        {post.published ? (
                          <span
                            className="text-xs text-green-500"
                            title="Published"
                          >
                            ✓
                          </span>
                        ) : (
                          <span className="text-xs text-gray-600" title="Draft">
                            ○
                          </span>
                        )}
                        <span className="text-xs text-gray-500">
                          #{post.id}
                        </span>
                      </div>
                    </div>
                    <p className="text-xs text-gray-500 line-clamp-2 hidden sm:block">
                      {post.content.substring(0, 60)}...
                    </p>
                    <div className="flex items-center justify-between mt-1 sm:mt-2">
                      <span className="text-xs text-gray-600">
                        {new Date(post.created_at).toLocaleDateString()}
                      </span>
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          handleDelete(post.id);
                        }}
                        className="text-xs text-red-500 hover:text-red-400"
                      >
                        Del
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Main Editor - Увеличенная рабочая область */}
          <div className="col-span-12 xl:col-span-10">
            <div className="bg-black border border-gray-800 rounded-lg">
              {/* Toolbar */}
              <div className="border-b border-gray-800 p-2 sm:p-3 flex items-center justify-between flex-wrap gap-2">
                <div className="flex items-center gap-1 sm:gap-2 flex-wrap">
                  <button
                    onClick={() => insertMarkdown("bold", "bold text")}
                    className="p-1.5 sm:p-2 hover:bg-gray-900 rounded transition-colors text-xs sm:text-sm"
                    title="Bold"
                  >
                    <strong>B</strong>
                  </button>
                  <button
                    onClick={() => insertMarkdown("italic", "italic text")}
                    className="p-1.5 sm:p-2 hover:bg-gray-900 rounded transition-colors text-xs sm:text-sm"
                    title="Italic"
                  >
                    <em>I</em>
                  </button>
                  <div className="w-px h-4 sm:h-6 bg-gray-800"></div>
                  <button
                    onClick={() => insertMarkdown("h1", "Heading 1")}
                    className="p-1.5 sm:p-2 hover:bg-gray-900 rounded transition-colors text-xs sm:text-sm"
                    title="H1"
                  >
                    H1
                  </button>
                  <button
                    onClick={() => insertMarkdown("h2", "Heading 2")}
                    className="p-1.5 sm:p-2 hover:bg-gray-900 rounded transition-colors text-xs sm:text-sm"
                    title="H2"
                  >
                    H2
                  </button>
                  <div className="w-px h-4 sm:h-6 bg-gray-800"></div>
                  <button
                    onClick={() => insertMarkdown("link", "link text")}
                    className="p-1.5 sm:p-2 hover:bg-gray-900 rounded transition-colors text-xs sm:text-sm"
                    title="Link"
                  >
                    🔗
                  </button>
                  <button
                    onClick={() => insertMarkdown("image", "alt text")}
                    className="p-1.5 sm:p-2 hover:bg-gray-900 rounded transition-colors text-xs sm:text-sm"
                    title="Image"
                  >
                    🖼️
                  </button>
                  <button
                    onClick={() => insertMarkdown("code", "code")}
                    className="p-1.5 sm:p-2 hover:bg-gray-900 rounded transition-colors text-xs sm:text-sm"
                    title="Code"
                  >
                    &lt;/&gt;
                  </button>
                  <button
                    onClick={() => insertMarkdown("list", "list item")}
                    className="p-1.5 sm:p-2 hover:bg-gray-900 rounded transition-colors text-xs sm:text-sm"
                    title="List"
                  >
                    •
                  </button>
                </div>

                <button
                  onClick={() => setShowPreview(!showPreview)}
                  className={`px-3 py-1.5 sm:px-4 sm:py-2 rounded text-xs sm:text-sm transition-colors ${
                    showPreview
                      ? "bg-[hsl(270,73%,63%)] text-white"
                      : "border border-gray-700 hover:border-gray-600"
                  }`}
                >
                  {showPreview ? "📝 Editor" : "👁️ Preview"}
                </button>
              </div>

              {/* Content Area */}
              <div className="p-3 sm:p-4 md:p-6">
                {!showPreview ? (
                  <>
                    <input
                      type="text"
                      placeholder="Post title..."
                      value={title}
                      onChange={(e) => setTitle(e.target.value)}
                      className="w-full bg-transparent border-none outline-none text-2xl sm:text-3xl font-bold mb-4 sm:mb-6 placeholder-gray-700"
                    />

                    {/* Чекбокс Published */}
                    <div className="mb-4 sm:mb-6 flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3">
                      <label className="flex items-center gap-2 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={published}
                          onChange={(e) => setPublished(e.target.checked)}
                          className="w-4 h-4 sm:w-5 sm:h-5 rounded border-gray-700 bg-transparent text-[hsl(270,73%,63%)] focus:ring-[hsl(270,73%,63%)] focus:ring-offset-0 cursor-pointer"
                        />
                        <span className="text-xs sm:text-sm">
                          Publish this post
                        </span>
                      </label>
                      <span className="text-xs text-gray-600">
                        {published
                          ? "(Visible to everyone)"
                          : "(Draft - only admins)"}
                      </span>
                    </div>

                    <textarea
                      placeholder="Write your post content in Markdown...

Examples:
# Heading
**bold** *italic*
[link](url)
![image](url)
\`\`\`code\`\`\`
"
                      value={content}
                      onChange={(e) => setContent(e.target.value)}
                      className="w-full h-[400px] sm:h-[500px] md:h-[600px] lg:h-[700px] bg-transparent border border-gray-800 rounded p-3 sm:p-4 outline-none focus:border-gray-700 transition-colors resize-none font-mono text-xs sm:text-sm"
                    />
                  </>
                ) : (
                  <div className="prose prose-invert prose-sm sm:prose-lg max-w-none">
                    <h1 className="text-3xl sm:text-4xl font-bold mb-4 sm:mb-6 text-[hsl(270,73%,63%)]">
                      {title || "Untitled Post"}
                    </h1>
                    <div className="mb-4 sm:mb-6 text-xs sm:text-sm">
                      {published ? (
                        <span className="text-green-500">✓ Published</span>
                      ) : (
                        <span className="text-yellow-500">○ Draft</span>
                      )}
                    </div>
                    <div className="markdown-content">
                      <ReactMarkdown
                        remarkPlugins={[remarkGfm]}
                        rehypePlugins={[rehypeRaw]}
                      >
                        {content || "*No content yet...*"}
                      </ReactMarkdown>
                    </div>
                  </div>
                )}
              </div>

              {/* Actions */}
              <div className="border-t border-gray-800 p-3 sm:p-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
                <div className="text-xs sm:text-sm text-gray-500">
                  {selectedPost
                    ? `Editing post #${selectedPost.id}`
                    : "Creating new post"}
                </div>
                <div className="flex gap-2 sm:gap-3 w-full sm:w-auto">
                  {selectedPost && (
                    <button
                      onClick={clearForm}
                      className="flex-1 sm:flex-none px-3 py-1.5 sm:px-4 sm:py-2 border border-gray-700 rounded hover:border-gray-600 transition-colors text-xs sm:text-sm"
                    >
                      Cancel
                    </button>
                  )}
                  <button
                    onClick={selectedPost ? handleUpdate : handleCreate}
                    disabled={isLoading || !title.trim() || !content.trim()}
                    className="flex-1 sm:flex-none px-4 py-1.5 sm:px-6 sm:py-2 bg-[hsl(270,73%,63%)] text-white rounded hover:bg-[hsl(270,73%,70%)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed text-xs sm:text-sm font-medium"
                  >
                    {isLoading
                      ? "Saving..."
                      : selectedPost
                        ? "Update"
                        : published
                          ? "Publish"
                          : "Save Draft"}
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <style>{`
        .custom-scrollbar::-webkit-scrollbar {
          width: 6px;
        }
        .custom-scrollbar::-webkit-scrollbar-track {
          background: #111;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb {
          background: #333;
          border-radius: 4px;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover {
          background: #444;
        }
      `}</style>
    </div>
  );
}

export default Admin;
