import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { getServices, getBrands, getAreas, getContact, getAboutCards, getBlogPosts } from '../utils/api';

const HomePage = () => {
  const [services, setServices] = useState([]);
  const [brands, setBrands] = useState([]);
  const [areas, setAreas] = useState([]);
  const [contact, setContact] = useState(null);
  const [aboutCards, setAboutCards] = useState([]);
  const [blogPosts, setBlogPosts] = useState([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    try {
      const [servicesRes, brandsRes, areasRes, contactRes, aboutRes, blogRes] = await Promise.all([
        getServices(),
        getBrands(),
        getAreas(),
        getContact(),
        getAboutCards(),
        getBlogPosts('published')
      ]);
      
      setServices(servicesRes.data);
      setBrands(brandsRes.data);
      setAreas(areasRes.data);
      setContact(contactRes.data);
      setAboutCards(aboutRes.data);
      setBlogPosts(blogRes.data.slice(0, 3)); // Latest 3 posts
    } catch (error) {
      console.error('Error loading data:', error);
    }
  };

  const filteredAreas = areas.map(area => ({
    ...area,
    cities: area.cities.filter(city => 
      city.toLowerCase().includes(searchTerm.toLowerCase())
    )
  })).filter(area => area.cities.length > 0 || searchTerm === '');

  return (
    <div className="min-h-screen">
      <style>{`
        .hero {
          position: relative;
          padding: 170px 0;
          text-align: center;
          color: #ffffff;
          background:
            linear-gradient(
              to bottom,
              rgba(15,23,42,0.45) 0%,
              rgba(15,23,42,0.30) 50%,
              rgba(15,23,42,0.20) 100%
            ),
            url('/assets/img/cc.png') 50% 20% / cover no-repeat;
          overflow: hidden;
        }
        
        .hero h1 {
          font-size: 46px;
          font-weight: 800;
          letter-spacing: -0.5px;
          margin-bottom: 20px;
          text-shadow: 0 10px 40px rgba(0,0,0,0.6);
        }
        
        .hero p {
          font-size: 18px;
          max-width: 720px;
          margin: 0 auto 35px auto;
          opacity: 0.95;
          text-shadow: 0 6px 25px rgba(0,0,0,0.5);
        }
        
        header {
          background: #ffffff;
          position: sticky;
          top: 0;
          z-index: 1000;
          border-bottom: 1px solid #e5e7eb;
        }
        
        .brand {
          display: flex;
          align-items: center;
          gap: 14px;
          text-decoration: none;
        }
        
        .brand img {
          height: 48px;
        }
        
        .brand-main {
          font-size: 22px;
          font-weight: 700;
          color: #0f172a;
          letter-spacing: -0.5px;
        }
        
        .brand-main strong {
          color: #0d6efd;
          font-weight: 800;
        }
        
        .brand-tagline {
          font-size: 12px;
          color: #64748b;
          letter-spacing: 1px;
          text-transform: uppercase;
        }
        
        .card {
          background: #ffffff;
          padding: 35px;
          border-radius: 16px;
          border: 1px solid #e2e8f0;
          text-align: center;
          transition: 0.3s ease;
        }
        
        .card:hover {
          transform: translateY(-6px);
          box-shadow: 0 15px 35px rgba(0,0,0,0.08);
        }
        
        .card::before {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          height: 4px;
          width: 100%;
          background: linear-gradient(90deg,#0d6efd,#1e40af);
          border-top-left-radius: 16px;
          border-top-right-radius: 16px;
        }
        
        .client-box {
          background: #ffffff;
          width: 100%;
          max-width: 200px;
          height: 130px;
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 20px;
          border-radius: 16px;
          border: 1px solid #e2e8f0;
          transition: all .3s ease;
        }
        
        .client-box:hover {
          transform: translateY(-8px);
          box-shadow: 0 25px 50px rgba(13,110,253,0.15);
        }
        
        .client-box img {
          max-width: 140px;
          max-height: 70px;
          width: auto;
          height: auto;
          object-fit: contain;
        }
        
        @media(max-width: 768px) {
          .hero h1 {
            font-size: 30px;
          }
          nav {
            position: absolute;
            top: 70px;
            right: 0;
            background: #ffffff;
            width: 100%;
            display: none;
            flex-direction: column;
            text-align: center;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
            padding: 20px 0;
          }
          nav.active {
            display: flex;
          }
        }
      `}</style>

      {/* Header */}
      <header>
        <div className="max-w-6xl mx-auto px-5 py-4 flex justify-between items-center">
          <Link to="/" className="brand">
            <img src="/assets/img/logo1.png" alt="Logo RH Elektronik" />
            <div>
              <div className="brand-main">
                <strong>RH</strong> Elektronik
              </div>
              <small className="brand-tagline">
                Standar Resmi Brand, Kualitas Terjamin
              </small>
            </div>
          </Link>

          <button 
            className="md:hidden text-2xl"
            onClick={() => setMenuOpen(!menuOpen)}
          >
            ☰
          </button>

          <nav className={`${menuOpen ? 'active' : 'hidden md:flex'} gap-7 items-center`}>
            <a href="#tentang" className="text-gray-800 font-semibold hover:text-blue-600">Tentang</a>
            <a href="#clients" className="text-gray-800 font-semibold hover:text-blue-600">Brand</a>
            <a href="#layanan" className="text-gray-800 font-semibold hover:text-blue-600">Layanan</a>
            <Link to="/blog" className="text-gray-800 font-semibold hover:text-blue-600">Blog</Link>
            <Link to="/shop" className="text-gray-800 font-semibold hover:text-blue-600">🛍️ Shop</Link>
            <Link to="/advertise" className="text-gray-800 font-semibold hover:text-blue-600">📢 Advertise</Link>
            <a href="#kontak" className="text-gray-800 font-semibold hover:text-blue-600">Kontak</a>
            <button 
              onClick={() => setShowModal(true)}
              className="bg-blue-600 text-white px-5 py-2 rounded-lg font-semibold hover:bg-blue-700"
            >
              Registrasi
            </button>
          </nav>
        </div>
      </header>

      {/* Hero */}
      <section className="hero">
        <div className="max-w-6xl mx-auto px-5">
          <h1>Authorized Service Center</h1>
          <p>
            Pusat Layanan Resmi Midea, AQUA, Toshiba, Hisense, Modena, Changhong & CHiQ 
            dengan teknisi tersertifikasi dan standar resmi pabrikan.
          </p>

          <div className="flex justify-center gap-5 flex-wrap mt-8">
            <a 
              href="https://wa.me/6281554333316"
              className="flex items-center gap-3 px-8 py-4 rounded-xl bg-green-500 text-white font-bold shadow-lg hover:shadow-xl hover:-translate-y-1 transition-all min-w-[240px] justify-center"
              data-testid="whatsapp-button"
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="currentColor" viewBox="0 0 24 24">
                <path d="M20.52 3.48A11.91 11.91 0 0012.05 0C5.52 0 .2 5.32.2 11.85c0 2.09.55 4.13 1.6 5.93L0 24l6.39-1.67a11.85 11.85 0 005.66 1.45h.01c6.53 0 11.85-5.32 11.85-11.85 0-3.17-1.23-6.14-3.39-8.45z"/>
              </svg>
              Konsultasi WhatsApp
            </a>

            <button 
              onClick={() => setShowModal(true)}
              className="flex items-center gap-3 px-8 py-4 rounded-xl bg-gradient-to-r from-blue-600 to-blue-800 text-white font-bold shadow-lg hover:shadow-xl hover:-translate-y-1 transition-all min-w-[240px] justify-center"
              data-testid="registration-button"
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="currentColor" viewBox="0 0 24 24">
                <path d="M19 3H5c-1.1 0-2 .9-2 2v14l4-4h12c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/>
              </svg>
              Registrasi Servis
            </button>
          </div>
        </div>
      </section>

      {/* About */}
      <section id="tentang" className="py-20 bg-gradient-to-b from-white to-gray-50">
        <div className="max-w-6xl mx-auto px-5">
          <h2 className="text-center mb-12 text-3xl font-extrabold text-gray-900">Tentang RH Elektronik</h2>
          <div className="grid md:grid-cols-3 gap-8">
            {aboutCards.map((card) => (
              <div key={card.id} className="card relative">
                <h3 className="mb-3 text-lg font-bold">{card.title}</h3>
                <p className="text-gray-600">{card.description}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Brands */}
      <section id="clients" className="py-20 bg-white">
        <div className="max-w-6xl mx-auto px-5">
          <div className="text-center max-w-3xl mx-auto mb-14">
            <h2 className="text-3xl font-extrabold text-gray-900 mb-4">Authorized Brand Partner</h2>
          </div>

          <div className="grid grid-cols-2 md:grid-cols-4 gap-12 justify-items-center">
            {brands.map((brand) => (
              <div key={brand.id} className="client-box">
                <img src={`/${brand.logo_url}`} alt={brand.alt_text} />
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Services */}
      <section id="layanan" className="py-20 bg-gradient-to-b from-gray-50 to-white">
        <div className="max-w-6xl mx-auto px-5">
          <h2 className="text-center mb-12 text-3xl font-extrabold text-gray-900">Layanan Kami</h2>
          <div className="grid md:grid-cols-3 gap-8">
            {services.map((service) => (
              <div key={service.id} className="card relative">
                <div className="text-4xl mb-3">{service.icon}</div>
                <h3 className="mb-3 text-lg font-bold">{service.title}</h3>
                <p className="text-gray-600">{service.description}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Blog Section */}
      {blogPosts.length > 0 && (
        <section className="py-20 bg-gray-50">
          <div className="max-w-6xl mx-auto px-5">
            <div className="flex justify-between items-center mb-12">
              <h2 className="text-3xl font-extrabold text-gray-900">Artikel Terbaru</h2>
              <Link to="/blog" className="text-blue-600 font-semibold hover:text-blue-700" data-testid="view-all-blogs">
                Lihat Semua →
              </Link>
            </div>
            <div className="grid md:grid-cols-3 gap-8">
              {blogPosts.map((post) => (
                <Link 
                  key={post.id} 
                  to={`/blog/${post.id}`}
                  className="bg-white rounded-2xl overflow-hidden shadow-sm hover:shadow-lg transition-all"
                  data-testid={`blog-card-${post.id}`}
                >
                  {post.featured_image && (
                    <img 
                      src={post.featured_image} 
                      alt={post.title}
                      className="w-full h-48 object-cover"
                    />
                  )}
                  <div className="p-6">
                    <h3 className="font-bold text-xl mb-2 text-gray-900">{post.title}</h3>
                    <p className="text-gray-600 text-sm mb-4">{post.excerpt}</p>
                    <div className="flex items-center text-sm text-gray-500">
                      <span>{post.author}</span>
                      <span className="mx-2">•</span>
                      <span>{new Date(post.created_at).toLocaleDateString('id-ID')}</span>
                    </div>
                  </div>
                </Link>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* Areas */}
      <section id="area" className="py-20 bg-gradient-to-b from-gray-50 to-gray-100">
        <div className="max-w-6xl mx-auto px-5">
          <h2 className="text-center mb-12 text-3xl font-extrabold text-gray-900">Area Layanan</h2>
          
          <div className="max-w-md mx-auto mb-10">
            <input 
              type="text"
              placeholder="Cari kota atau kabupaten... contoh: Ciamis"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full px-4 py-3 rounded-xl border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          <div className="grid md:grid-cols-2 gap-6">
            {filteredAreas.map((area) => (
              <div key={area.id} className="bg-white p-6 rounded-2xl shadow-sm">
                <h3 className="font-bold text-xl mb-4 text-gray-900">{area.province}</h3>
                <ul className="grid grid-cols-2 gap-2">
                  {area.cities.map((city, idx) => (
                    <li key={idx} className="text-gray-700 py-1 hover:text-blue-600 cursor-pointer transition">
                      {city}
                    </li>
                  ))}
                </ul>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* CTA */}
      <section className="py-24 text-center bg-gradient-to-br from-blue-50 to-white">
        <h2 className="text-3xl font-extrabold text-gray-900 mb-4">Butuh Layanan Servis Resmi?</h2>
        <p className="text-gray-600 mb-8">Daftarkan unit Anda sekarang atau hubungi tim kami.</p>
        <button 
          onClick={() => setShowModal(true)}
          className="bg-blue-600 text-white px-8 py-4 rounded-xl font-bold shadow-lg hover:bg-blue-700 hover:-translate-y-1 transition-all"
        >
          Registrasi Sekarang
        </button>
      </section>

      {/* Contact */}
      <section id="kontak" className="py-20 bg-gray-50">
        <div className="max-w-6xl mx-auto px-5">
          <h2 className="text-center mb-12 text-3xl font-extrabold text-gray-900">Kontak & Alamat</h2>

          {contact && (
            <div className="grid md:grid-cols-3 gap-8 mb-12">
              <div className="card relative">
                <h3 className="mb-3 text-lg font-bold">🕒 Jam Operasional</h3>
                <p className="text-gray-600 whitespace-pre-line">{contact.hours}</p>
              </div>

              <div className="card relative">
                <h3 className="mb-4 text-lg font-bold">📞 Info Kontak</h3>
                <a 
                  href={`https://wa.me/${contact.phone.replace(/[^0-9]/g, '')}`}
                  className="flex items-center gap-3 px-5 py-3 rounded-full bg-gradient-to-r from-green-500 to-green-600 text-white font-semibold mb-3 hover:shadow-lg transition"
                >
                  <span>📱</span>
                  <span>{contact.phone}</span>
                </a>
                <a 
                  href={`mailto:${contact.email}`}
                  className="flex items-center gap-3 px-5 py-3 rounded-full bg-gradient-to-r from-red-500 to-red-600 text-white font-semibold hover:shadow-lg transition"
                >
                  <span>📧</span>
                  <span className="text-sm">{contact.email}</span>
                </a>
              </div>

              <div className="card relative">
                <h3 className="mb-3 text-lg font-bold">📍 Alamat Kantor Pusat</h3>
                <p className="text-gray-600 whitespace-pre-line">{contact.address}</p>
              </div>
            </div>
          )}

          {contact?.map_embed && (
            <div className="rounded-2xl overflow-hidden shadow-lg">
              <iframe 
                src={contact.map_embed}
                width="100%" 
                height="300" 
                style={{border: 0}} 
                allowFullScreen="" 
                loading="lazy"
                title="Google Maps"
              />
            </div>
          )}
        </div>
      </section>

      {/* Footer */}
      <footer className="bg-gray-900 text-gray-400 text-center py-10">
        <p>© 2026 CV RH Elektronik - Authorized Service Center</p>
        <div className="mt-4">
          <Link to="/admin/login" className="text-blue-400 hover:text-blue-300 text-sm">
            Admin Login
          </Link>
        </div>
      </footer>

      {/* Floating Buttons */}
      <div className="fixed right-5 bottom-5 flex flex-col gap-3 z-50">
        <a 
          href="https://wa.me/6281554333316"
          className="px-5 py-3 rounded-full bg-green-500 text-white font-semibold shadow-lg hover:bg-green-600 transition"
        >
          WhatsApp
        </a>
        <button 
          onClick={() => window.open('https://rhelektronik.com/?modal=laporan', '_blank')}
          className="px-5 py-3 rounded-full bg-blue-600 text-white font-semibold shadow-lg hover:bg-blue-700 transition"
        >
          Laporan Servis
        </button>
      </div>

      {/* Modal */}
      {showModal && (
        <div className="fixed inset-0 bg-black bg-opacity-60 backdrop-blur-sm flex items-center justify-center z-[9999] p-5">
          <div className="relative w-full h-screen max-w-full bg-white rounded-none overflow-hidden">
            <button 
              onClick={() => setShowModal(false)}
              className="fixed top-5 right-8 text-4xl bg-white text-blue-600 w-12 h-12 rounded-full flex items-center justify-center shadow-xl hover:bg-blue-600 hover:text-white transition z-[10000]"
            >
              ×
            </button>
            <iframe 
              src="https://csms.rhelektronik.com/registrasi-servis?embed=1"
              className="w-full h-screen border-0"
              title="Registrasi Servis"
            />
          </div>
        </div>
      )}
    </div>
  );
};

export default HomePage;
