import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { ArrowRight, Truck, Shield, Headphones, Wrench, Laptop, Smartphone, Watch } from 'lucide-react';
import { Button } from '../components/ui/button';
import { Badge } from '../components/ui/badge';
import ProductCard from '../components/cards/ProductCard';
import ServiceCard from '../components/cards/ServiceCard';

const API = `${process.env.REACT_APP_BACKEND_URL}/api`;

const Home = () => {
  const [featuredProducts, setFeaturedProducts] = useState([]);
  const [featuredServices, setFeaturedServices] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        // Seed data first
        await axios.post(`${API}/seed`);
        
        const [productsRes, servicesRes] = await Promise.all([
          axios.get(`${API}/products`),
          axios.get(`${API}/services`)
        ]);
        setFeaturedProducts(productsRes.data.slice(0, 4));
        setFeaturedServices(servicesRes.data.slice(0, 3));
      } catch (error) {
        console.error('Failed to fetch data:', error);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  const features = [
    { icon: Truck, title: 'Free Shipping', desc: 'On orders over $100' },
    { icon: Shield, title: 'Warranty', desc: '1 Year manufacturer warranty' },
    { icon: Headphones, title: '24/7 Support', desc: 'Expert assistance anytime' },
    { icon: Wrench, title: 'Expert Repair', desc: 'Certified technicians' },
  ];

  const categories = [
    { icon: Smartphone, name: 'Phones', link: '/products?category=phones' },
    { icon: Laptop, name: 'Laptops', link: '/products?category=laptops' },
    { icon: Watch, name: 'Wearables', link: '/products?category=wearables' },
  ];

  return (
    <div className="min-h-screen">
      {/* Hero Section */}
      <section className="relative overflow-hidden py-16 md:py-24 lg:py-32">
        <div className="max-w-7xl mx-auto px-4 md:px-8">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 items-center">
            {/* Content */}
            <div className="space-y-6 animate-fade-in-up">
              <Badge variant="secondary" className="rounded-full px-4 py-1">
                New Arrivals Available
              </Badge>
              <h1 className="text-4xl sm:text-5xl lg:text-6xl font-bold leading-tight tracking-tight font-['Outfit']">
                Premium Tech,
                <br />
                <span className="text-muted-foreground">Expert Service</span>
              </h1>
              <p className="text-lg text-muted-foreground max-w-lg">
                Discover the latest electronics and get professional repair services. 
                Quality products, trusted solutions for all your tech needs.
              </p>
              <div className="flex flex-wrap gap-4 pt-2">
                <Link to="/products" data-testid="hero-shop-now">
                  <Button size="lg" className="rounded-full px-8 gap-2 btn-press">
                    Shop Now
                    <ArrowRight className="h-5 w-5" />
                  </Button>
                </Link>
                <Link to="/services" data-testid="hero-our-services">
                  <Button size="lg" variant="outline" className="rounded-full px-8">
                    Our Services
                  </Button>
                </Link>
              </div>
            </div>

            {/* Hero Image */}
            <div className="relative animate-fade-in-up stagger-2">
              <div className="relative aspect-square max-w-lg mx-auto">
                <div className="absolute inset-0 bg-gradient-to-br from-primary/10 to-transparent rounded-3xl" />
                <img
                  src="https://images.unsplash.com/photo-1759588071908-fc10a79714fe?w=800"
                  alt="Premium Electronics"
                  className="w-full h-full object-cover rounded-3xl shadow-2xl"
                  data-testid="hero-image"
                />
                {/* Floating Card */}
                <div className="absolute -bottom-4 -left-4 md:-left-8 bg-card border border-border rounded-xl p-4 shadow-lg animate-fade-in-up stagger-3">
                  <p className="text-sm text-muted-foreground">Starting from</p>
                  <p className="text-2xl font-bold font-['Outfit']">$99.99</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Features Bar */}
      <section className="border-y border-border bg-muted/30 py-8">
        <div className="max-w-7xl mx-auto px-4 md:px-8">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
            {features.map((feature, idx) => {
              const Icon = feature.icon;
              return (
                <div key={idx} className="flex items-center gap-3" data-testid={`feature-${idx}`}>
                  <div className="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0">
                    <Icon className="h-5 w-5 text-primary" />
                  </div>
                  <div>
                    <p className="font-medium text-sm font-['Outfit']">{feature.title}</p>
                    <p className="text-xs text-muted-foreground">{feature.desc}</p>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </section>

      {/* Categories */}
      <section className="py-16 md:py-24">
        <div className="max-w-7xl mx-auto px-4 md:px-8">
          <div className="text-center mb-12">
            <h2 className="text-3xl md:text-4xl font-bold font-['Outfit'] mb-4">
              Shop by Category
            </h2>
            <p className="text-muted-foreground max-w-2xl mx-auto">
              Browse our wide selection of premium electronics
            </p>
          </div>
          
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-6">
            {categories.map((cat, idx) => {
              const Icon = cat.icon;
              return (
                <Link
                  key={idx}
                  to={cat.link}
                  className="group relative overflow-hidden rounded-2xl border border-border bg-card p-8 text-center hover:border-primary/50 transition-all hover-lift"
                  data-testid={`category-${cat.name.toLowerCase()}`}
                >
                  <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-primary/10 flex items-center justify-center transition-transform group-hover:scale-110">
                    <Icon className="h-8 w-8 text-primary" />
                  </div>
                  <h3 className="text-xl font-semibold font-['Outfit'] group-hover:text-primary transition-colors">
                    {cat.name}
                  </h3>
                </Link>
              );
            })}
          </div>
        </div>
      </section>

      {/* Featured Products */}
      <section className="py-16 md:py-24 bg-muted/30">
        <div className="max-w-7xl mx-auto px-4 md:px-8">
          <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-12">
            <div>
              <h2 className="text-3xl md:text-4xl font-bold font-['Outfit'] mb-2">
                Featured Products
              </h2>
              <p className="text-muted-foreground">
                Handpicked selection of our best-selling items
              </p>
            </div>
            <Link to="/products" data-testid="view-all-products">
              <Button variant="outline" className="rounded-full gap-2">
                View All
                <ArrowRight className="h-4 w-4" />
              </Button>
            </Link>
          </div>

          {loading ? (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
              {[...Array(4)].map((_, i) => (
                <div key={i} className="rounded-xl border border-border bg-card p-4 animate-pulse">
                  <div className="aspect-square bg-muted rounded-lg mb-4" />
                  <div className="h-4 bg-muted rounded w-2/3 mb-2" />
                  <div className="h-6 bg-muted rounded w-1/2" />
                </div>
              ))}
            </div>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
              {featuredProducts.map((product) => (
                <ProductCard key={product.id} product={product} />
              ))}
            </div>
          )}
        </div>
      </section>

      {/* Services Section */}
      <section className="py-16 md:py-24">
        <div className="max-w-7xl mx-auto px-4 md:px-8">
          <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-12">
            <div>
              <h2 className="text-3xl md:text-4xl font-bold font-['Outfit'] mb-2">
                Our Services
              </h2>
              <p className="text-muted-foreground">
                Professional tech support and repair services
              </p>
            </div>
            <Link to="/services" data-testid="view-all-services">
              <Button variant="outline" className="rounded-full gap-2">
                All Services
                <ArrowRight className="h-4 w-4" />
              </Button>
            </Link>
          </div>

          {loading ? (
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              {[...Array(3)].map((_, i) => (
                <div key={i} className="rounded-xl border border-border bg-card p-6 animate-pulse">
                  <div className="aspect-video bg-muted rounded-lg mb-4" />
                  <div className="h-5 bg-muted rounded w-2/3 mb-2" />
                  <div className="h-4 bg-muted rounded w-full mb-4" />
                  <div className="h-8 bg-muted rounded w-1/3" />
                </div>
              ))}
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              {featuredServices.map((service) => (
                <ServiceCard key={service.id} service={service} />
              ))}
            </div>
          )}
        </div>
      </section>

      {/* CTA Section */}
      <section className="py-16 md:py-24 bg-primary text-primary-foreground">
        <div className="max-w-7xl mx-auto px-4 md:px-8 text-center">
          <h2 className="text-3xl md:text-4xl font-bold font-['Outfit'] mb-4">
            Need Expert Help?
          </h2>
          <p className="text-primary-foreground/80 max-w-2xl mx-auto mb-8">
            Our certified technicians are ready to help you with any tech problem. 
            From repairs to upgrades, we've got you covered.
          </p>
          <div className="flex flex-wrap justify-center gap-4">
            <Link to="/contact" data-testid="cta-contact">
              <Button 
                size="lg" 
                variant="secondary" 
                className="rounded-full px-8 gap-2 btn-press"
              >
                Contact Us
                <ArrowRight className="h-5 w-5" />
              </Button>
            </Link>
            <Link to="/services" data-testid="cta-services">
              <Button 
                size="lg" 
                variant="outline" 
                className="rounded-full px-8 border-primary-foreground/30 text-primary-foreground hover:bg-primary-foreground/10"
              >
                Browse Services
              </Button>
            </Link>
          </div>
        </div>
      </section>
    </div>
  );
};

export default Home;
