import React, { useState, useEffect } from "react";
import { Link, useParams } from "react-router-dom";
import { useLanguage } from "../context/LanguageContext";
import { BlogPost, blogService } from "../services/blog.service";
import { format } from "date-fns";
import { tr } from "date-fns/locale";

interface PostData {
  image?: string;
  author?: {
    id: string;
    name: string;
    avatar?: string;
  };
}

const BlogDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const { language, setLanguage, t } = useLanguage();
  const [blogPost, setBlogPost] = useState<BlogPost | null>(null);
  const [postData, setPostData] = useState<PostData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchBlogPost = async () => {
      setLoading(true);
      setError(null);
      try {
        if (id) {
          const response = await blogService.getPostBySlug(id);
          setBlogPost(response);
          setPostData({
            image: response.coverImage,
            author: response.author,
          });
        } else {
          setError("Blog post ID is missing.");
        }
      } catch (error: any) {
        setError(error.message || "Failed to fetch blog post.");
      } finally {
        setLoading(false);
      }
    };

    fetchBlogPost();
  }, [id]);

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <h1 className="text-2xl font-bold text-gray-900">Loading...</h1>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <h1 className="text-2xl font-bold text-gray-900">Error: {error}</h1>
      </div>
    );
  }

  if (!blogPost || !postData) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <h1 className="text-2xl font-bold text-gray-900">
          {t("blog.notFound")}
        </h1>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 pt-32 pb-16">
      <div className="container mx-auto px-4">
        <Link
          to="/blog"
          className="text-blue-600 hover:underline mb-4 inline-block"
        >
          &larr; {t("blog.backToBlog")}
        </Link>
        {postData.image && (
          <img
            src={postData.image}
            alt={t(blogPost.title)}
            className="w-full h-96 object-cover rounded-lg mb-8"
          />
        )}
        <h1 className="text-4xl font-bold text-gray-900 mb-6">
          {t(blogPost.title)}
        </h1>
        <div className="flex items-center text-sm text-gray-500 space-x-4 mb-8">
          <div className="flex items-center">
            <span>{postData.author?.name}</span>
          </div>
          <div className="flex items-center">
            {blogPost.publishedAt &&
              format(new Date(blogPost.publishedAt), "dd MMM yyyy", {
                locale: tr,
              })}
          </div>
        </div>
        <div className="prose max-w-none text-gray-800" dangerouslySetInnerHTML={{ __html: language == "tr" ? t(blogPost.contentTr!!) : t(blogPost.contentEn!!) }} />
      </div>
    </div>
  );
};

export default BlogDetail;
