import React, { useState, useEffect } from 'react';
import { MapPin, Star, Calendar, Tag, Search, Send, Mail, Phone, MessageSquare } from 'lucide-react';
import { testimonials, categories } from '../mockData';
import { destinationsAPI, specialsAPI, contactAPI, newsletterAPI } from '../services/api';
import { Button } from '../components/ui/button';
import { Input } from '../components/ui/input';
import { Textarea } from '../components/ui/textarea';
import { Badge } from '../components/ui/badge';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../components/ui/card';
import { toast } from 'sonner';

const Home = () => {
  const [selectedCategory, setSelectedCategory] = useState('All');
  const [searchQuery, setSearchQuery] = useState('');
  const [contactForm, setContactForm] = useState({ name: '', email: '', message: '' });
  const [newsletterEmail, setNewsletterEmail] = useState('');
  const [destinations, setDestinations] = useState([]);
  const [specials, setSpecials] = useState([]);
  const [loading, setLoading] = useState(true);

  // Fetch destinations and specials on mount
  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      setLoading(true);
      const [destinationsData, specialsData] = await Promise.all([
      destinationsAPI.getAll(),
      specialsAPI.getAll()]
      );
      setDestinations(destinationsData);
      setSpecials(specialsData);
    } catch (error) {
      console.error('Error fetching data:', error);
      toast.error('Failed to load destinations');
    } finally {
      setLoading(false);
    }
  };

  // Get special destinations
  const specialDestinations = specials.map((special) => {
    const dest = destinations.find((d) => d.id === special.destination_id);
    if (!dest) return null;
    return {
      ...dest,
      discount: special.discount,
      endDate: special.end_date,
      highlights: special.highlights,
      specialId: special.id
    };
  }).filter(Boolean);

  // Filter destinations
  const filteredDestinations = destinations.filter((dest) => {
    const matchesCategory = selectedCategory === 'All' || dest.category === selectedCategory;
    const matchesSearch = dest.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    dest.location.toLowerCase().includes(searchQuery.toLowerCase());
    return matchesCategory && matchesSearch;
  });

  const handleContactSubmit = async (e) => {
    e.preventDefault();
    try {
      await contactAPI.submit(contactForm);
      toast.success('Message sent! We\'ll get back to you soon.');
      setContactForm({ name: '', email: '', message: '' });
    } catch (error) {
      toast.error('Failed to send message. Please try again.');
    }
  };

  const handleNewsletterSubmit = async (e) => {
    e.preventDefault();
    try {
      await newsletterAPI.subscribe(newsletterEmail);
      toast.success('Successfully subscribed to our newsletter!');
      setNewsletterEmail('');
    } catch (error) {
      toast.error('Failed to subscribe. Please try again.');
    }
  };

  return (
    <div className="min-h-screen">
      {/* Hero Section */}
      <section id="home" className="relative h-screen flex items-center justify-center overflow-hidden">
        <div
          className="absolute inset-0 z-0"
          style={{
            backgroundImage: 'url(https://images.unsplash.com/photo-1488646953014-85cb44e25828?w=1600&q=80)',
            backgroundSize: 'cover',
            backgroundPosition: 'center'
          }}>

          <div className="absolute inset-0 bg-gradient-to-r from-cyan-900/80 to-blue-900/70"></div>
        </div>
        
        <div className="relative z-10 text-center text-white px-4 max-w-4xl mx-auto">
          <h1 className="text-5xl md:text-7xl font-bold mb-6 animate-in fade-in slide-in-from-bottom duration-700">
            Discover Your Next Adventure
          </h1>
          <p className="text-xl md:text-2xl mb-8 text-cyan-50 animate-in fade-in slide-in-from-bottom duration-700 delay-100">Explore breathtaking destinations around the world with Epic Travel & Expeditions

          </p>
          <div className="flex flex-col sm:flex-row gap-4 justify-center animate-in fade-in slide-in-from-bottom duration-700 delay-200">
            <Button
              size="lg"
              className="bg-cyan-600 hover:bg-cyan-700 text-white px-8 py-6 text-lg"
              onClick={() => document.getElementById('destinations').scrollIntoView({ behavior: 'smooth' })}>

              Explore Destinations
            </Button>
            <Button
              size="lg"
              variant="outline"
              className="border-2 border-white text-white hover:bg-white hover:text-cyan-600 px-8 py-6 text-lg"
              onClick={() => document.getElementById('specials').scrollIntoView({ behavior: 'smooth' })}>

              View Specials
            </Button>
          </div>
        </div>
      </section>

      {/* Specials of the Week */}
      <section id="specials" className="py-20 bg-gradient-to-br from-cyan-50 to-blue-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-12">
            <Badge className="mb-4 bg-cyan-600 text-white">Limited Time Offers</Badge>
            <h2 className="text-4xl md:text-5xl font-bold text-gray-900 mb-4">
              This Week's Special Deals
            </h2>
            <p className="text-xl text-gray-600 max-w-2xl mx-auto">
              Exclusive discounts on handpicked destinations. Book now before these offers expire!
            </p>
          </div>

          {loading ?
          <div className="text-center py-12">
              <p className="text-gray-600">Loading specials...</p>
            </div> :
          specialDestinations.length === 0 ?
          <div className="text-center py-12">
              <p className="text-gray-600">No special offers available at the moment.</p>
            </div> :

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
              {specialDestinations.map((special) =>
            <Card key={special.id} className="overflow-hidden hover:shadow-2xl transition-shadow duration-300 group">
                  <div className="relative overflow-hidden">
                    <img
                  src={special.image}
                  alt={special.name}
                  className="w-full h-64 object-cover group-hover:scale-110 transition-transform duration-500" />

                    <div className="absolute top-4 right-4 bg-red-500 text-white px-4 py-2 rounded-full font-bold text-lg shadow-lg">
                      {special.discount}% OFF
                    </div>
                    <div className="absolute bottom-4 left-4 bg-white/95 backdrop-blur-sm px-3 py-1 rounded-full flex items-center space-x-1">
                      <Star className="w-4 h-4 fill-yellow-400 text-yellow-400" />
                      <span className="font-semibold">{special.rating}</span>
                    </div>
                  </div>
                  <CardHeader>
                    <CardTitle className="text-2xl">{special.name}</CardTitle>
                    <CardDescription className="flex items-center text-base">
                      <MapPin className="w-4 h-4 mr-1" />
                      {special.location}
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    <p className="text-gray-600 mb-4">{special.description}</p>
                    <div className="space-y-2 mb-4">
                      {special.highlights.map((highlight, idx) =>
                  <div key={idx} className="flex items-start space-x-2 text-sm text-gray-700">
                          <Tag className="w-4 h-4 text-cyan-600 mt-0.5 flex-shrink-0" />
                          <span>{highlight}</span>
                        </div>
                  )}
                    </div>
                    <div className="flex items-center justify-between mb-4">
                      <div>
                        <span className="text-gray-500 line-through text-lg">${special.price}</span>
                        <span className="text-3xl font-bold text-cyan-600 ml-2">
                          ${Math.round(special.price * (1 - special.discount / 100))}
                        </span>
                      </div>
                      <div className="flex items-center text-sm text-gray-500">
                        <Calendar className="w-4 h-4 mr-1" />
                        Until {new Date(special.endDate).toLocaleDateString()}
                      </div>
                    </div>
                    <Button className="w-full bg-cyan-600 hover:bg-cyan-700">
                      Book Now
                    </Button>
                  </CardContent>
                </Card>
            )}
            </div>
          }
        </div>
      </section>

      {/* Destinations Gallery */}
      <section id="destinations" className="py-20 bg-white">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-12">
            <h2 className="text-4xl md:text-5xl font-bold text-gray-900 mb-4">
              Explore Our Destinations
            </h2>
            <p className="text-xl text-gray-600 max-w-2xl mx-auto">
              From tropical beaches to bustling cities, find your perfect getaway
            </p>
          </div>

          {/* Search and Filter */}
          <div className="mb-8 flex flex-col md:flex-row gap-4 items-center justify-between">
            <div className="relative w-full md:w-96">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
              <Input
                type="text"
                placeholder="Search destinations..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10" />

            </div>
            <div className="flex gap-2 flex-wrap justify-center">
              {categories.map((category) =>
              <Button
                key={category}
                variant={selectedCategory === category ? "default" : "outline"}
                onClick={() => setSelectedCategory(category)}
                className={selectedCategory === category ? "bg-cyan-600 hover:bg-cyan-700" : ""}>

                  {category}
                </Button>
              )}
            </div>
          </div>

          {/* Destinations Grid */}
          {loading ?
          <div className="text-center py-12">
              <p className="text-gray-600">Loading destinations...</p>
            </div> :

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
              {filteredDestinations.map((destination) =>
            <Card key={destination.id} className="overflow-hidden hover:shadow-xl transition-shadow duration-300 group cursor-pointer">
                <div className="relative overflow-hidden">
                  <img
                  src={destination.image}
                  alt={destination.name}
                  className="w-full h-64 object-cover group-hover:scale-110 transition-transform duration-500" />

                  <div className="absolute top-4 left-4 bg-white/95 backdrop-blur-sm px-3 py-1 rounded-full flex items-center space-x-1">
                    <Star className="w-4 h-4 fill-yellow-400 text-yellow-400" />
                    <span className="font-semibold">{destination.rating}</span>
                  </div>
                  <Badge className="absolute top-4 right-4 bg-cyan-600">
                    {destination.category}
                  </Badge>
                </div>
                <CardHeader>
                  <CardTitle className="text-2xl">{destination.name}</CardTitle>
                  <CardDescription className="flex items-center text-base">
                    <MapPin className="w-4 h-4 mr-1" />
                    {destination.location}
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <p className="text-gray-600 mb-4 line-clamp-3">{destination.description}</p>
                  <div className="flex items-center justify-between">
                    <div>
                      <span className="text-sm text-gray-500">Starting from</span>
                      <div className="text-2xl font-bold text-cyan-600">${destination.price}</div>
                    </div>
                    <Button className="bg-cyan-600 hover:bg-cyan-700">
                      View Details
                    </Button>
                  </div>
                </CardContent>
              </Card>
            )}
          </div>
          }
        </div>
      </section>

      {/* Testimonials */}
      <section id="testimonials" className="py-20 bg-gradient-to-br from-blue-50 to-cyan-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-12">
            <h2 className="text-4xl md:text-5xl font-bold text-gray-900 mb-4">
              What Our Travelers Say
            </h2>
            <p className="text-xl text-gray-600 max-w-2xl mx-auto">
              Real experiences from real adventurers
            </p>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            {testimonials.map((testimonial) =>
            <Card key={testimonial.id} className="hover:shadow-xl transition-shadow duration-300">
                <CardContent className="pt-6">
                  <div className="flex items-center mb-4">
                    <img
                    src={testimonial.image}
                    alt={testimonial.name}
                    className="w-16 h-16 rounded-full object-cover mr-4" />

                    <div>
                      <h4 className="font-semibold text-lg">{testimonial.name}</h4>
                      <p className="text-sm text-gray-500">{testimonial.location}</p>
                    </div>
                  </div>
                  <div className="flex mb-3">
                    {[...Array(testimonial.rating)].map((_, i) =>
                  <Star key={i} className="w-4 h-4 fill-yellow-400 text-yellow-400" />
                  )}
                  </div>
                  <p className="text-gray-600 italic">"{testimonial.text}"</p>
                </CardContent>
              </Card>
            )}
          </div>
        </div>
      </section>

      {/* Contact & Newsletter */}
      <section id="contact" className="py-20 bg-white">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
            {/* Contact Form */}
            <div>
              <h2 className="text-3xl md:text-4xl font-bold text-gray-900 mb-4">
                Get In Touch
              </h2>
              <p className="text-gray-600 mb-8">
                Have questions? We'd love to hear from you. Send us a message and we'll respond as soon as possible.
              </p>
              <form onSubmit={handleContactSubmit} className="space-y-4">
                <div>
                  <Input
                    type="text"
                    placeholder="Your Name"
                    value={contactForm.name}
                    onChange={(e) => setContactForm({ ...contactForm, name: e.target.value })}
                    required />

                </div>
                <div>
                  <Input
                    type="email"
                    placeholder="Your Email"
                    value={contactForm.email}
                    onChange={(e) => setContactForm({ ...contactForm, email: e.target.value })}
                    required />

                </div>
                <div>
                  <Textarea
                    placeholder="Your Message"
                    value={contactForm.message}
                    onChange={(e) => setContactForm({ ...contactForm, message: e.target.value })}
                    rows={5}
                    required />

                </div>
                <Button type="submit" className="w-full bg-cyan-600 hover:bg-cyan-700" size="lg">
                  <Send className="w-5 h-5 mr-2" />
                  Send Message
                </Button>
              </form>

              <div className="mt-8 space-y-4">
                <div className="flex items-center space-x-3 text-gray-700">
                  <Phone className="w-5 h-5 text-cyan-600" />
                  <span>+1 (817) 266-2022</span>
                </div>
                <div className="flex items-center space-x-3 text-gray-700">
                  <Mail className="w-5 h-5 text-cyan-600" />
                  <span>advisor@epictravelexpeditions.com</span>
                </div>
                <div className="flex items-center space-x-3 text-gray-700">
                  <MessageSquare className="w-5 h-5 text-cyan-600" />
                  <span>Live chat available 24/7</span>
                </div>
              </div>
            </div>

            {/* Newsletter */}
            <div className="bg-gradient-to-br from-cyan-600 to-blue-700 rounded-2xl p-8 md:p-12 text-white">
              <h2 className="text-3xl md:text-4xl font-bold mb-4">
                Subscribe to Our Newsletter
              </h2>
              <p className="text-cyan-50 mb-8">
                Get exclusive travel deals, destination guides, and travel tips delivered to your inbox.
              </p>
              <form onSubmit={handleNewsletterSubmit} className="space-y-4">
                <Input
                  type="email"
                  placeholder="Enter your email"
                  value={newsletterEmail}
                  onChange={(e) => setNewsletterEmail(e.target.value)}
                  className="bg-white/20 border-white/30 text-white placeholder:text-cyan-100"
                  required />

                <Button type="submit" className="w-full bg-white text-cyan-600 hover:bg-cyan-50" size="lg">
                  Subscribe Now
                </Button>
              </form>
              <p className="text-sm text-cyan-100 mt-4">
                Join 50,000+ travelers who never miss a deal
              </p>
            </div>
          </div>
        </div>
      </section>
    </div>);

};

export default Home;