import { useParams, Link } from "react-router-dom";
import { useEffect, useState } from "react";
import { BlogHeader } from "@/components/BlogHeader";
import { BlogFooter } from "@/components/BlogFooter";
import { PromoBanner } from "@/components/PromoBanner";
import { SEOHead } from "@/components/SEOHead";
import { ShareButtons } from "@/components/ShareButtons";
import { ReadingProgress } from "@/components/ReadingProgress";
import { TableOfContents } from "@/components/TableOfContents";
import { InternalLinks } from "@/components/InternalLinks";
import { NoomiiResourceLinks } from "@/components/NoomiiResourceLinks";
import { SEOEnhancedImage } from "@/components/SEOEnhancedImage";
import { AdvancedSchema } from "@/components/AdvancedSchema";
import { FAQSection } from "@/components/FAQSection";
import { SocialShareEnhanced } from "@/components/SocialShareEnhanced";
import { LanguageSelector } from "@/components/LanguageSelector";
import { supabase } from "@/integrations/supabase/client";
import { ChevronRight, Clock, Eye, Calendar } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Card } from "@/components/ui/card";
import DOMPurify from "dompurify";
import { enhanceContentLinks } from "@/lib/contentLinks";

const categoryLabels: Record<string, string> = {
  "life-coaching": "Life Coaching",
  "corporate-coaching": "Corporate Coaching",
  "business-coaching": "Business Coaching",
  "adhd-coaching": "ADHD Coaching",
  "executive-leadership-coaching": "Executive & Leadership",
  "health-wellness-coaching": "Health & Wellness",
  "spirituality-coaching": "Spirituality",
  "retirement-coaching": "Retirement",
  "relationship-coaching": "Relationship Coaching",
  "recovery-coaching": "Recovery Coaching",
};

const BlogPost = () => {
  const { slug } = useParams<{ slug: string }>();
  const [post, setPost] = useState<any>(null);
  const [authorBio, setAuthorBio] = useState<string>("");
  const [authorProfile, setAuthorProfile] = useState<any>(null);
  const [relatedPosts, setRelatedPosts] = useState<any[]>([]);
  const [localeVariants, setLocaleVariants] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchPost = async () => {
      setLoading(true);
      
      // Fetch the post (exclude created_by for security)
      const { data: postData, error: postError } = await supabase
        .from("blog_posts")
        .select("id, title, slug, excerpt, content, category, author_name, author_avatar, author_profile_url, publish_date, read_time, image, views, meta_title, meta_description, faq_schema, keywords, created_by, updated_at, locale, alternate_locales, target_markets")
        .eq("slug", slug)
        .eq("is_published", true)
        .single();

      if (postError) {
        if (import.meta.env.DEV) {
          console.error("Error fetching post:", postError);
        }
        setPost(null);
      } else if (postData) {
        setPost(postData);
        
        // Get locale variants for hreflang tags
        const { data: variants } = await supabase.rpc('get_post_locale_variants', {
          post_slug: slug,
          post_locale: postData.locale || 'en-us'
        });
        
        if (variants) {
          setLocaleVariants(variants);
        }

        // Fetch author profile with all credentials
        const { data: profileData } = await supabase
          .from("profiles")
          .select("author_bio, job_title, credentials, education, years_experience, certifications, awards, published_works, specializations")
          .eq("id", postData.created_by)
          .single();

        if (profileData) {
          setAuthorBio(profileData.author_bio || "");
          setAuthorProfile(profileData);
        }

        // Increment view count
        await supabase
          .from("blog_posts")
          .update({ views: postData.views + 1 })
          .eq("id", postData.id);

        // Fetch related posts (exclude created_by for security)
        const { data: relatedData } = await supabase
          .from("blog_posts")
          .select("id, title, slug, excerpt, image")
          .eq("category", postData.category)
          .eq("is_published", true)
          .neq("id", postData.id)
          .order("publish_date", { ascending: false })
          .limit(2);

        if (relatedData) {
          setRelatedPosts(relatedData);
        }
      }

      setLoading(false);
      window.scrollTo(0, 0);
    };

    if (slug) {
      fetchPost();
    }
  }, [slug]);

  if (loading) {
    return (
      <div className="min-h-screen bg-background">
        <BlogHeader />
        <div className="container mx-auto px-4 py-16 text-center">
          <p className="text-muted-foreground">Loading...</p>
        </div>
      </div>
    );
  }

  if (!post) {
    return (
      <div className="min-h-screen bg-background">
        <BlogHeader />
        <div className="container mx-auto px-4 py-16 text-center">
          <h1 className="text-4xl font-bold mb-4">Post Not Found</h1>
          <Link to="/" className="text-primary hover:underline">
            Return to Blog Home
          </Link>
        </div>
      </div>
    );
  }

  const publishDate = new Date(post.publish_date).toLocaleDateString("en-US", {
    year: "numeric",
    month: "long",
    day: "numeric",
  });

  const publishDateISO = new Date(post.publish_date).toISOString();
  const modifiedDateISO = post.updated_at ? new Date(post.updated_at).toISOString() : publishDateISO;
  
  // Generate comprehensive keywords for SEO
  const seoKeywords = [
    ...(post.keywords || []),
    categoryLabels[post.category],
    "coaching",
    "professional development",
    "personal growth",
    `${categoryLabels[post.category]} coach`,
    "coaching tips",
    "coaching strategies"
  ];

  // Helper to extract plain text from HTML
  const extractTextFromHtml = (html: string): string => {
    const doc = new DOMParser().parseFromString(html, 'text/html');
    return doc.body.textContent || '';
  };

  const articleBody = extractTextFromHtml(post.content || post.excerpt);
  const wordCount = articleBody.split(/\s+/).filter(word => word.length > 0).length;

  // Enhanced BlogPosting Schema with Article Body + Interaction Statistics
  const structuredData = {
    "@context": "https://schema.org",
    "@type": "BlogPosting",
    headline: post.title,
    abstract: post.excerpt,
    articleBody: articleBody.substring(0, 5000), // Include first 5000 chars for LLM context
    image: {
      "@type": "ImageObject",
      url: post.image,
      width: 1200,
      height: 630,
      caption: post.title,
      representativeOfPage: true,
    },
    author: {
      "@type": "Person",
      name: post.author_name,
      url: post.author_profile_url,
      image: {
        "@type": "ImageObject",
        url: post.author_avatar,
        caption: `${post.author_name} - Professional Coach`,
      },
      jobTitle: authorProfile?.job_title || "Professional Coach",
      description: authorBio || `Professional ${categoryLabels[post.category]} expert`,
      knowsAbout: authorProfile?.specializations?.length > 0 
        ? authorProfile.specializations 
        : [categoryLabels[post.category], "Coaching", "Professional Development"],
      ...(authorProfile?.credentials && authorProfile.credentials.length > 0 && {
        hasCredential: authorProfile.credentials.map((cred: string) => ({
          "@type": "EducationalOccupationalCredential",
          credentialCategory: "Professional Certification",
          name: cred,
        })),
      }),
      ...(authorProfile?.education && authorProfile.education.length > 0 && {
        alumniOf: authorProfile.education.map((edu: string) => ({
          "@type": "EducationalOrganization",
          name: edu,
        })),
      }),
      ...(authorProfile?.awards && authorProfile.awards.length > 0 && {
        award: authorProfile.awards,
      }),
      ...(authorProfile?.published_works && authorProfile.published_works.length > 0 && {
        workExample: authorProfile.published_works.map((work: string) => ({
          "@type": "CreativeWork",
          name: work,
        })),
      }),
      affiliation: {
        "@type": "Organization",
        name: "Noomii",
        url: "https://www.noomii.com",
      },
      sameAs: [
        post.author_profile_url,
        "https://www.noomii.com"
      ].filter(Boolean),
    },
    publisher: {
      "@type": "Organization",
      name: "Noomii",
      url: "https://www.noomii.com",
      logo: {
        "@type": "ImageObject",
        url: "https://blog.noomii.com/noomii-logo.png",
        width: 600,
        height: 60,
      },
      sameAs: [
        "https://www.facebook.com/noomii",
        "https://twitter.com/Noomii",
        "https://www.linkedin.com/company/noomii"
      ],
    },
    datePublished: publishDateISO,
    dateModified: new Date(post.updated_at || post.publish_date).toISOString(),
    description: post.meta_description,
    mainEntityOfPage: {
      "@type": "WebPage",
      "@id": `https://blog.noomii.com/blog/${post.slug}`,
    },
    url: `https://blog.noomii.com/blog/${post.slug}`,
    articleSection: categoryLabels[post.category],
    keywords: post.keywords && post.keywords.length > 0 
      ? post.keywords.join(', ')
      : `${categoryLabels[post.category]}, coaching, professional development, personal growth`,
    wordCount: wordCount,
    timeRequired: `PT${post.read_time}M`,
    inLanguage: "en-US",
    isAccessibleForFree: true,
    isPartOf: {
      "@type": "Blog",
      "@id": "https://blog.noomii.com",
      name: "Coaching Conversations by Noomii",
      url: "https://blog.noomii.com",
    },
    speakable: {
      "@type": "SpeakableSpecification",
      cssSelector: [".prose"],
    },
    // Interaction statistics for social proof
    interactionStatistic: [
      {
        "@type": "InteractionCounter",
        interactionType: "https://schema.org/ReadAction",
        userInteractionCount: post.views || 0,
      }
    ],
    // Content rating
    contentRating: "General Audience",
    // Accessibility
    accessMode: ["textual", "visual"],
    accessibilityFeature: ["alternativeText", "readingOrder", "structuralNavigation"],
    accessibilityHazard: "none",
  };

  const breadcrumbStructuredData = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: [
      {
        "@type": "ListItem",
        position: 1,
        name: "Home",
        item: "https://blog.noomii.com",
      },
      {
        "@type": "ListItem",
        position: 2,
        name: "Blog",
        item: "https://blog.noomii.com/blog",
      },
      {
        "@type": "ListItem",
        position: 3,
        name: categoryLabels[post.category],
        item: `https://blog.noomii.com/blog?category=${post.category}`,
      },
      {
        "@type": "ListItem",
        position: 4,
        name: post.title,
        item: `https://blog.noomii.com/blog/${post.slug}`,
      },
    ],
  };

  // Extract FAQ questions from schema for display
  const faqQuestions = post.faq_schema?.mainEntity?.map((entity: any) => ({
    question: entity.name,
    answer: entity.acceptedAnswer?.text || ""
  })) || [];

  // WebSite Schema with Sitelinks SearchBox
  const websiteStructuredData = {
    "@context": "https://schema.org",
    "@type": "WebSite",
    name: "Coaching Conversations by Noomii",
    url: "https://blog.noomii.com",
    description: "Expert coaching insights, advice, and resources to help you find the right coach and transform your life.",
    publisher: {
      "@type": "Organization",
      name: "Noomii",
      url: "https://www.noomii.com",
      logo: {
        "@type": "ImageObject",
        url: "https://blog.noomii.com/noomii-logo.png",
      },
    },
    potentialAction: {
      "@type": "SearchAction",
      target: {
        "@type": "EntryPoint",
        urlTemplate: "https://blog.noomii.com/blog?search={search_term_string}",
      },
      "query-input": "required name=search_term_string",
    },
  };

  const allStructuredData = [structuredData, breadcrumbStructuredData, websiteStructuredData];
  if (post.faq_schema) {
    allStructuredData.push(post.faq_schema);
  }

  return (
    <>
      <SEOHead
        title={post.meta_title || post.title}
        description={post.meta_description}
        canonical={`https://blog.noomii.com/blog/${post.slug}`}
        ogType="article"
        ogImage={post.image}
        ogImageAlt={`${post.title} - ${categoryLabels[post.category]} coaching insights by ${post.author_name}`}
        keywords={seoKeywords}
        article={{
          publishedTime: publishDateISO,
          modifiedTime: modifiedDateISO,
          author: post.author_name,
          section: categoryLabels[post.category],
          tags: seoKeywords,
        }}
        structuredData={allStructuredData}
        locale={post.locale || 'en-us'}
        localeVariants={localeVariants}
        targetMarkets={post.target_markets || ['US']}
      />

      <AdvancedSchema
        author={{
          name: post.author_name,
          url: post.author_profile_url,
          image: post.author_avatar,
          jobTitle: `Professional ${categoryLabels[post.category]} Coach`,
          bio: authorBio,
          sameAs: [post.author_profile_url, "https://www.noomii.com"].filter(Boolean),
        }}
      />

      <ReadingProgress />

      <div className="min-h-screen bg-background">
        <BlogHeader />
        
        {/* Language Selector - Top Right */}
        <div className="container mx-auto px-4 py-2 flex justify-end">
          <LanguageSelector 
            currentLocale={post.locale || 'en-us'}
            localeVariants={localeVariants}
          />
        </div>

        {/* Breadcrumb Navigation */}
        <nav className="container mx-auto px-4 py-4 bg-muted/30" aria-label="Breadcrumb">
          <ol className="flex items-center gap-2 text-sm">
            <li>
              <Link 
                to="/" 
                className="text-muted-foreground hover:text-primary transition-colors font-medium"
              >
                Home
              </Link>
            </li>
            <li aria-hidden="true">
              <ChevronRight className="w-4 h-4 text-muted-foreground" />
            </li>
            <li>
              <Link
                to="/blog"
                className="text-muted-foreground hover:text-primary transition-colors font-medium"
              >
                Blog
              </Link>
            </li>
            <li aria-hidden="true">
              <ChevronRight className="w-4 h-4 text-muted-foreground" />
            </li>
            <li>
              <Link
                to={`/blog?category=${post.category}`}
                className="text-muted-foreground hover:text-primary transition-colors font-medium"
              >
                {categoryLabels[post.category]}
              </Link>
            </li>
            <li aria-hidden="true">
              <ChevronRight className="w-4 h-4 text-muted-foreground" />
            </li>
            <li>
              <span className="text-foreground font-medium line-clamp-1">
                {post.title}
              </span>
            </li>
          </ol>
        </nav>

        {/* Hero Section */}
        <article className="container mx-auto px-4 pb-16">
          <header className="max-w-4xl mx-auto mb-8">
            <Badge className="mb-4 bg-primary text-primary-foreground">
              {categoryLabels[post.category]}
            </Badge>

            <h1 className="text-4xl md:text-5xl font-bold mb-6 leading-tight">
              {post.title}
            </h1>

            <div className="flex items-center gap-4 mb-6">
              <img
                src={post.author_avatar}
                alt={post.author_name}
                loading="eager"
                decoding="async"
                width="56"
                height="56"
                className="w-14 h-14 rounded-full"
              />
              <div>
                <a
                  href={post.author_profile_url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="font-semibold hover:text-primary transition-colors"
                >
                  {post.author_name}
                </a>
                <div className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground">
                  <span className="flex items-center gap-1">
                    <Calendar className="w-4 h-4" />
                    {publishDate}
                  </span>
                  {post.updated_at && new Date(post.updated_at).getTime() !== new Date(post.publish_date).getTime() && (
                    <span className="flex items-center gap-1 text-xs">
                      Updated: {new Date(post.updated_at).toLocaleDateString("en-US", {
                        year: "numeric",
                        month: "short",
                        day: "numeric",
                      })}
                    </span>
                  )}
                  <span className="flex items-center gap-1">
                    <Clock className="w-4 h-4" />
                    {post.read_time} min read
                  </span>
                  <span className="flex items-center gap-1">
                    <Eye className="w-4 h-4" />
                    {post.views.toLocaleString()} views
                  </span>
                </div>
              </div>
            </div>
          </header>

          {/* Featured Image — locked to a universal 16:9 ratio */}
          <div className="max-w-5xl mx-auto mb-12">
            <SEOEnhancedImage
              src={post.image}
              alt={`${post.title} - ${categoryLabels[post.category]} coaching insights and strategies`}
              title={post.title}
              loading="eager"
              fetchPriority="high"
              className="w-full aspect-[16/9] overflow-hidden rounded-lg shadow-lg"
              imgClassName="w-full h-full object-cover"
              width="1600"
              height="900"
            />
          </div>

          {/* Content with Table of Contents */}
          <div className="max-w-7xl mx-auto">
            <div className="grid grid-cols-1 xl:grid-cols-[1fr,300px] gap-8">
              <div className="max-w-3xl">
                <div className="prose prose-lg max-w-none prose-a:text-primary prose-a:underline prose-img:rounded-lg prose-img:aspect-[16/9] prose-img:object-cover prose-img:w-full">
                  <p className="lead text-xl text-muted-foreground mb-8">{post.excerpt}</p>
                  <div dangerouslySetInnerHTML={{ 
                    __html: enhanceContentLinks(DOMPurify.sanitize(post.content, {
                      ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'u', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'a', 'blockquote', 'code', 'pre', 'img', 'span', 'div'],
                      ALLOWED_ATTR: ['href', 'src', 'alt', 'title', 'class', 'target', 'rel', 'id']
                    }))
                  }} />
                </div>


                {/* Internal Links Section */}
                <InternalLinks postId={post.id} maxLinks={4} />

                {/* Relevant, verified links into noomii.com */}
                <NoomiiResourceLinks postId={post.id} maxLinks={5} />

                {/* FAQ Section */}
                {faqQuestions.length > 0 && (
                  <FAQSection faqs={faqQuestions} />
                )}

                {/* Promotional Banner */}
                <div className="mt-12 mb-8">
                  <PromoBanner category={post.category} />
                </div>

                {/* Author Bio */}
                <Card className="mt-8 p-6">
              <div className="flex items-start gap-4">
                <SEOEnhancedImage
                  src={post.author_avatar}
                  alt={`${post.author_name} - Professional ${categoryLabels[post.category]} coach`}
                  title={post.author_name}
                  loading="lazy"
                  width="80"
                  height="80"
                  className="w-20 h-20 rounded-full"
                />
                <div className="flex-1">
                  <h3 className="text-xl font-bold mb-2">About {post.author_name}</h3>
                  
                  {/* Job Title and Experience */}
                  {(authorProfile?.job_title || authorProfile?.years_experience) && (
                    <div className="mb-3">
                      {authorProfile?.job_title && (
                        <p className="text-sm font-semibold text-foreground">{authorProfile.job_title}</p>
                      )}
                      {authorProfile?.years_experience && (
                        <p className="text-sm text-muted-foreground">{authorProfile.years_experience} years of experience</p>
                      )}
                    </div>
                  )}

                  {/* Bio */}
                  <p className="text-muted-foreground mb-3">
                    {authorBio || `${post.author_name} is a professional coach specializing in ${categoryLabels[post.category].toLowerCase()}. With years of experience helping clients achieve their goals, they bring a wealth of knowledge and practical insights to the coaching community.`}
                  </p>

                  {/* Credentials */}
                  {authorProfile?.credentials && authorProfile.credentials.length > 0 && (
                    <div className="mb-3">
                      <p className="text-xs font-semibold text-muted-foreground mb-1">Credentials</p>
                      <div className="flex flex-wrap gap-1">
                        {authorProfile.credentials.map((cred: string, idx: number) => (
                          <Badge key={idx} variant="secondary" className="text-xs">{cred}</Badge>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Certifications */}
                  {authorProfile?.certifications && authorProfile.certifications.length > 0 && (
                    <div className="mb-3">
                      <p className="text-xs font-semibold text-muted-foreground mb-1">Certifications</p>
                      <div className="flex flex-wrap gap-1">
                        {authorProfile.certifications.map((cert: string, idx: number) => (
                          <Badge key={idx} variant="outline" className="text-xs">{cert}</Badge>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Education */}
                  {authorProfile?.education && authorProfile.education.length > 0 && (
                    <div className="mb-3">
                      <p className="text-xs font-semibold text-muted-foreground mb-1">Education</p>
                      <ul className="text-sm text-muted-foreground list-disc list-inside">
                        {authorProfile.education.map((edu: string, idx: number) => (
                          <li key={idx}>{edu}</li>
                        ))}
                      </ul>
                    </div>
                  )}

                  {/* Awards */}
                  {authorProfile?.awards && authorProfile.awards.length > 0 && (
                    <div className="mb-3">
                      <p className="text-xs font-semibold text-muted-foreground mb-1">Awards & Recognition</p>
                      <ul className="text-sm text-muted-foreground list-disc list-inside">
                        {authorProfile.awards.map((award: string, idx: number) => (
                          <li key={idx}>{award}</li>
                        ))}
                      </ul>
                    </div>
                  )}

                  {/* Published Works */}
                  {authorProfile?.published_works && authorProfile.published_works.length > 0 && (
                    <div className="mb-3">
                      <p className="text-xs font-semibold text-muted-foreground mb-1">Published Works</p>
                      <ul className="text-sm text-muted-foreground list-disc list-inside">
                        {authorProfile.published_works.map((work: string, idx: number) => (
                          <li key={idx}>{work}</li>
                        ))}
                      </ul>
                    </div>
                  )}

                  {/* Specializations */}
                  {authorProfile?.specializations && authorProfile.specializations.length > 0 && (
                    <div className="mb-3">
                      <p className="text-xs font-semibold text-muted-foreground mb-1">Specializations</p>
                      <div className="flex flex-wrap gap-1">
                        {authorProfile.specializations.map((spec: string, idx: number) => (
                          <Badge key={idx} variant="default" className="text-xs">{spec}</Badge>
                        ))}
                      </div>
                    </div>
                  )}

                  <a
                    href={post.author_profile_url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-primary hover:underline text-sm font-medium"
                  >
                    View Profile on Noomii →
                  </a>
                </div>
              </div>
            </Card>

                {/* Related Posts */}
                {relatedPosts.length > 0 && (
                  <section className="mt-16">
                    <h2 className="text-2xl font-bold mb-6">Related Articles</h2>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      {relatedPosts.map((relatedPost) => (
                        <Link key={relatedPost.id} to={`/blog/${relatedPost.slug}`}>
                          <Card className="overflow-hidden group hover:shadow-lg transition-shadow">
                            <SEOEnhancedImage
                              src={relatedPost.image}
                              alt={`${relatedPost.title} - Related ${categoryLabels[post.category]} article`}
                              title={relatedPost.title}
                              loading="lazy"
                              className="w-full aspect-[16/9] object-cover group-hover:scale-105 transition-transform duration-300"
                              width="400"
                              height="225"
                            />
                            <div className="p-4">
                              <h3 className="font-bold mb-2 group-hover:text-primary transition-colors">
                                {relatedPost.title}
                              </h3>
                              <p className="text-sm text-muted-foreground line-clamp-2">
                                {relatedPost.excerpt}
                              </p>
                            </div>
                          </Card>
                        </Link>
                      ))}
                    </div>
                  </section>
                )}
              </div>

              {/* Sidebar with Table of Contents */}
              <aside className="hidden xl:block">
                <TableOfContents />
              </aside>
            </div>
          </div>

          {/* Share Buttons - Sticky on mobile, normal on desktop */}
          <div className="pb-24 md:pb-0">
            <SocialShareEnhanced
              url={`/blog/${post.slug}`}
              title={post.title}
              description={post.excerpt}
              image={post.image}
              hashtags={seoKeywords.slice(0, 3)}
            />
          </div>
        </article>

        <BlogFooter />
      </div>
    </>
  );
};

export default BlogPost;
