'use client';

import { useState, useEffect } from 'react';
import Header from '@/components/Header';
import Biography from '@/components/Biography';
import AlbumShowcase from '@/components/AlbumShowcase';
import MusicPlayer from '@/components/MusicPlayer';
import PaymentModal from '@/components/PaymentModal';
import PurchaseSuccessModal from '@/components/PurchaseSuccessModal';
import CartSidebar from '@/components/CartSidebar';
import { Album, Purchase } from '@/lib/types';

export default function Home() {
  const [purchasedAlbums, setPurchasedAlbums] = useState<string[]>([]);
  const [purchases, setPurchases] = useState<Purchase[]>([]);
  const [currentAlbum, setCurrentAlbum] = useState<Album | null>(null);
  const [albumToPurchase, setAlbumToPurchase] = useState<Album | null>(null);
  const [showSuccessModal, setShowSuccessModal] = useState(false);
  const [latestPurchase, setLatestPurchase] = useState<Purchase | null>(null);
  const [cartOpen, setCartOpen] = useState(false);

  // Load purchases from localStorage on mount
  useEffect(() => {
    const savedPurchases = localStorage.getItem('purchases');
    if (savedPurchases) {
      const parsedPurchases = JSON.parse(savedPurchases);
      setPurchases(parsedPurchases);
      setPurchasedAlbums(parsedPurchases.map((p: Purchase) => p.albumId));
    }
  }, []);

  const handlePlayAlbum = (album: Album) => {
    setCurrentAlbum(album);
  };

  const handlePurchaseClick = (album: Album) => {
    setAlbumToPurchase(album);
  };

  const handlePurchaseSuccess = (albumId: string, transactionId: string) => {
    const purchase: Purchase = {
      albumId,
      transactionId,
      purchaseDate: new Date(),
    };

    const updatedPurchases = [...purchases, purchase];
    setPurchases(updatedPurchases);
    setPurchasedAlbums([...purchasedAlbums, albumId]);
    setLatestPurchase(purchase);

    // Save to localStorage
    localStorage.setItem('purchases', JSON.stringify(updatedPurchases));

    // Close payment modal and show success modal
    setAlbumToPurchase(null);
    setShowSuccessModal(true);
  };

  const handleCloseSuccessModal = () => {
    setShowSuccessModal(false);
    // Automatically open the player with the purchased album
    if (albumToPurchase) {
      setCurrentAlbum(albumToPurchase);
    }
  };

  return (
    <>
      <Header onCartClick={() => setCartOpen(true)} />

      <main className="pt-20">
        {/* Hero Section */}
        <section className="min-h-[60vh] flex items-center justify-center px-4 md:px-8 relative overflow-hidden">
          {/* Animated Background */}
          <div className="absolute inset-0 overflow-hidden">
            <div className="absolute top-1/4 left-1/4 w-96 h-96 bg-accent-cyan/10 rounded-full blur-3xl animate-pulse"></div>
            <div className="absolute bottom-1/4 right-1/4 w-96 h-96 bg-accent-orange/10 rounded-full blur-3xl animate-pulse" style={{ animationDelay: '1s' }}></div>
          </div>

          <div className="relative z-10 text-center max-w-4xl mx-auto">
            <h1 className="text-5xl md:text-7xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-accent-cyan via-white to-accent-orange mb-6">
              Progressive Rock
              <br />
              Reimagined
            </h1>
            <p className="text-xl md:text-2xl text-gray-300 mb-8">
              Explore intricate compositions and sonic landscapes
            </p>
            <button
              onClick={() => {
                const element = document.getElementById('albums');
                element?.scrollIntoView({ behavior: 'smooth' });
              }}
              className="px-8 py-4 bg-gradient-to-r from-accent-cyan to-accent-orange hover:from-accent-cyan/80 hover:to-accent-orange/80 rounded-full font-semibold text-white transition-all glow-cyan text-lg"
            >
              Explore Albums
            </button>
          </div>
        </section>

        {/* Biography Section */}
        <Biography />

        {/* Albums Section */}
        <AlbumShowcase
          purchasedAlbums={purchasedAlbums}
          onPlay={handlePlayAlbum}
          onPurchase={handlePurchaseClick}
        />

        {/* Footer */}
        <footer className="py-12 px-4 md:px-8 border-t border-white/10 mt-20">
          <div className="max-w-7xl mx-auto text-center">
            <p className="text-gray-400">
              &copy; {new Date().getFullYear()} Parsa. All rights reserved.
            </p>
            <p className="text-sm text-gray-500 mt-2">
              Progressive Rock Composer & Producer
            </p>
          </div>
        </footer>
      </main>

      {/* Music Player */}
      {currentAlbum && (
        <MusicPlayer
          album={currentAlbum}
          isPurchased={purchasedAlbums.includes(currentAlbum.id)}
          onClose={() => setCurrentAlbum(null)}
          onPurchase={handlePurchaseClick}
        />
      )}

      {/* Payment Modal */}
      <PaymentModal
        album={albumToPurchase}
        onClose={() => setAlbumToPurchase(null)}
        onSuccess={handlePurchaseSuccess}
      />

      {/* Purchase Success Modal */}
      <PurchaseSuccessModal
        show={showSuccessModal}
        album={albumToPurchase}
        purchase={latestPurchase}
        onClose={handleCloseSuccessModal}
      />

      {/* Cart Sidebar */}
      <CartSidebar isOpen={cartOpen} onClose={() => setCartOpen(false)} />
    </>
  );
}
