'use client';
import { ArrowLeft } from 'lucide-react';
import Image from 'next/image';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import WebLayout from '@/components/web/layout/web-layout';
import type { Blog, Page } from '@/db/schema';
import { formatDate } from '@/lib/AdminUtils';
import 'yet-another-react-lightbox/plugins/captions.css';
import 'yet-another-react-lightbox/plugins/thumbnails.css';
import 'yet-another-react-lightbox/styles.css';

const PageDetail = () => {
  const { slug } = useParams<{ slug: string }>();
  const [page, setPage] = useState<Page | null>(null);
  const [posts, setPosts] = useState<Blog[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadingPosts, setLoadingPosts] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        // Fetch page and posts in parallel
        const [pageRes, postsRes] = await Promise.all([
          fetch(`/api/pages/${slug}`),
          fetch('/api/blogs'),
        ]);

        const pageData = await pageRes.json();
        const postsData = await postsRes.json();

        setPage(pageData);
        setPosts(postsData);
      } catch (error) {
        console.error('Failed to fetch data:', error);
        setPage(null);
        setPosts([]);
      } finally {
        setLoading(false);
        setLoadingPosts(false);
      }
    };

    fetchData();
  }, [slug]);

  if (loading) {
    return (
      <WebLayout>
        <div className="pt-32 pb-16">
          <div className="container mx-auto px-4">
            <div className="animate-pulse space-y-4">
              <div className="h-10 w-2/3 rounded bg-gray-300" />
              <div className="h-6 w-1/2 rounded bg-gray-300" />
              <div className="h-64 rounded bg-gray-300" />
              <div className="space-y-2">
                <div className="h-4 rounded bg-gray-300" />
                <div className="h-4 w-5/6 rounded bg-gray-300" />
                <div className="h-4 w-4/6 rounded bg-gray-300" />
              </div>
            </div>
          </div>
        </div>
      </WebLayout>
    );
  }

  if (!page) {
    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">
              Page Not Found
            </h1>
            <p className="mb-8 text-gray-600">
              The page you're looking for doesn't exist or has been moved.
            </p>
            <Link href="/pages">
              <Button className="bg-oki-blue-dark text-white hover:bg-oki-blue-light">
                Return to Pages
              </Button>
            </Link>
          </div>
        </div>
      </WebLayout>
    );
  }

  return (
    <WebLayout>
      {/* Hero Section */}
      <section
        className="relative py-24"
        style={{
          backgroundImage: `url(${page.pageImage})`,
          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-20">
          <Link
            className="mb-6 inline-flex items-center text-white/90 hover:text-white"
            href="/pages"
          >
            <ArrowLeft className="mr-2" size={16} />
            <span>Back to Pages</span>
          </Link>
          <h1 className="mb-6 max-w-4xl font-bold text-4xl text-white md:text-5xl">
            {page.pageTitle}
          </h1>
        </div>
      </section>

      {/* Page 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">
                <h2 className="mb-4 font-semibold text-2xl">
                  {page.pageTitle}
                </h2>
                <div className="relative aspect-video w-full overflow-hidden rounded-lg">
                  <Image
                    alt={page.pageTitle}
                    className="object-cover"
                    fill
                    priority
                    src={page.pageImage}
                  />
                </div>
                <div
                  className="prose lg:prose-xl max-w-none"
                  dangerouslySetInnerHTML={{
                    __html: page.pageContents || '',
                  }}
                />
              </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>
                {loadingPosts ? (
                  <div className="space-y-6">
                    {Array.from({ length: 3 }).map((_, index) => (
                      <div className="flex gap-4" key={index}>
                        <div className="h-20 w-20 flex-shrink-0 rounded bg-gray-200" />
                        <div className="flex-1">
                          <div className="h-5 w-3/4 rounded bg-gray-200" />
                          <div className="mt-2 h-4 w-1/2 rounded bg-gray-200" />
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="space-y-6">
                    {posts
                      .filter((p) => p.id !== page.id)
                      .slice(0, 3)
                      .map((recentPost) => (
                        <div className="flex gap-4" key={recentPost.id}>
                          <div className="relative h-20 w-20 flex-shrink-0">
                            <Image
                              alt={recentPost.title}
                              className="rounded object-cover"
                              fill
                              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.createdAt)}
                            </p>
                          </div>
                        </div>
                      ))}
                  </div>
                )}
              </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 PageDetail;
