// frontend/src/pages/BlogPost.tsx
import { useState, useEffect, useCallback } from "react";
import { useParams, useNavigate } from "react-router-dom";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { oneDark as theme } from "react-syntax-highlighter/dist/esm/styles/prism";

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

function BlogPost() {
  const { id } = useParams<{ id: string }>();
  const [post, setPost] = useState<Post | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const navigate = useNavigate();

  useEffect(() => {
    if (id) {
      fetchPost(id);
    }
  }, [id]);

  const fetchPost = async (postId: string) => {
    try {
      const response = await fetch(`/api/v1/posts/${postId}`);
      if (response.ok) {
        const data = await response.json();
        setPost(data.data || data);
      } else {
        navigate("/blog");
      }
    } catch (error) {
      console.error("Failed to fetch post:", error);
      navigate("/blog");
    } finally {
      setIsLoading(false);
    }
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });
  };

  const copyCode = useCallback((code: string) => {
    navigator.clipboard.writeText(code);
  }, []);

  if (isLoading) {
    return (
      <div className="min-h-screen bg-black flex items-center justify-center">
        <div className="text-[hsl(270,73%,63%)] text-xl font-['Commit_Mono',monospace]">
          Loading...
        </div>
      </div>
    );
  }

  if (!post) {
    return (
      <div className="min-h-screen bg-black flex items-center justify-center">
        <div className="text-gray-500 text-xl font-['Commit_Mono',monospace]">
          Post not found
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-black text-white font-['Commit_Mono',monospace]">
      <div className="max-w-[900px] mx-auto px-4 sm:px-6 py-12 sm:py-16">
        <button
          onClick={() => navigate("/blog")}
          className="flex items-center gap-2 text-gray-400 hover:text-[hsl(270,73%,63%)] transition-colors mb-8 text-sm sm:text-base"
        >
          <svg
            className="w-4 h-4"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M15 19l-7-7 7-7"
            />
          </svg>
          Back to blog page
        </button>

        <article>
          <header className="mb-8 sm:mb-12">
            <h1 className="text-3xl sm:text-4xl md:text-5xl font-bold text-[hsl(270,73%,63%)] mb-4 leading-tight">
              {post.title}
            </h1>
            <div className="flex items-center gap-4 text-sm text-gray-500">
              <time dateTime={post.created_at}>
                {formatDate(post.created_at)}
              </time>
              <span>•</span>
              <span>{Math.ceil(post.content.length / 1000)} min reading</span>
            </div>
          </header>

          <div className="blog-content">
            <ReactMarkdown
              remarkPlugins={[remarkGfm]}
              components={{
                code(props) {
                  const { children, className, ...rest } = props;
                  const match = /language-(\w+)/.exec(className || "");
                  const language = match ? match[1] : "text";

                  if (!match) {
                    return (
                      <code {...rest} className="inline-code">
                        {children}
                      </code>
                    );
                  }

                  return (
                    <div className="code-container">
                      <button
                        onClick={() =>
                          copyCode(String(children).replace(/\n$/, ""))
                        }
                        className="copy-button"
                        title="Copy code"
                      >
                        <span>Copy</span>
                      </button>
                      <SyntaxHighlighter
                        style={theme}
                        language={language}
                        PreTag="div"
                        customStyle={{
                          background: "rgb(12, 12, 22)",
                          margin: 0,
                          padding: "1.75rem 1.5rem 1.5rem",
                          borderRadius: "0 0 12px 12px",
                          fontSize: "0.875rem",
                          lineHeight: "1.65",
                        }}
                      >
                        {String(children).replace(/\n$/, "")}
                      </SyntaxHighlighter>
                    </div>
                  );
                },
                strong: ({ children }) => (
                  <strong className="text-white font-bold">{children}</strong>
                ),
                em: ({ children }) => (
                  <em className="text-white italic">{children}</em>
                ),
              }}
            >
              {post.content}
            </ReactMarkdown>
          </div>
        </article>
      </div>

      <style>{`
        .blog-content {
          color: #ffffff !important;
          line-height: 1.8;
        }

        .blog-content p {
          color: #ffffff !important;
          margin-bottom: 1.5em;
        }

        .blog-content strong {
          color: #ffffff !important;
          font-weight: 700 !important;
        }

        .blog-content ul, .blog-content ol {
          color: #ffffff !important;
          padding-left: 1.5em;
        }

        .blog-content li {
          color: #ffffff !important;
        }

        /* Inline код */
        .inline-code {
          color: #ffffff !important;
          background: rgba(255,255,255,0.1) !important;
          padding: 0.2em 0.4em !important;
          border-radius: 6px !important;
          font-size: 0.875em !important;
          font-family: 'Commit_Mono', monospace !important;
        }

        /* Контейнер кода */
        .code-container {
          position: relative;
          margin: 2em 0;
          border-radius: 12px;
          overflow: hidden;
          background: linear-gradient(145deg, rgb(8,8,18) 0%, rgb(18,18,32) 100%);
          border: 1px solid rgba(255,255,255,0.06);
          box-shadow: 0 12px 40px rgba(0,0,0,0.5);
        }

        /* Анимированная кнопка */
        .copy-button {
          position: absolute;
          top: 14px;
          right: 14px;
          z-index: 20;
          background: linear-gradient(135deg, rgba(117,43,255,0.25) 0%, rgba(117,43,255,0.15) 100%);
          border: 1px solid rgba(117,43,255,0.5);
          color: #ffffff;
          padding: 8px 16px;
          border-radius: 8px;
          font-size: 13px;
          font-weight: 500;
          cursor: pointer;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          font-family: 'Commit_Mono', monospace;
          backdrop-filter: blur(20px);
          box-shadow: 0 4px 16px rgba(117,43,255,0.25);
        }

        .copy-button:hover {
          background: linear-gradient(135deg, hsl(270,73%,65%) 0%, hsl(270,73%,55%) 100%);
          transform: translateY(-3px) scale(1.03);
          box-shadow: 0 12px 30px rgba(117,43,255,0.45);
          border-color: hsl(270,73%,75%);
        }

        .copy-button:active {
          transform: translateY(-1px) scale(0.98);
          transition: all 0.1s;
        }

        /* Заголовки */
        .blog-content h1, .blog-content h2, .blog-content h3 {
          color: hsl(270, 73%, 63%) !important;
          margin-top: 2em;
          margin-bottom: 0.75em;
        }

        .blog-content a {
          color: hsl(270, 73%, 63%) !important;
        }

        /* Responsive */
        @media (max-width: 640px) {
          .code-container {
            margin: 1.5em -1rem;
            border-radius: 0;
            border-left: none;
            border-right: none;
          }
          .copy-button {
            top: 10px;
            right: 10px;
            padding: 6px 12px;
            font-size: 12px;
          }
        }
      `}</style>
    </div>
  );
}

export default BlogPost;
