'use client'

import { useEffect } from 'react'
import Image from 'next/image'
import { useTranslations } from 'next-intl'
import { toast } from 'react-hot-toast'
import { Calendar, Clock, ArrowLeft, Share2, Newspaper } from 'lucide-react'
import { Link } from '@/i18n/navigation'
import Container from '@/components/frontend/Container'
import { useLocaleAlternatesStore } from '@/store/localeAlternatesStore'
import type { BlogPostDetail } from '@/lib/db/queries/getBlogPosts'

interface BlogDetailClientProps {
  post: BlogPostDetail
  // locale -> full path for this exact post, one entry per language it was
  // actually translated into — same language-switch-404 fix already applied
  // to the product detail page (post_translations.slug is only unique
  // *within* a language). See localeAlternatesStore.ts.
  alternatePaths: Record<string, string>
  defaultLocale: string
}

export default function BlogDetailClient({ post, alternatePaths, defaultLocale }: BlogDetailClientProps) {
  const t = useTranslations('Blog')
  const setAlternates = useLocaleAlternatesStore((s) => s.setAlternates)
  const clearAlternates = useLocaleAlternatesStore((s) => s.clearAlternates)

  useEffect(() => {
    setAlternates(alternatePaths, defaultLocale)
    return () => clearAlternates()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [alternatePaths, defaultLocale])

  const handleShare = async () => {
    const url = window.location.href
    if (typeof navigator.share === 'function') {
      try {
        await navigator.share({ title: post.title, url })
      } catch {
        // user cancelled the native share sheet — not an error
      }
      return
    }
    try {
      await navigator.clipboard.writeText(url)
      toast.success(t('linkCopied'))
    } catch {
      toast.error(t('shareFailed'))
    }
  }

  return (
    <>
      {/* Hero */}
      <section className="relative overflow-hidden bg-gradient-to-br from-primary/10 to-secondary/10 py-12">
        <Container>
          <div className="max-w-3xl mx-auto text-center">
            <Link
              href="/blogs"
              className="inline-flex items-center gap-1 text-sm text-primary hover:underline mb-4"
            >
              <ArrowLeft size={14} /> {t('backToBlog')}
            </Link>
            {post.categoryName && post.categorySlug && (
              <Link
                href={{ pathname: '/blogs', query: { category: post.categorySlug } }}
                className="inline-block bg-primary/10 text-primary text-xs font-medium px-3 py-1 rounded-full mb-4 hover:bg-primary hover:text-white transition"
              >
                {post.categoryName}
              </Link>
            )}
            <h1 className="text-3xl md:text-4xl lg:text-5xl font-bold text-dark mb-4">
              {post.title}
            </h1>
            <div className="flex flex-wrap justify-center gap-4 text-sm text-gray-custom">
              <div className="flex items-center gap-1">
                <Calendar size={14} />
                <span>{new Date(post.publishedAt).toLocaleDateString()}</span>
              </div>
              <div className="flex items-center gap-1">
                <Clock size={14} />
                <span>{t('readTimeMinutes', { minutes: post.readTimeMinutes })}</span>
              </div>
            </div>
          </div>
        </Container>
      </section>

      {/* Content */}
      <Container className="py-8">
        <div className="flex flex-col lg:flex-row gap-8">
          <article className="flex-1 max-w-3xl mx-auto">
            {/* Cover Image */}
            <div className="relative mb-8 rounded-xl overflow-hidden bg-gray-100 aspect-video flex items-center justify-center">
              {post.imageUrl ? (
                <Image src={post.imageUrl} alt={post.title} fill sizes="(max-width: 768px) 100vw, 768px" className="object-cover" priority />
              ) : (
                <Newspaper size={48} className="text-gray-300" />
              )}
            </div>

            {/* Article Body */}
            <div
              className="prose prose-lg max-w-none prose-headings:text-dark prose-p:text-gray-custom prose-strong:text-dark prose-li:text-gray-custom"
              dangerouslySetInnerHTML={{ __html: post.content ?? '' }}
            />

            {/* Share */}
            <div className="flex justify-center mt-8 pt-6 border-t border-gray-100">
              <button
                onClick={handleShare}
                className="flex items-center gap-2 px-4 py-2 bg-gray-100 rounded-full hover:bg-primary hover:text-white transition text-sm font-medium"
              >
                <Share2 size={16} /> {t('share')}
              </button>
            </div>
          </article>
        </div>

        {/* Related Posts */}
        {post.relatedPosts.length > 0 && (
          <div className="mt-12">
            <h2 className="text-2xl font-bold text-dark mb-6">{t('relatedArticles')}</h2>
            <div className="grid md:grid-cols-3 gap-6">
              {post.relatedPosts.map((relatedPost) => (
                <div key={relatedPost.id} className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden hover:shadow-md transition">
                  <Link href={`/blog/${relatedPost.slug}`} className="block">
                    <div className="relative h-40 bg-gray-100 flex items-center justify-center">
                      {relatedPost.imageUrl ? (
                        <Image src={relatedPost.imageUrl} alt={relatedPost.title} fill sizes="(max-width: 768px) 100vw, 300px" className="object-cover" />
                      ) : (
                        <Newspaper size={32} className="text-gray-300" />
                      )}
                    </div>
                    <div className="p-4">
                      <h3 className="font-semibold text-dark mb-2 line-clamp-2">{relatedPost.title}</h3>
                      {relatedPost.excerpt && <p className="text-sm text-gray-custom line-clamp-2">{relatedPost.excerpt}</p>}
                      <div className="flex items-center gap-3 text-xs text-gray-custom mt-3">
                        <span>{new Date(relatedPost.publishedAt).toLocaleDateString()}</span>
                        <span>{t('readTimeMinutes', { minutes: relatedPost.readTimeMinutes })}</span>
                      </div>
                    </div>
                  </Link>
                </div>
              ))}
            </div>
          </div>
        )}
      </Container>
    </>
  )
}
