'use client';
import {
  ArrowLeft,
  Calendar,
  Facebook,
  Linkedin,
  Tag,
  Twitter,
  User,
} from 'lucide-react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import React, { useEffect, useState } from 'react';
import Lightbox from 'yet-another-react-lightbox';
import Captions from 'yet-another-react-lightbox/plugins/captions';
import Thumbnails from 'yet-another-react-lightbox/plugins/thumbnails';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import WebLayout from '@/components/web/layout/web-layout';
import { cn } from '@/lib/utils';
import 'yet-another-react-lightbox/styles.css';
import 'yet-another-react-lightbox/plugins/thumbnails.css';
import 'yet-another-react-lightbox/plugins/captions.css';
import Image from 'next/image';

const BlogPost = () => {
  const { id } = useParams<{ id: string }>();
  const [post, setPost] = useState<BlogProps | null>(null);
  const [posts, setPosts] = useState<BlogProps[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadings, setLoadings] = useState(true);
  const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);

  useEffect(() => {
    const fetchBlog = async () => {
      try {
        const response = await fetch(`/api/blogs/${id}`);
        const data = await response.json();
        setPost(data);
      } catch (error) {
        console.error('Failed to fetch blog post', error);
        setPost(null);
      } finally {
        setLoading(false);
      }
    };

    const fetchBlogs = async () => {
      try {
        const response = await fetch('/api/blogs');
        const data = await response.json();
        setPosts(data);
      } catch (error) {
        console.error('Failed to fetch blog posts', error);
      } finally {
        setLoadings(false);
      }
    };

    fetchBlogs();
    fetchBlog();
  }, [id]);

  const formatDate = (isoDate: string) => {
    const date = new Date(isoDate);
    const months = [
      'January',
      'February',
      'March',
      'April',
      'May',
      'June',
      'July',
      'August',
      'September',
      'October',
      'November',
      'December',
    ];
    return `${
      months[date.getMonth()]
    } ${date.getDate()}, ${date.getFullYear()}`;
  };

  // Skeleton loader
  if (loading) {
    return (
      <WebLayout>
        <div className="pt-20">
          {/* Hero Section Skeleton */}
          <section className="animate-pulse bg-gray-200 py-20 text-white">
            <div className="container mx-auto px-4">
              <div className="max-w-3xl">
                <div className="mb-4 h-6 w-40 rounded bg-gray-300" />
                <div className="mb-6 h-12 w-3/4 rounded bg-gray-300" />
                <div className="h-6 w-full rounded bg-gray-300" />
                <div className="mt-2 h-6 w-5/6 rounded bg-gray-300" />
              </div>
            </div>
          </section>

          {/* Blog Content Skeleton */}
          <section className="py-16">
            <div className="container mx-auto px-4">
              <div className="grid grid-cols-1 gap-12 lg:grid-cols-3">
                <div className="lg:col-span-2">
                  <div className="mb-6 h-8 w-1/4 rounded bg-gray-200" />
                  {[...Array(5)].map((_, i) => (
                    <div
                      className="mb-4 h-4 w-full rounded bg-gray-200"
                      key={i}
                    />
                  ))}
                  <div className="mt-12 mb-6 h-8 w-1/4 rounded bg-gray-200" />
                  <div className="grid grid-cols-2 gap-2 md:grid-cols-4">
                    {[...Array(4)].map((_, i) => (
                      <Skeleton className="h-64 w-full rounded-lg" key={i} />
                    ))}
                  </div>
                </div>

                <div className="lg:col-span-1">
                  <div className="sticky top-24 rounded-lg bg-gray-100 p-6">
                    <div className="mb-6 h-6 w-1/2 rounded bg-gray-200" />
                    <div className="mb-6 h-4 w-full rounded bg-gray-200" />
                    <div className="mb-4 h-10 w-full rounded bg-gray-200" />
                    <div className="h-10 w-full rounded bg-gray-200" />
                  </div>
                </div>
              </div>
            </div>
          </section>
        </div>
      </WebLayout>
    );
  }

  // Not found state
  if (!post) {
    return (
      <WebLayout>
        <div className="pt-32 pb-16">
          <div className="container mx-auto px-4 text-center">
            <h1 className="mb-6 font-bold text-3xl text-oki-gray-dark">
              Blog Post Not Found
            </h1>
            <p className="mb-8 text-gray-600">
              The article you're looking for doesn't exist or has been moved.
            </p>
            <Link href="/blog">
              <Button className="bg-oki-blue-dark text-white hover:bg-oki-blue-light">
                Return to Blog
              </Button>
            </Link>
          </div>
        </div>
      </WebLayout>
    );
  }

  return (
    <WebLayout>
      {/* Hero Section */}
      <section
        className="relative py-24"
        style={{
          backgroundImage: `url(${post.image})`,
          backgroundSize: 'cover',
          backgroundPosition: 'center',
        }}
      >
        <div className="absolute inset-0 bg-oki-blue-dark/75 " />
        <div className="container relative z-10 mx-auto px-4 pt-24">
          <Link
            className="mb-6 inline-flex items-center text-white/90 hover:text-white"
            href="/blog"
          >
            <ArrowLeft className="mr-2" size={16} />
            <span>Back to Blog</span>
          </Link>
          <h1 className="mb-6 max-w-4xl font-bold text-4xl text-white md:text-5xl">
            {post.title}
          </h1>
          <div className="flex flex-wrap items-center gap-6 text-white/80">
            <div className="flex items-center">
              <User className="mr-2" size={18} />
              <span>{post.author}</span>
            </div>
            <div className="flex items-center">
              <Calendar className="mr-2" size={18} />
              <span>{formatDate(post.created_at)}</span>
            </div>
            <div className="flex items-center">
              <Tag className="mr-2" size={18} />
              <span>{post.category}</span>
            </div>
          </div>
        </div>
      </section>

      {/* Blog Content */}
      <section className="bg-white py-16 text-black">
        <div className="container mx-auto px-4">
          <div className="grid grid-cols-1 gap-12 lg:grid-cols-3">
            <div className="lg:col-span-2">
              <div className="prose prose-lg max-w-none">{post.content}</div>

              <div className="p-4">
                <h3 className="mb-6 font-bold text-2xl text-oki-gray-dark">
                  Blog Gallery
                </h3>
                <div className="grid grid-cols-1 gap-2 sm:grid-cols-2 md:grid-cols-4">
                  {post.images?.map((image, index) => (
                    <div
                      className={cn(
                        'h-64 cursor-pointer overflow-hidden rounded-lg',
                        index === 0 &&
                          'h-64 md:col-span-2 md:row-span-2 md:h-full',
                        index === 1 && 'md:col-span-1 md:row-span-1',
                        index === 2 && 'md:col-span-1 md:row-span-2',
                        index === 3 && 'md:col-span-2 md:row-span-1',
                        index === 4 && 'md:col-span-2 md:row-span-1',
                        index === 5 && 'md:col-span-1 md:row-span-2'
                      )}
                      key={index}
                    >
                      <Image
                        alt={`${post.title} - Image ${index + 1}`}
                        className="h-full w-full object-cover grayscale transition-transform duration-500 hover:scale-105 hover:grayscale-0"
                        height={400}
                        onClick={() => setLightboxIndex(index)}
                        src={image.image}
                        width={600}
                      />
                    </div>
                  ))}
                </div>

                {lightboxIndex !== null && (
                  <Lightbox
                    close={() => setLightboxIndex(null)}
                    index={lightboxIndex}
                    open
                    plugins={[Thumbnails, Captions]}
                    slides={post.images.map((img) => ({
                      src: img.image,
                      title: post.title,
                      description: post.title,
                    }))}
                  />
                )}
              </div>

              {/* Share */}
              <div className="mt-12 border-gray-200 border-b pb-8">
                <h3 className="mb-4 font-semibold text-lg text-oki-gray-dark">
                  Share this article:
                </h3>
                <div className="flex gap-4">
                  <a
                    className="rounded-full bg-[#1877F2] p-2 text-white transition-opacity hover:opacity-90"
                    href={`https://facebook.com/sharer/sharer.php?u=https://okisokariari.com/blog/${post.id}`}
                    rel="noopener noreferrer"
                    target="_blank"
                  >
                    <Facebook size={18} />
                  </a>
                  <a
                    className="rounded-full bg-[#1DA1F2] p-2 text-white transition-opacity hover:opacity-90"
                    href={`https://twitter.com/intent/tweet?text=${post.title}&url=https://okisokariari.com/blog/${post.id}`}
                    rel="noopener noreferrer"
                    target="_blank"
                  >
                    <Twitter size={18} />
                  </a>
                  <a
                    className="rounded-full bg-[#0A66C2] p-2 text-white transition-opacity hover:opacity-90"
                    href={`https://www.linkedin.com/shareArticle?mini=true&url=https://okisokariari.com/blog/${post.id}&title=${post.title}`}
                    rel="noopener noreferrer"
                    target="_blank"
                  >
                    <Linkedin size={18} />
                  </a>
                </div>
              </div>

              {/* Author Bio */}
              <div className="mt-8 rounded-lg bg-oki-gray-light p-6">
                <div className="mb-4 flex items-center gap-4">
                  <div className="flex h-16 w-16 items-center justify-center rounded-full bg-oki-blue-light font-bold text-white text-xl">
                    {post.author
                      .split(' ')
                      .map((name: string) => name[0])
                      .join('')}
                  </div>
                  <div>
                    <h3 className="font-bold text-oki-gray-dark">
                      {post.author}
                    </h3>
                    <p className="text-gray-600">Author</p>
                  </div>
                </div>
                <p className="text-gray-600">
                  An expert in the field with years of industry experience at
                  O.K. Isokariari Nigeria Limited, committed to sharing
                  knowledge and insights on engineering and construction
                  excellence.
                </p>
              </div>
            </div>

            {/* Sidebar */}
            <aside className="lg:col-span-1">
              {/* Recent Posts */}
              <div className="mb-8 rounded-lg bg-white p-6 shadow-md">
                <h3 className="mb-6 border-b pb-3 font-semibold text-oki-gray-dark text-xl">
                  Recent Posts
                </h3>
                <div className="space-y-6">
                  {posts
                    .filter((p) => p.id !== post.id)
                    .slice(0, 3)
                    .map((recentPost) => (
                      <div className="flex gap-4" key={recentPost.id}>
                        <div className="h-20 w-20 flex-shrink-0">
                          <Image
                            alt={recentPost.title}
                            className="h-full w-full rounded object-cover"
                            src={recentPost.image}
                          />
                        </div>
                        <div>
                          <Link
                            className="font-medium text-oki-gray-dark transition-colors hover:text-oki-blue-dark"
                            href={`/blog/${recentPost.slug}`}
                          >
                            {recentPost.title}
                          </Link>
                          <p className="mt-1 text-gray-500 text-sm">
                            {formatDate(recentPost.created_at)}
                          </p>
                        </div>
                      </div>
                    ))}
                </div>
              </div>

              {/* Categories */}
              <div className="mb-8 rounded-lg bg-white p-6 shadow-md">
                <h3 className="mb-6 border-b pb-3 font-semibold text-oki-gray-dark text-xl">
                  Categories
                </h3>
                <ul className="space-y-2">
                  {Array.from(new Set(posts.map((p) => p.category))).map(
                    (category) => (
                      <li key={category}>
                        <Link
                          className="flex items-center text-gray-600 transition-colors hover:text-oki-blue-dark"
                          href={`/blog?category=${category}`}
                        >
                          <ArrowLeft className="mr-2 rotate-180" size={14} />
                          {category}
                        </Link>
                      </li>
                    )
                  )}
                </ul>
              </div>

              {/* CTA */}
              <div className="rounded-lg bg-oki-blue-dark p-6 text-white shadow-md">
                <h3 className="mb-4 font-semibold text-xl">
                  Need Expert Consultation?
                </h3>
                <p className="mb-6 text-white/80">
                  Our team of experts is ready to assist you with your
                  construction and engineering needs.
                </p>
                <Link href="/contact">
                  <Button className="w-full bg-white text-oki-blue-dark hover:bg-white/90">
                    Contact Us
                  </Button>
                </Link>
              </div>
            </aside>
          </div>
        </div>
      </section>
    </WebLayout>
  );
};

export default BlogPost;
