import React, { useEffect, useState } from 'react';
import type { ReactElement } from 'react';
import Head from 'next/head';
import Link from 'next/link';
import axios from 'axios';
import { mdiMagnify, mdiBookOpenVariant, mdiCart, mdiChevronRight, mdiStar } from '@mdi/js';
import BaseIcon from '../components/BaseIcon';
import LayoutGuest from '../layouts/Guest';
import { getPageTitle } from '../config';

export default function LandingPage() {
  const [books, setBooks] = useState([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');

  useEffect(() => {
    const fetchBooks = async () => {
      try {
        // Fetch featured books or just first 8 books
        const response = await axios.get('/books', {
          params: { limit: 8, offset: 0 }
        });
        setBooks(response.data.rows || []);
      } catch (error) {
        console.error('Failed to fetch books:', error);
      } finally {
        setLoading(false);
      }
    };
    fetchBooks();
  }, []);

  return (
    <div className="bg-slate-50 min-h-screen font-sans text-slate-900">
      <Head>
        <title>{getPageTitle('Home')}</title>
      </Head>

      {/* Navigation */}
      <nav className="bg-white border-b border-slate-200 sticky top-0 z-50">
        <div className="container mx-auto px-4 h-16 flex items-center justify-between">
          <div className="flex items-center space-x-2">
            <BaseIcon path={mdiBookOpenVariant} size={28} className="text-blue-600" />
            <span className="text-xl font-bold tracking-tight">eBookStore</span>
          </div>
          <div className="hidden md:flex items-center space-x-8">
            <Link href="/" className="text-blue-600 font-medium hover:text-blue-700">Home</Link>
            <Link href="/login" className="text-slate-600 hover:text-blue-600 transition-colors">Catalog</Link>
            <Link href="/login" className="text-slate-600 hover:text-blue-600 transition-colors">Categories</Link>
          </div>
          <div className="flex items-center space-x-4">
             <Link href="/dashboard" className="text-slate-600 hover:text-blue-600 transition-colors mr-2">
              Admin
            </Link>
            <Link href="/login" className="bg-blue-600 text-white px-5 py-2 rounded-full font-medium hover:bg-blue-700 transition-all shadow-md hover:shadow-lg">
              Login
            </Link>
          </div>
        </div>
      </nav>

      {/* Hero Section */}
      <header className="bg-white py-16 md:py-24">
        <div className="container mx-auto px-4 text-center max-w-4xl">
          <h1 className="text-4xl md:text-6xl font-extrabold mb-6 leading-tight">
            Discover Your Next <span className="text-blue-600">Favorite Book</span>
          </h1>
          <p className="text-lg md:text-xl text-slate-600 mb-10 max-w-2xl mx-auto">
            Access thousands of digital books across all genres. Read anytime, anywhere on any device.
          </p>
          <div className="relative max-w-2xl mx-auto">
            <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
              <BaseIcon path={mdiMagnify} size={20} className="text-slate-400" />
            </div>
            <input
              type="text"
              className="block w-full pl-12 pr-4 py-4 bg-slate-50 border border-slate-200 rounded-2xl focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all shadow-sm"
              placeholder="Search by title, author, or ISBN..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
            <button className="absolute right-2 inset-y-2 bg-blue-600 text-white px-6 rounded-xl font-medium hover:bg-blue-700 transition-all">
              Search
            </button>
          </div>
        </div>
      </header>

      {/* Featured Books */}
      <section className="py-16 container mx-auto px-4">
        <div className="flex items-center justify-between mb-10">
          <h2 className="text-3xl font-bold">Featured Books</h2>
          <Link href="/login" className="text-blue-600 font-medium flex items-center hover:underline">
            View All <BaseIcon path={mdiChevronRight} size={20} />
          </Link>
        </div>

        {loading ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-8">
            {[1, 2, 3, 4].map((i) => (
              <div key={i} className="animate-pulse">
                <div className="bg-slate-200 aspect-[3/4] rounded-2xl mb-4"></div>
                <div className="h-6 bg-slate-200 rounded w-3/4 mb-2"></div>
                <div className="h-4 bg-slate-200 rounded w-1/2"></div>
              </div>
            ))}
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-8">
            {books.map((book: any) => (
              <div key={book.id} className="group bg-white rounded-2xl overflow-hidden border border-slate-100 shadow-sm hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1">
                <Link href={`/book/${book.id}`} className="block">
                  <div className="aspect-[3/4] bg-slate-200 relative overflow-hidden">
                    {book.cover_images?.[0] ? (
                      <img
                        src={`/api/file/download?id=${book.cover_images[0].id}`}
                        alt={book.title}
                        className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                      />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center text-slate-400">
                        <BaseIcon path={mdiBookOpenVariant} size={48} />
                      </div>
                    )}
                    <div className="absolute top-3 right-3 bg-white/90 backdrop-blur-sm px-2 py-1 rounded-lg text-sm font-bold shadow-sm">
                      ${book.price}
                    </div>
                  </div>
                </Link>
                <div className="p-5">
                  <Link href={`/book/${book.id}`} className="block">
                    <h3 className="font-bold text-lg mb-1 truncate group-hover:text-blue-600 transition-colors" title={book.title}>
                      {book.title}
                    </h3>
                  </Link>
                  <p className="text-slate-500 text-sm mb-4 truncate">
                    {book.author?.name || 'Unknown Author'}
                  </p>
                  <div className="flex items-center justify-between">
                    <div className="flex items-center text-yellow-500">
                      <BaseIcon path={mdiStar} size={16} />
                      <span className="ml-1 text-xs font-bold text-slate-700">4.8</span>
                    </div>
                    <Link href={`/book/${book.id}`} className="text-blue-600 p-2 rounded-full hover:bg-blue-50 transition-colors">
                      <BaseIcon path={mdiCart} size={20} />
                    </Link>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </section>

      {/* CTA Section */}
      <section className="bg-blue-600 py-16 my-16">
        <div className="container mx-auto px-4 text-center text-white max-w-3xl">
          <h2 className="text-3xl md:text-4xl font-bold mb-6">Start Your Reading Journey Today</h2>
          <p className="text-blue-100 mb-10 text-lg">
            Join thousands of readers and get access to the world&apos;s best eBooks. Free trial available for new members.
          </p>
          <div className="flex flex-col sm:flex-row items-center justify-center space-y-4 sm:space-y-0 sm:space-x-4">
            <Link href="/register" className="bg-white text-blue-600 px-8 py-3 rounded-full font-bold text-lg hover:bg-blue-50 transition-all shadow-lg w-full sm:w-auto">
              Get Started for Free
            </Link>
            <Link href="/login" className="border-2 border-white/30 text-white px-8 py-3 rounded-full font-bold text-lg hover:bg-white/10 transition-all w-full sm:w-auto">
              View Plans
            </Link>
          </div>
        </div>
      </section>

      {/* Footer */}
      <footer className="bg-white py-12 border-t border-slate-200">
        <div className="container mx-auto px-4 text-center">
          <div className="flex items-center justify-center space-x-2 mb-6">
            <BaseIcon path={mdiBookOpenVariant} size={24} className="text-blue-600" />
            <span className="text-lg font-bold">eBookStore</span>
          </div>
          <p className="text-slate-500 mb-8 max-w-md mx-auto">
            The best place to find and enjoy your favorite digital books.
          </p>
          <div className="flex justify-center space-x-6 text-sm text-slate-500 font-medium">
            <Link href="/privacy-policy" className="hover:text-blue-600">Privacy Policy</Link>
            <Link href="/login" className="hover:text-blue-600">Terms of Service</Link>
            <Link href="/login" className="hover:text-blue-600">Contact Us</Link>
          </div>
          <div className="mt-8 pt-8 border-t border-slate-100 text-slate-400 text-sm">
            © 2026 eBookStore. All rights reserved. Built with Flatlogic.
          </div>
        </div>
      </footer>
    </div>
  );
}

LandingPage.getLayout = function getLayout(page: ReactElement) {
  return <LayoutGuest>{page}</LayoutGuest>;
};