'use client'
import Image from 'next/image'
import { Calendar, Eye, User, Share } from 'iconsax-react'
import LastPost from '../components/LastPost'
import { NextPage } from 'next'
import Layout from '@/hoc/Layout'
import { SHOP_CONFIG } from '@/config/const'
import { useGetBlogDetails, useGetLastBlogs } from '../hooks/useBlogData'
import { useParams } from 'next/navigation'
import { useEffect, useState } from 'react'

const BlogDetail: NextPage = () => {

    const { id } = useParams()
    const { data, isLoading } = useGetBlogDetails(id as string)
    const { data: lastBlogsData } = useGetLastBlogs(3)
    const [currentUrl, setCurrentUrl] = useState('')

    useEffect(() => {
        if (typeof window !== 'undefined') {
            setCurrentUrl(window.location.href)
        }
    }, [])

    const shareOnTelegram = () => {
        const blog = data?.results?.blog
        if (blog && currentUrl) {
            const text = `مشاهده مقاله: ${blog.title_fa}`
            const url = `https://t.me/share/url?url=${encodeURIComponent(currentUrl)}&text=${encodeURIComponent(text)}`
            window.open(url, '_blank')
        }
    }

    const shareOnWhatsApp = () => {
        const blog = data?.results?.blog
        if (blog && currentUrl) {
            const text = `${blog.title_fa}\n\n${currentUrl}`
            const url = `https://wa.me/?text=${encodeURIComponent(text)}`
            window.open(url, '_blank')
        }
    }

    const handleNativeShare = async () => {
        const blog = data?.results?.blog
        if (blog && currentUrl && typeof navigator !== 'undefined' && 'share' in navigator) {

            const shareData = {
                title: blog.title_fa,
                text: `مشاهده مقاله: ${blog.title_fa}`,
                url: currentUrl,
            }
            await (navigator as { share: (data: typeof shareData) => Promise<void> }).share(shareData)

        }
    }

    if (isLoading) {
        return <div className="flex justify-center items-center min-h-screen">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
        </div>
    }

    if (!data?.results?.blog) {
        return <div className="flex justify-center items-center min-h-screen">
            <p className="text-gray-500">بلاگ یافت نشد</p>
        </div>
    }

    const blog = data.results.blog

    return (
        <div className="max-w-7xl mx-auto px-4 py-8">
            {/* Breadcrumb */}
            <div className="text-sm text-gray-500 mb-6">
                فروشگاه {SHOP_CONFIG.name} / {blog.category.title_fa} / {blog.title_fa}
            </div>

            <div className="flex gap-8">
                {/* Main Content */}
                <div className="flex-1">
                    {/* Blog Header */}
                    <div className="mb-8">
                        <div className="bg-orange-100 text-orange-600 px-3 py-1 rounded text-sm inline-block mb-4">
                            {blog.category.title_fa}
                        </div>

                        <h1 className="text-2xl font-bold text-gray-900 mb-4 leading-relaxed">
                            {blog.title_fa}
                        </h1>

                        <div className="flex items-center gap-6 text-gray-500 text-sm">
                            <div className="flex items-center gap-2">
                                <User size={16} color="#9CA3AF" />
                                <span>نویسنده: {blog.author.fullName}</span>
                            </div>
                            <div className="flex items-center gap-2">
                                <Calendar size={16} color="#9CA3AF" />
                                <span>{blog.createdAt}</span>
                            </div>
                            <div className="flex items-center gap-2">
                                <Eye size={16} color="#9CA3AF" />
                                <span>{blog.view} بازدید</span>
                            </div>
                        </div>
                    </div>

                    {/* Featured Image */}
                    <div className="mb-8">
                        <Image
                            src={blog.imageUrl}
                            alt={blog.title_fa}
                            width={1200}
                            height={600}
                            className="w-full h-[400px] object-cover rounded-lg"
                        />
                    </div>

                    {/* Blog Content */}
                    <div
                        className="prose prose-lg max-w-none text-gray-800 leading-8"
                        dangerouslySetInnerHTML={{ __html: blog.content }}
                    />

                    {/* Tags */}
                    <div className="mt-8 pt-6 border-t border-gray-200">
                        <div className="flex items-center gap-2 flex-wrap">
                            <span className="text-gray-600 font-medium">برچسب‌ها:</span>
                            {blog.tags.map((tag, index) => (
                                <span key={index} className="bg-primary/10 text-primary px-3 py-1 rounded-full text-sm">
                                    {tag}
                                </span>
                            ))}
                        </div>
                    </div>

                    {/* Share Section */}
                    <div className="mt-6 pt-6 border-t border-gray-200">
                        <div className="flex items-center justify-between">
                            <div className="flex items-center gap-4">
                                <span className="text-gray-600 font-medium">اشتراک‌گذاری:</span>
                                <button
                                    onClick={shareOnTelegram}
                                    className="flex items-center gap-2 bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-colors"
                                >
                                    <span>تلگرام</span>
                                </button>
                                <button
                                    onClick={shareOnWhatsApp}
                                    className="flex items-center gap-2 bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition-colors"
                                >
                                    <span>واتساپ</span>
                                </button>
                                {typeof navigator !== 'undefined' && 'share' in navigator && (
                                    <button
                                        onClick={handleNativeShare}
                                        className="flex items-center gap-2 bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 transition-colors"
                                    >
                                        <Share size={16} color='#ffffff' />
                                        <span>اشتراک‌گذاری</span>
                                    </button>
                                )}
                            </div>
                        </div>
                    </div>
                </div>

                {/* Sidebar */}
                <div className="w-80 space-y-8">
                    <LastPost blogs={lastBlogsData?.results?.blogs || []} />
                </div>
            </div>
        </div>
    )
}

export default function BlogDetailWithLayout() {
    return (
        <Layout>
            <BlogDetail />
        </Layout>
    )
}