"use client";

import React, { useEffect, useState } from "react";
import { apiCall } from "@/utils/callApi";
import {
  Calendar,
  User,
  Eye,
  X,
  Clock,
  ArrowLeft,
  ArrowRight,
} from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import Newsletter from "@/components/frontend-pages/home/Newsletter";

interface Blog {
  _id: string;
  title: string;
  sub_title: string;
  images: string[];
  description: string;
  short_description: string;
  createdAt: string;
  slug: string;
  updatedAt: string;
}

export default function BlogPage() {
  const [blogs, setBlogs] = useState<Blog[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedBlog, setSelectedBlog] = useState<Blog | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [searchTerm, setSearchTerm] = useState("");

  useEffect(() => {
    fetchBlogs();
  }, [currentPage]);

  const fetchBlogs = async () => {
    try {
      setLoading(true);
      const response = await apiCall<any>(
        `/clientapi/blog?page=${currentPage}&limit=6`,
      );
      // console.log("Blog API Response:", response);

      if (response?.data.success && response?.data) {
        setBlogs(response.data.data);
        setTotalPages(response.data.pagination?.pages || 1);
      }
    } catch (error) {
      console.error("Error fetching blogs:", error);
    } finally {
      setLoading(false);
    }
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });
  };

  const stripHtml = (html: string) => {
    const tmp = document.createElement("DIV");
    tmp.innerHTML = html;
    return tmp.textContent || tmp.innerText || "";
  };

  const filteredBlogs = blogs.filter(
    (blog) =>
      blog.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
      blog.short_description.toLowerCase().includes(searchTerm.toLowerCase()),
  );

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50">
        <div className="container mx-auto px-3 py-6 md:py-10">
          <div className="animate-pulse">
            <div className="mb-6 h-8 w-48 rounded bg-gray-200"></div>
            <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
              {[1, 2, 3, 4, 5, 6].map((i) => (
                <div
                  key={i}
                  className="overflow-hidden rounded-xl bg-white shadow"
                >
                  <div className="h-48 bg-gray-200"></div>
                  <div className="p-4">
                    <div className="mb-2 h-6 w-3/4 rounded bg-gray-200"></div>
                    <div className="mb-2 h-4 w-full rounded bg-gray-200"></div>
                    <div className="h-4 w-2/3 rounded bg-gray-200"></div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen">
      {/* Breadcrumb */}
      <section className="breadcrumbcontainer">
        <div className="container px-3">
          <ol className="breadcrumb">
            <li className="breadcrumb-item">
              <a href="/">
                Home
              </a>
            </li>
            <li className="breadcrumb-item active ">
              Blog
            </li>
          </ol>
        </div>
      </section>

      <section className="blogcontainer py-10">
        <div className="container px-3">
          {/* Header */}
          <div className="mb-8 text-center">
            <h1 className="mb-2 text-3xl font-bold text-gray-800 md:text-4xl">
              Our Blog
            </h1>
            <p className="mx-auto max-w-2xl text-gray-500">
              Discover the latest trends, styling tips, and fashion insights from
              our experts.
            </p>
          </div>

          {/* Search Bar */}
          <div className="mx-auto mb-8 max-w-md">
            <div className="relative">
              <input
                type="text"
                placeholder="Search blogs..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full rounded-lg border border-gray-300 px-4 py-2 pl-10 pr-4 focus:border-transparent focus:outline-none focus:ring-2 focus:ring-primary"
              />
              <svg
                className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-gray-400"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                />
              </svg>
            </div>
          </div>

          {/* Blog Grid */}
          {filteredBlogs.length === 0 ? (
            <div className="py-12 text-center">
              <p className="text-gray-500">
                No blogs found matching your search.
              </p>
            </div>
          ) : (
            <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
              {filteredBlogs.map((blog) => (
                 <Link href={"/blog/" + blog.slug}>
                <div
                  key={blog._id}
                 
                  className="blogbx flex flex-col overflow-hidden"
                >
                  {/* Blog Image */}
                  <div className="blogbximg overflow-hidden">
                    <img
                      src={blog.images[0]}
                      alt={blog.title}
                      className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
                    />
                    <div className="absolute inset-0 bg-black opacity-0 transition-opacity group-hover:opacity-20"></div>
                  </div>

                  {/* Blog Content */}
                  <div className="blogbxcontent flex flex-col flex-1 p-5">
                    <div className="flex-1">
                      <span className="date">
                        <Calendar size={12} />
                        {formatDate(blog.createdAt)}
                      </span>
                      <h3 className="line-clamp-2">
                        {blog.title}
                      </h3>
                      <p className="line-clamp-3">
                        {stripHtml(blog.short_description)}
                      </p>
                    </div>
                   
                      <button className="knowmorebtn mt-5 inline-flex items-center gap-2 font-medium">
                        <span>Read More</span>
                        <i className="icon icon-angle-right"></i>
                      </button>
                    
                  </div>
                </div>
                </Link>
              ))}
            </div>
          )}

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="mt-8 flex items-center justify-center gap-2">
              <button
                onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
                disabled={currentPage === 1}
                className="rounded-lg border border-gray-300 p-2 transition hover:bg-primary hover:text-white disabled:cursor-not-allowed disabled:opacity-50"
              >
                <ArrowLeft size={18} />
              </button>
              <span className="px-4 py-2 text-sm">
                Page {currentPage} of {totalPages}
              </span>
              <button
                onClick={() =>
                  setCurrentPage((prev) => Math.min(prev + 1, totalPages))
                }
                disabled={currentPage === totalPages}
                className="rounded-lg border border-gray-300 p-2 transition hover:bg-primary hover:text-white disabled:cursor-not-allowed disabled:opacity-50"
              >
                <ArrowRight size={18} />
              </button>
            </div>
          )}
        </div>
      </section>

      {/* Blog Details Modal */}

      <Newsletter />
      <style jsx>{`
        @keyframes fadeIn {
          from {
            opacity: 0;
            transform: scale(0.95);
          }
          to {
            opacity: 1;
            transform: scale(1);
          }
        }
        .animate-fadeIn {
          animation: fadeIn 0.2s ease-out;
        }
        .line-clamp-2 {
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
        .line-clamp-3 {
          display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
      `}</style>
    </div>
  );
}
