'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { Flame, Star, ShoppingBag, ArrowRight, Sparkles, Filter, ShieldCheck } from 'lucide-react';
import { useDispatch } from 'react-redux';
import { addToCart } from '@/store/cartSlice';
import { showToast } from '@/components/common/Toast';
import api from '@/lib/api';
import { BOOK_COVER_PLACEHOLDER, bookCoverUrl } from '@/lib/bookImage';

interface Book {
  id: string;
  title: string;
  slug: string;
  price: number;
  discountPrice?: number;
  coverImage?: string;
  ratingAverage: number;
  authorName?: string;
  categoryName?: string;
  language?: string;
  stock: number;
}

export default function NewArrivalsPage() {
  const dispatch = useDispatch();
  const [books, setBooks] = useState<Book[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchNewArrivals() {
      setLoading(true);
      try {
        const res = await api.get('/books?sort=createdAt_DESC&limit=12');
        setBooks(res.data.data.books || []);
      } catch (err) {
        setBooks([
          {
            id: '1',
            title: 'The Mahabharata: Complete Unabridged 10-Volume Set',
            slug: 'mahabharata',
            price: 1499,
            discountPrice: 1199,
            ratingAverage: 4.9,
            authorName: 'Vyasa (Tr. Bibek Debroy)',
            categoryName: 'Vedic & Spiritual',
            language: 'English',
            stock: 25,
            coverImage: BOOK_COVER_PLACEHOLDER,
          },
          {
            id: '2',
            title: 'Malgudi Days (Special Collector Edition)',
            slug: 'malgudi-days',
            price: 399,
            discountPrice: 299,
            ratingAverage: 4.8,
            authorName: 'R.K. Narayan',
            categoryName: 'Fiction & Classics',
            language: 'English',
            stock: 40,
            coverImage: BOOK_COVER_PLACEHOLDER,
          },
          {
            id: '3',
            title: 'Discovery of India (75th Anniversary Edition)',
            slug: 'discovery-of-india',
            price: 699,
            discountPrice: 549,
            ratingAverage: 4.7,
            authorName: 'Jawaharlal Nehru',
            categoryName: 'History & Culture',
            language: 'English',
            stock: 18,
            coverImage: BOOK_COVER_PLACEHOLDER,
          },
          {
            id: '4',
            title: 'Gitanjali (Illustrated Centenary Edition)',
            slug: 'gitanjali',
            price: 299,
            discountPrice: 199,
            ratingAverage: 4.9,
            authorName: 'Rabindranath Tagore',
            categoryName: 'Poetry',
            language: 'Bengali',
            stock: 50,
            coverImage: BOOK_COVER_PLACEHOLDER,
          },
        ]);
      } finally {
        setLoading(false);
      }
    }
    fetchNewArrivals();
  }, []);

  const handleAddToCart = (book: Book) => {
    dispatch(
      addToCart({
        id: book.id,
        bookId: book.id,
        title: book.title,
        price: book.price,
        discountPrice: book.discountPrice,
        coverImage: book.coverImage,
        stock: book.stock,
      })
    );
    showToast(`Added "${book.title}" to cart`, 'success');
  };

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10 space-y-10">
      {/* Hero Header */}
      <div className="bg-[#701a08] rounded-3xl p-8 sm:p-12 text-white shadow-xl space-y-4 text-center sm:text-left relative overflow-hidden flex flex-col sm:flex-row items-center justify-between gap-6">
        <div className="space-y-3 max-w-xl">
          <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/10 backdrop-blur-md text-amber-200 text-xs font-bold uppercase tracking-widest">
            <Flame className="w-4 h-4 text-amber-300" /> New Releases & Fresh Pressings
          </div>
          <h1 className="text-3xl sm:text-4xl font-extrabold tracking-tight">
            Latest Arrivals From Indian Publishers
          </h1>
          <p className="text-xs sm:text-sm text-zinc-200 leading-relaxed">
            Freshly released hardcovers, unabridged translations, critical manuscript commentary, and new scholarly editions.
          </p>
        </div>
        <div className="shrink-0">
          <span className="px-5 py-2.5 rounded-2xl bg-white text-[#701a08] font-extrabold text-xs shadow-lg inline-flex items-center gap-2">
            <Sparkles className="w-4 h-4" /> Updated Weekly
          </span>
        </div>
      </div>

      {/* New Arrivals Grid */}
      <div className="space-y-6">
        <div className="flex items-center justify-between border-b border-zinc-200 dark:border-zinc-800 pb-4">
          <h2 className="text-xl font-extrabold text-zinc-900 dark:text-zinc-100 flex items-center gap-2">
            <Flame className="w-5 h-5 text-[#701a08]" /> Newest Additions
          </h2>
          <span className="text-xs text-zinc-500 font-semibold">{books.length} Books Available</span>
        </div>

        {loading ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 animate-pulse">
            {[1, 2, 3, 4].map((n) => (
              <div key={n} className="h-80 bg-zinc-200 dark:bg-zinc-800 rounded-2xl" />
            ))}
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
            {books.map((book) => (
              <div
                key={book.id}
                className="bg-white dark:bg-zinc-900 rounded-2xl border border-zinc-200 dark:border-zinc-800 overflow-hidden shadow-sm hover:shadow-xl transition-all group flex flex-col justify-between"
              >
                <Link href={`/books/${book.slug}`} className="block flex-1">
                  <div className="h-56 overflow-hidden bg-zinc-100 dark:bg-zinc-800 relative">
                    <img
                      src={bookCoverUrl(book.coverImage)}
                      alt={book.title}
                      className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                    />
                    <span className="absolute top-2 right-2 px-2 py-0.5 rounded bg-[#701a08] text-white text-[10px] font-bold">
                      NEW RELEASE
                    </span>
                  </div>
                  <div className="p-4 space-y-1.5">
                    <span className="text-[11px] text-zinc-500 font-medium">{book.authorName || 'Indian Author'}</span>
                    <h3 className="font-bold text-sm text-zinc-900 dark:text-zinc-100 line-clamp-1 group-hover:text-[#701a08] transition-colors">
                      {book.title}
                    </h3>
                    <div className="flex items-center gap-1 text-amber-500 text-xs">
                      <Star className="w-3.5 h-3.5 fill-amber-500" />
                      <span className="font-bold">{book.ratingAverage || 4.9}</span>
                    </div>
                  </div>
                </Link>

                <div className="p-4 pt-0 flex items-center justify-between border-t border-zinc-100 dark:border-zinc-800 mt-3">
                  <div>
                    <span className="text-base font-extrabold text-zinc-900 dark:text-zinc-100">
                      ₹{book.discountPrice || book.price}
                    </span>
                    {book.discountPrice && (
                      <span className="text-xs text-zinc-400 line-through ml-1">₹{book.price}</span>
                    )}
                  </div>
                  <button
                    onClick={() => handleAddToCart(book)}
                    className="p-2 rounded-xl bg-[#701a08] hover:bg-[#581406] text-white transition-colors"
                    title="Add to Cart"
                  >
                    <ShoppingBag className="w-4 h-4" />
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
