import { useState, useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { api } from '../context/AuthContext';
import { Star, MapPin, Clock, Calendar, CheckCircle, Shield, User, MessageSquare, CreditCard, ArrowLeft, Loader2 } from 'lucide-react';
import { format } from 'date-fns';
import toast from 'react-hot-toast';

export default function ServiceDetail() {
  const { id } = useParams();
  const navigate = useNavigate();
  const { user } = useAuth();
  const [service, setService] = useState(null);
  const [loading, setLoading] = useState(true);
  const [bookingLoading, setBookingLoading] = useState(false);
  const [showBooking, setShowBooking] = useState(false);
  const [formData, setFormData] = useState({ scheduledAt: '', address: '', notes: '', duration: 1 });

  useEffect(() => {
    api.get(`/services/${id}`).then(res => { setService(res.data.service); setLoading(false); }).catch(() => { toast.error('Service not found'); navigate('/services'); });
  }, [id, navigate]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!user) { navigate('/login'); return; }
    setBookingLoading(true);
    try {
      await api.post('/bookings', { serviceId: id, ...formData });
      toast.success('Booking requested! Provider will confirm shortly.');
      setShowBooking(false);
      navigate('/dashboard');
    } catch (err) {
      toast.error(err.response?.data?.error || 'Booking failed');
    } finally {
      setBookingLoading(false);
    }
  };

  if (loading) return <div className="min-h-screen flex items-center justify-center"><Loader2 className="w-8 h-8 animate-spin text-primary-600" /></div>;
  if (!service) return null;

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="bg-white border-b border-gray-200">
        <div className="container py-4">
          <Link to="/services" className="inline-flex items-center gap-2 text-sm text-gray-600 hover:text-primary-600">
            <ArrowLeft className="w-4 h-4" />
            Back to Services
          </Link>
        </div>
      </div>

      <div className="container py-8">
        <div className="grid lg:grid-cols-3 gap-8">
          <div className="lg:col-span-2 space-y-6">
            <div className="card overflow-hidden">
              <div className="aspect-video bg-gray-100 relative">
                {service.images?.[0] ? (
                  <img src={service.images[0]} alt={service.title} className="w-full h-full object-cover" />
                ) : (
                  <div className="w-full h-full flex items-center justify-center text-6xl">🔧</div>
                )}
                <div className="absolute top-4 left-4 flex gap-2">
                  <span className="badge bg-primary-600 text-white">{service.category}</span>
                  {service.subcategory && <span className="badge bg-gray-100 text-gray-700">{service.subcategory}</span>}
                </div>
              </div>
              <div className="p-6">
                <div className="flex items-start justify-between">
                  <div>
                    <h1 className="text-2xl font-bold text-gray-900">{service.title}</h1>
                    <div className="flex items-center gap-4 mt-2 text-sm text-gray-600">
                      {service.provider && (
                        <Link to={`/profile/${service.provider._id}`} className="flex items-center gap-2 hover:text-primary-600">
                          {service.provider.avatar ? <img src={service.provider.avatar} alt="" className="w-6 h-6 rounded-full" /> : <div className="w-6 h-6 rounded-full bg-primary-100 flex items-center justify-center text-primary-600 font-medium">{service.provider.name?.[0]}</div>}
                          <span>{service.provider.name}</span>
                        </Link>
                      )}
                      <span className="flex items-center gap-1">
                        <Star className="w-4 h-4 text-yellow-500 fill-current" />
                        {service.rating?.toFixed(1) || '4.5'} ({service.reviewCount || 0} reviews)
                      </span>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className="text-3xl font-bold text-primary-600">${service.price}</p>
                    <p className="text-gray-500">/{service.priceType === 'hourly' ? 'hr' : 'job'}</p>
                  </div>
                </div>

                <div className="mt-6 pt-6 border-t border-gray-100">
                  <h3 className="text-lg font-semibold mb-4">Description</h3>
                  <p className="text-gray-600 leading-relaxed">{service.description || 'No description provided.'}</p>
                </div>

                <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mt-6 pt-6 border-t border-gray-100">
                  <div className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
                    <Clock className="w-5 h-5 text-primary-600" />
                    <div>
                      <p className="text-xs text-gray-500">Duration</p>
                      <p className="font-medium">{service.duration || 1} hour{service.duration !== 1 ? 's' : ''}</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
                    <MapPin className="w-5 h-5 text-primary-600" />
                    <div>
                      <p className="text-xs text-gray-500">Service Area</p>
                      <p className="font-medium text-sm">{service.provider?.address || 'Local area'}</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
                    <CheckCircle className="w-5 h-5 text-primary-600" />
                    <div>
                      <p className="text-xs text-gray-500">Quality</p>
                      <p className="font-medium">Verified Provider</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
                    <Shield className="w-5 h-5 text-primary-600" />
                    <div>
                      <p className="text-xs text-gray-500">Guarantee</p>
                      <p className="font-medium">Satisfaction Guaranteed</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {service.provider && (
              <div className="card p-6">
                <h3 className="text-lg font-semibold mb-4">About the Provider</h3>
                <div className="flex items-start gap-4">
                  <div className="w-16 h-16 rounded-full bg-primary-100 flex items-center justify-center flex-shrink-0">
                    {service.provider.avatar ? <img src={service.provider.avatar} alt="" className="w-16 h-16 rounded-full" /> : <span className="text-2xl font-bold text-primary-600">{service.provider.name?.[0]}</span>}
                  </div>
                  <div className="flex-1">
                    <h4 className="font-semibold text-gray-900">{service.provider.name}</h4>
                    <p className="text-sm text-gray-500">{service.provider.reviewCount || 0} reviews • {service.provider.rating?.toFixed(1) || '4.5'} rating</p>
                    <div className="flex items-center gap-4 mt-3 text-sm text-gray-600">
                      <span className="flex items-center gap-1"><User className="w-4 h-4" /> Verified</span>
                      <span className="flex items-center gap-1"><MessageSquare className="w-4 h-4" /> Responsive</span>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>

          <div className="lg:col-span-1">
            <div className="card p-6 sticky top-24">
              <h3 className="text-lg font-semibold mb-4">Book This Service</h3>
              <div className="space-y-3 mb-4">
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600">Service Fee</span>
                  <span className="font-medium">${service.price}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-gray-600">Platform Fee</span>
                  <span className="font-medium">${(service.price * 0.1).toFixed(2)}</span>
                </div>
                <div className="border-t border-gray-100 pt-3">
                  <div className="flex justify-between font-semibold">
                    <span>Total</span>
                    <span className="text-primary-600">${(service.price * 1.1).toFixed(2)}</span>
                  </div>
                </div>
              </div>

              {user ? (
                <>
                  <button
                    onClick={() => setShowBooking(true)}
                    className="btn-primary w-full py-3 text-lg"
                    disabled={bookingLoading}
                  >
                    {bookingLoading ? <Loader2 className="w-5 h-5 animate-spin" /> : 'Book Now'}
                  </button>
                  <p className="text-center text-xs text-gray-500 mt-2">Pay securely after provider confirms</p>
                </>
              ) : (
                <button onClick={() => navigate('/login')} className="btn-primary w-full py-3 text-lg">
                  Login to Book
                </button>
              )}

              <div className="mt-6 pt-6 border-t border-gray-100 space-y-3 text-sm">
                <div className="flex items-center gap-2 text-gray-600">
                  <Shield className="w-4 h-4 text-primary-600" />
                  <span>Secure payment via Stripe</span>
                </div>
                <div className="flex items-center gap-2 text-gray-600">
                  <Calendar className="w-4 h-4 text-primary-600" />
                  <span>Free cancellation 24hrs before</span>
                </div>
                <div className="flex items-center gap-2 text-gray-600">
                  <CreditCard className="w-4 h-4 text-primary-600" />
                  <span>Pay after service completion</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {showBooking && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50" onClick={() => setShowBooking(false)}>
          <div className="bg-white rounded-xl max-w-md w-full max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
            <div className="p-6 border-b border-gray-100 flex items-center justify-between">
              <h3 className="text-lg font-semibold">Book Service</h3>
              <button onClick={() => setShowBooking(false)} className="p-1 hover:bg-gray-100 rounded-lg">✕</button>
            </div>
            <form onSubmit={handleSubmit} className="p-6 space-y-4">
              <div>
                <label className="label">Date & Time</label>
                <input type="datetime-local" required value={formData.scheduledAt} onChange={e => setFormData({...formData, scheduledAt: e.target.value})} className="input" min={new Date().toISOString().slice(0,16)} />
              </div>
              <div>
                <label className="label">Duration (hours)</label>
                <select value={formData.duration} onChange={e => setFormData({...formData, duration: Number(e.target.value)})} className="input">
                  {[1,2,3,4,5,6,7,8].map(h => <option key={h} value={h}>{h} hour{h!==1?'s':''}</option>)}
                </select>
              </div>
              <div>
                <label className="label">Service Address</label>
                <textarea required value={formData.address} onChange={e => setFormData({...formData, address: e.target.value})} className="input" rows={3} placeholder="Enter full address" />
              </div>
              <div>
                <label className="label">Notes (optional)</label>
                <textarea value={formData.notes} onChange={e => setFormData({...formData, notes: e.target.value})} className="input" rows={2} placeholder="Any special instructions..." />
              </div>
              <div className="flex gap-3 pt-4">
                <button type="button" onClick={() => setShowBooking(false)} className="btn-secondary flex-1">Cancel</button>
                <button type="submit" className="btn-primary flex-1" disabled={bookingLoading}>{bookingLoading ? 'Booking...' : 'Confirm Booking'}</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}