"use client";

import { useEffect, useState } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import rehypeRaw from "rehype-raw";

export function HelpArticleContent({
  content,
  slug,
}: {
  content: string;
  slug: string;
}) {
  const [feedbackSent, setFeedbackSent] = useState(false);
  const [feedbackValue, setFeedbackValue] = useState<boolean | null>(null);

  // Increment view count on mount
  useEffect(() => {
    fetch(`/api/help/${slug}/views`, { method: "POST" }).catch(() => {});
  }, [slug]);

  async function handleFeedback(helpful: boolean) {
    if (feedbackSent) return;
    setFeedbackSent(true);
    setFeedbackValue(helpful);
    try {
      await fetch(`/api/help/${slug}/feedback`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ helpful }),
      });
    } catch {
      // Silently fail - feedback is best-effort
    }
  }

  return (
    <>
      {/* Article Content */}
      <div
        className="prose prose-lg prose-invert prose-pink max-w-none
          prose-headings:text-text prose-headings:font-bold prose-headings:scroll-mt-20
          prose-h2:mt-10 prose-h2:mb-4 prose-h3:mt-8 prose-h3:mb-3
          prose-p:text-text-muted prose-p:leading-relaxed prose-p:mb-5
          prose-a:text-primary prose-a:no-underline hover:prose-a:underline
          prose-strong:text-text
          prose-code:text-primary prose-code:bg-surface-light prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-sm
          prose-pre:bg-surface-light prose-pre:rounded-lg
          prose-blockquote:border-primary prose-blockquote:text-text-muted prose-blockquote:my-6
          prose-img:rounded-lg prose-img:my-6
          prose-ul:my-4 prose-ol:my-4 prose-li:text-text-muted prose-li:mb-2
          prose-table:text-text-muted
          prose-th:text-text prose-th:border-surface-light
          prose-td:border-surface-light
          prose-hr:my-8 prose-hr:border-surface-light"
      >
        <ReactMarkdown
          remarkPlugins={[remarkGfm]}
          rehypePlugins={[rehypeRaw]}
          components={{
            h2: ({ children, ...props }) => {
              const text = typeof children === "string" ? children : String(children);
              const id = text
                .toLowerCase()
                .replace(/[^a-z0-9]+/g, "-")
                .replace(/(^-|-$)/g, "");
              return (
                <h2 id={id} {...props}>
                  {children}
                </h2>
              );
            },
            h3: ({ children, ...props }) => {
              const text = typeof children === "string" ? children : String(children);
              const id = text
                .toLowerCase()
                .replace(/[^a-z0-9]+/g, "-")
                .replace(/(^-|-$)/g, "");
              return (
                <h3 id={id} {...props}>
                  {children}
                </h3>
              );
            },
          }}
        >
          {content}
        </ReactMarkdown>
      </div>

      {/* Was this helpful? */}
      <div className="mt-10 border-t border-surface-light pt-8">
        <div className="bg-surface rounded-lg p-6 text-center">
          <p className="font-semibold mb-3">Was this article helpful?</p>
          {feedbackSent ? (
            <p className="text-text-muted text-sm">
              {feedbackValue
                ? "Thanks for your feedback! Glad we could help."
                : "Thanks for letting us know. We'll work on improving this article."}
            </p>
          ) : (
            <div className="flex justify-center gap-4">
              <button
                onClick={() => handleFeedback(true)}
                className="flex items-center gap-2 bg-green-500/20 text-green-400 hover:bg-green-500/30 px-5 py-2.5 rounded-lg transition-colors text-sm font-medium"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14 10h4.764a2 2 0 011.789 2.894l-3.5 7A2 2 0 0115.263 21h-4.017c-.163 0-.326-.02-.485-.06L7 20m7-10V5a2 2 0 00-2-2h-.095c-.5 0-.905.405-.905.905 0 .714-.211 1.412-.608 2.006L7 11v9m7-10h-2M7 20H5a2 2 0 01-2-2v-6a2 2 0 012-2h2.5" />
                </svg>
                Yes, helpful
              </button>
              <button
                onClick={() => handleFeedback(false)}
                className="flex items-center gap-2 bg-red-500/20 text-red-400 hover:bg-red-500/30 px-5 py-2.5 rounded-lg transition-colors text-sm font-medium"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 14H5.236a2 2 0 01-1.789-2.894l3.5-7A2 2 0 018.736 3h4.018a2 2 0 01.485.06l3.76.94m-7 10v5a2 2 0 002 2h.096c.5 0 .905-.405.905-.904 0-.715.211-1.413.608-2.008L17 13V4m-7 10h2m5-10h2a2 2 0 012 2v6a2 2 0 01-2 2h-2.5" />
                </svg>
                Not helpful
              </button>
            </div>
          )}
        </div>
      </div>
    </>
  );
}
