import { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import Link from 'next/link';
import { 
  MapPin, 
  Phone, 
  Mail, 
  Calendar, 
  Package, 
  ShoppingCart, 
  ChevronLeft, 
  ChevronRight,
  MessageCircle,
  Star,
  User,
  Clock,
  CheckCircle,
  XCircle
} from 'lucide-react';

export default function ClassifiedDetailPage() {
  const router = useRouter();
  const { id } = router.query;
  
  const [ad, setAd] = useState(null);
  const [loading, setLoading] = useState(true);
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const [showOrderModal, setShowOrderModal] = useState(false);
  const [reviews, setReviews] = useState([]);
  const [newReview, setNewReview] = useState({ rating: 5, comment: '' });

  // Dummy data
  const dummyAds = [
    {
      id: "1",
      createdAt: "2026-01-10T14:30:00Z",
      city: "New York",
      price: "850",
      condition: "Like New",
      title: "iPhone 15 Pro Max 256GB - Space Black",
      category: "Electronics",
      description: "Selling my iPhone 15 Pro Max in excellent condition. Only 3 months old, comes with original box, charger, and unused accessories. The phone is in pristine condition with no scratches or dents. Battery health is at 100%. Reason for selling: upgraded to a newer model.",
      seller: {
        name: "John Doe",
        phone: "+1 (555) 123-4567",
        email: "john.doe@example.com",
        memberSince: "2024-05-15"
      },
      images: [
        "https://images.unsplash.com/photo-1695048133142-1a20484d2569?w=800&q=80",
        "https://images.unsplash.com/photo-1695048132832-b41495f12eb4?q=80&w=1170&auto=format&fit=crop&ixlib=rb-4.1.0&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
        "https://images.unsplash.com/photo-1704380895316-caa2e4d68a7e?q=80&w=687&auto=format&fit=crop&ixlib=rb-4.1.0&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D"
      ],
      specifications: {
        brand: "Apple",
        model: "iPhone 15 Pro Max",
        storage: "256GB",
        color: "Space Black",
        warranty: "9 months remaining"
      }
    },
    {
      id: "2",
      createdAt: "2026-01-09T10:15:00Z",
      city: "Los Angeles",
      price: "1200",
      condition: "Good",
      title: "MacBook Air M2 2023 - 8GB RAM 256GB SSD",
      category: "Electronics",
      description: "Excellent MacBook Air M2 for sale. Perfect for students and professionals. Runs smoothly, battery lasts all day. Minor wear on the bottom case but screen and keyboard are perfect.",
      seller: {
        name: "Sarah Smith",
        phone: "+1 (555) 234-5678",
        email: "sarah.smith@example.com",
        memberSince: "2023-08-20"
      },
      images: [
        "https://images.unsplash.com/photo-1517336714731-489689fd1ca8?w=800&q=80",
        "https://images.unsplash.com/photo-1517336714731-489689fd1ca8?w=800&q=80",
      ],
      specifications: {
        brand: "Apple",
        model: "MacBook Air M2",
        ram: "8GB",
        storage: "256GB SSD",
        year: "2023"
      }
    }
  ];

  useEffect(() => {
    if (id) {
      fetchAdDetails();
      fetchReviews();
    }
  }, [id]);

  // Auto-slide effect
  useEffect(() => {
    if (ad?.images && ad.images.length > 1) {
      const interval = setInterval(() => {
        setCurrentImageIndex((prev) => (prev + 1) % ad.images.length);
      }, 3000); // Change image every 3 seconds

      return () => clearInterval(interval);
    }
  }, [ad?.images]);

  const fetchAdDetails = async () => {
    setLoading(true);
    try {
      const response = await fetch(`/api/classifieds/ads/${id}`);
      
      if (response.ok) {
        const contentType = response.headers.get('content-type');
        if (contentType && contentType.includes('application/json')) {
          const data = await response.json();
          setAd(data.ad);
        } else {
          throw new Error('Invalid response');
        }
      } else {
        throw new Error('Ad not found');
      }
    } catch (error) {
      console.log('Using dummy data - API endpoint not yet implemented');
      const dummyAd = dummyAds.find(a => a.id === id);
      // setAd(dummyAd || dummyAds[0]);
      setAd(dummyAd || null);
    } finally {
      setLoading(false);
    }
  };

  const fetchReviews = async () => {
    try {
      const response = await fetch(`/api/classifieds/ads/${id}/reviews`);
      if (response.ok) {
        const data = await response.json();
        setReviews(data.reviews || []);
      } else {
        throw new Error('Reviews not found');
      }
    } catch (error) {
      setReviews([
        {
          id: 1,
          userName: "Mike Johnson",
          rating: 5,
          comment: "Great seller! Item exactly as described. Fast response and smooth transaction.",
          createdAt: "2026-01-08T10:00:00Z"
        },
        {
          id: 2,
          userName: "Emily Davis",
          rating: 4,
          comment: "Good product, minor shipping delay but overall satisfied with the purchase.",
          createdAt: "2026-01-07T15:30:00Z"
        }
      ]);
    }
  };

  const handlePlaceOrder = async (orderData) => {
    try {
      const response = await fetch('/api/classifieds/orders', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          adId: id,
          ...orderData
        })
      });

      if (response.ok) {
        const data = await response.json();
        alert('Order placed successfully! The seller will contact you soon.');
        setShowOrderModal(false);
      } else {
        throw new Error('Order failed');
      }
    } catch (error) {
      console.log('Simulating order placement...');
      alert('Order placed successfully! The seller will contact you soon.');
      setShowOrderModal(false);
    }
  };

  const handleSubmitReview = async (e) => {
    e.preventDefault();
    try {
      const response = await fetch(`/api/classifieds/ads/${id}/reviews`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(newReview)
      });

      if (response.ok) {
        fetchReviews();
        setNewReview({ rating: 5, comment: '' });
        alert('Review submitted successfully!');
      }
    } catch (error) {
      alert('Review submitted successfully!');
      setNewReview({ rating: 5, comment: '' });
    }
  };

  const nextImage = () => {
    if (ad?.images) {
      setCurrentImageIndex((prev) => (prev + 1) % ad.images.length);
    }
  };

  const prevImage = () => {
    if (ad?.images) {
      setCurrentImageIndex((prev) => (prev - 1 + ad.images.length) % ad.images.length);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-brand-green"></div>
      </div>
    );
  }

  if (!ad) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <h2 className="text-2xl font-bold text-gray-800 mb-4">Ad not found</h2>
          <Link href="/classifieds">
            <button className="px-6 py-2 bg-brand-green text-white rounded-lg hover:bg-brand-green-dark">
              Back to Classifieds
            </button>
          </Link>
        </div>
      </div>
    );
  }

  const whatsappUrl = `https://wa.me/${ad.seller?.phone?.replace(/[^0-9]/g, '')}?text=${encodeURIComponent(`Hi, I'm interested in: ${ad.title}`)}`;

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <div className="bg-white shadow-sm mb-6">
        <div className="container-full mx-auto px-4 py-4">
          <Link href="/classifieds">
            <button className="flex items-center text-brand-green hover:text-brand-green-dark">
              <ChevronLeft className="w-5 h-5 mr-1" />
              Back to Classifieds
            </button>
          </Link>
        </div>
      </div>

      <div className="container-full mx-auto px-4 pb-8">
        {/* Product Title Section */}
        <div className="bg-white rounded-lg shadow-sm p-6 mb-6">
          <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div>
              <h1 className="text-3xl font-bold text-gray-800 mb-2">{ad.title}</h1>
              <div className="flex flex-wrap items-center gap-4 text-sm text-gray-600">
                <div className="flex items-center gap-1">
                  <Package className="w-4 h-4" />
                  <span>{ad.category}</span>
                </div>
                <div className="flex items-center gap-1">
                  <MapPin className="w-4 h-4" />
                  <span>{ad.city}</span>
                </div>
                <div className="flex items-center gap-1">
                  <Calendar className="w-4 h-4" />
                  <span>Posted: {new Date(ad.createdAt).toLocaleDateString()}</span>
                </div>
              </div>
            </div>
            <div className="text-right">
              <p className="text-sm text-gray-500 mb-1">Price</p>
              <p className="text-4xl font-bold text-brand-green">${ad.price}</p>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Left Column - Images and Details */}
          <div className="lg:col-span-2 space-y-6">
            {/* Image Gallery */}
            <div className="bg-white rounded-lg shadow-sm overflow-hidden">
              <div className="relative h-96 bg-gray-200">
                {ad.images && ad.images.length > 0 ? (
                  <>
                    <img
                      src={ad.images[currentImageIndex]}
                      alt={ad.title}
                      className="w-full h-full object-contain"
                    />
                    {ad.images.length > 1 && (
                      <>
                        <button
                          onClick={prevImage}
                          className="absolute left-4 top-1/2 -translate-y-1/2 bg-white/80 hover:bg-white p-2 rounded-full shadow-lg transition-all"
                        >
                          <ChevronLeft className="w-6 h-6 text-gray-800" />
                        </button>
                        <button
                          onClick={nextImage}
                          className="absolute right-4 top-1/2 -translate-y-1/2 bg-white/80 hover:bg-white p-2 rounded-full shadow-lg transition-all"
                        >
                          <ChevronRight className="w-6 h-6 text-gray-800" />
                        </button>
                        
                        {/* Image Counter */}
                        <div className="absolute bottom-4 right-4 bg-black/60 text-white px-3 py-1 rounded-full text-sm">
                          {currentImageIndex + 1} / {ad.images.length}
                        </div>

                        {/* Slide Indicators */}
                        <div className="absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2">
                          {ad.images.map((_, idx) => (
                            <button
                              key={idx}
                              onClick={() => setCurrentImageIndex(idx)}
                              className={`w-2 h-2 rounded-full transition-all ${
                                currentImageIndex === idx 
                                  ? 'bg-brand-green w-8' 
                                  : 'bg-white/60 hover:bg-white'
                              }`}
                            />
                          ))}
                        </div>
                      </>
                    )}
                  </>
                ) : (
                  <div className="flex items-center justify-center h-full">
                    <Package className="w-24 h-24 text-gray-400" />
                  </div>
                )}
              </div>

              {/* Thumbnail Gallery */}
              {ad.images && ad.images.length > 1 && (
                <div className="flex gap-2 p-4 overflow-x-auto">
                  {ad.images.map((img, idx) => (
                    <button
                      key={idx}
                      onClick={() => setCurrentImageIndex(idx)}
                      className={`flex-shrink-0 w-20 h-20 rounded-lg overflow-hidden border-2 transition-all ${
                        currentImageIndex === idx ? 'border-brand-green' : 'border-gray-200 hover:border-gray-400'
                      }`}
                    >
                      <img src={img} alt={`Thumbnail ${idx + 1}`} className="w-full h-full object-cover" />
                    </button>
                  ))}
                </div>
              )}
            </div>

            {/* Description */}
            <div className="bg-white rounded-lg shadow-sm p-6">
              <h2 className="text-xl font-bold text-gray-800 mb-4">Description</h2>
              <p className="text-gray-700 leading-relaxed whitespace-pre-line">
                {ad.description}
              </p>
            </div>

            {/* Specifications */}
            {ad.specifications && (
              <div className="bg-white rounded-lg shadow-sm p-6">
                <h2 className="text-xl font-bold text-gray-800 mb-4">Specifications</h2>
                <div className="grid grid-cols-2 gap-4">
                  {Object.entries(ad.specifications).map(([key, value]) => (
                    <div key={key} className="border-b border-gray-200 pb-2">
                      <p className="text-sm text-gray-500 capitalize">{key.replace(/([A-Z])/g, ' $1').trim()}</p>
                      <p className="text-gray-800 font-medium">{value}</p>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Reviews Section */}
            <div className="bg-white rounded-lg shadow-sm p-6">
              <h2 className="text-xl font-bold text-gray-800 mb-4">Reviews & Ratings</h2>
              
              {/* Review Form */}
              <form onSubmit={handleSubmitReview} className="mb-6 pb-6 border-b border-gray-200">
                <h3 className="font-semibold text-gray-700 mb-3">Write a Review</h3>
                <div className="mb-4">
                  <label className="block text-sm text-gray-600 mb-2">Rating</label>
                  <div className="flex gap-2">
                    {[1, 2, 3, 4, 5].map((star) => (
                      <button
                        key={star}
                        type="button"
                        onClick={() => setNewReview({ ...newReview, rating: star })}
                        className="focus:outline-none"
                      >
                        <Star
                          className={`w-6 h-6 ${
                            star <= newReview.rating
                              ? 'text-yellow-500 fill-yellow-500'
                              : 'text-gray-300'
                          }`}
                        />
                      </button>
                    ))}
                  </div>
                </div>
                <div className="mb-4">
                  <label className="block text-sm text-gray-600 mb-2">Comment</label>
                  <textarea
                    value={newReview.comment}
                    onChange={(e) => setNewReview({ ...newReview, comment: e.target.value })}
                    className="w-full text-gray-700 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-green"
                    rows="4"
                    placeholder="Share your thougths..."
                    required
                  />
                </div>
                <button
                  type="submit"
                  className="px-6 py-2 bg-brand-green text-white rounded-lg hover:bg-brand-green-dark"
                >
                  Submit Review
                </button>
              </form>

              {/* Reviews List */}
              <div className="space-y-4">
                {reviews.length === 0 ? (
                  <p className="text-gray-500 text-center py-4">No reviews yet. Be the first to review!</p>
                ) : (
                  reviews.map((review) => (
                    <div key={review.id} className="border-b border-gray-200 pb-4">
                      <div className="flex items-start justify-between mb-2">
                        <div className="flex items-center gap-3">
                          <div className="w-10 h-10 bg-brand-green-light rounded-full flex items-center justify-center">
                            <User className="w-5 h-5 text-brand-green-dark" />
                          </div>
                          <div>
                            <p className="font-semibold text-gray-800">{review.userName}</p>
                            <div className="flex items-center gap-2">
                              <div className="flex">
                                {[...Array(5)].map((_, i) => (
                                  <Star
                                    key={i}
                                    className={`w-4 h-4 ${
                                      i < review.rating
                                        ? 'text-yellow-500 fill-yellow-500'
                                        : 'text-gray-300'
                                    }`}
                                  />
                                ))}
                              </div>
                              <span className="text-xs text-gray-500">
                                {new Date(review.createdAt).toLocaleDateString()}
                              </span>
                            </div>
                          </div>
                        </div>
                      </div>
                      <p className="text-gray-700 ml-13">{review.comment}</p>
                    </div>
                  ))
                )}
              </div>
            </div>
          </div>

          {/* Right Column - Price and Actions */}
          <div className="lg:col-span-1">
            <div className="bg-white rounded-lg shadow-sm p-6 sticky top-4 space-y-6">
              {/* Price */}
              <div>
                <p className="text-sm text-gray-500 mb-1">Price</p>
                <p className="text-4xl font-bold text-brand-green">${ad.price}</p>
              </div>

              {/* Condition */}
              <div className="flex items-center justify-between py-3 border-y border-gray-200">
                <span className="text-sm text-gray-600">Condition</span>
                <span className="px-3 py-1 bg-green-100 text-green-700 text-sm font-medium rounded-full">
                  {ad.condition}
                </span>
              </div>

              {/* Location */}
              <div className="flex items-center gap-2 text-gray-700">
                <MapPin className="w-5 h-5 text-gray-500" />
                <span>{ad.city}</span>
              </div>

              {/* Posted Date */}
              <div className="flex items-center gap-2 text-gray-700">
                <Calendar className="w-5 h-5 text-gray-500" />
                <span className="text-sm">
                  Posted: {new Date(ad.createdAt).toLocaleDateString()}
                </span>
              </div>

              {/* Category */}
              {ad.category && (
                <div className="flex items-center gap-2 text-gray-700">
                  <Package className="w-5 h-5 text-gray-500" />
                  <span className="text-sm">{ad.category}</span>
                </div>
              )}

              {/* Action Buttons */}
              <div className="space-y-3 pt-4">
                {/* <button
                  onClick={() => setShowOrderModal(true)}
                  className="w-full px-6 py-3 bg-brand-green text-white rounded-lg hover:bg-brand-green-dark flex items-center justify-center gap-2 font-medium"
                >
                  <ShoppingCart className="w-5 h-5" />
                  Place Order
                </button> */}

                <a 
                  href={whatsappUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="w-full px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center justify-center gap-2 font-medium"
                >
                  <MessageCircle className="w-5 h-5" />
                  WhatsApp
                </a>

                <a 
                  href={`tel:${ad.seller?.phone}`}
                  className="w-full px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center justify-center gap-2 font-medium"
                >
                  <Phone className="w-5 h-5" />
                  Call Now
                </a>
              </div>

              {/* Seller Info */}
              {ad.seller && (
                <div className="pt-6 border-t border-gray-200">
                  <h3 className="font-semibold text-gray-800 mb-4">Seller Information</h3>
                  <div className="space-y-3">
                    <div className="flex items-center gap-2">
                      <User className="w-5 h-5 text-gray-500" />
                      <span className="text-gray-700">{ad.seller.name}</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <Phone className="w-5 h-5 text-gray-500" />
                      <span className="text-gray-700">{ad.seller.phone}</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <Mail className="w-5 h-5 text-gray-500" />
                      <span className="text-gray-700 text-sm">{ad.seller.email}</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <Clock className="w-5 h-5 text-gray-500" />
                      <span className="text-gray-700 text-sm">
                        Member since {new Date(ad.seller.memberSince).toLocaleDateString()}
                      </span>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Order Modal */}
      {showOrderModal && (
        <OrderModal
          ad={ad}
          onClose={() => setShowOrderModal(false)}
          onSubmit={handlePlaceOrder}
        />
      )}
    </div>
  );
}

function OrderModal({ ad, onClose, onSubmit }) {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    address: '',
    message: ''
  });

  const handleSubmit = (e) => {
    e.preventDefault();
    onSubmit(formData);
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg shadow-xl max-w-md w-full max-h-[90vh] overflow-y-auto">
        <div className="p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-2xl font-bold text-gray-800">Place Order</h2>
            <button
              onClick={onClose}
              className="text-gray-500 hover:text-gray-700"
            >
              <XCircle className="w-6 h-6" />
            </button>
          </div>

          {/* Order Summary */}
          <div className="bg-gray-50 rounded-lg p-4 mb-6">
            <h3 className="font-semibold text-gray-700 mb-2">Order Summary</h3>
            <p className="text-sm text-gray-600 mb-1">{ad.title}</p>
            <p className="text-2xl font-bold text-brand-green">${ad.price}</p>
          </div>

          {/* Order Form */}
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Full Name *
              </label>
              <input
                type="text"
                required
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-green"
                placeholder="John Doe"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Email *
              </label>
              <input
                type="email"
                required
                value={formData.email}
                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-green"
                placeholder="john@example.com"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Phone Number *
              </label>
              <input
                type="tel"
                required
                value={formData.phone}
                onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-green"
                placeholder="+1 (555) 123-4567"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Delivery Address *
              </label>
              <textarea
                required
                value={formData.address}
                onChange={(e) => setFormData({ ...formData, address: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-green"
                rows="3"
                placeholder="123 Main St, Apt 4B, City, State, ZIP"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Message (Optional)
              </label>
              <textarea
                value={formData.message}
                onChange={(e) => setFormData({ ...formData, message: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-green"
                rows="2"
                placeholder="Any special instructions..."
              />
            </div>

            <div className="flex gap-3 pt-4">
              <button
                type="button"
                onClick={onClose}
                className="flex-1 px-6 py-3 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
              >
                Cancel
              </button>
              <button
                type="submit"
                className="flex-1 px-6 py-3 bg-brand-green text-white rounded-lg hover:bg-brand-green-dark flex items-center justify-center gap-2"
              >
                <CheckCircle className="w-5 h-5" />
                Confirm Order
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}