import { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { api } from '../context/AuthContext';
import { Calendar, MapPin, Clock, Star, MessageSquare, CreditCard, Loader2, Filter, X, MoreVertical, CheckCircle, XCircle, AlertCircle } from 'lucide-react';
import { format, parseISO } from 'date-fns';
import toast from 'react-hot-toast';

const statusColors = {
  pending: 'badge-pending',
  accepted: 'badge-accepted',
  in_progress: 'badge-in_progress',
  completed: 'badge-completed',
  cancelled: 'badge-cancelled',
  disputed: 'badge-disputed',
};

export default function Dashboard() {
  const { user } = useAuth();
  const navigate = useNavigate();
  const [bookings, setBookings] = useState([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('all');
  const [page, setPage] = useState(1);
  const [pages, setPages] = useState(1);
  const [total, setTotal] = useState(0);

  useEffect(() => {
    const params = new URLSearchParams({ page, limit: 10 });
    if (activeTab !== 'all') params.set('status', activeTab);
    setLoading(true);
    api.get(`/bookings?${params}`).then(res => {
      setBookings(res.data.bookings);
      setTotal(res.data.total);
      setPages(res.data.pages);
      setLoading(false);
    }).catch(() => setLoading(false));
  }, [activeTab, page]);

  const handleCancel = async (bookingId) => {
    if (!confirm('Are you sure you want to cancel this booking?')) return;
    try {
      await api.put(`/bookings/${bookingId}/status`, { status: 'cancelled' });
      toast.success('Booking cancelled');
      setBookings(prev => prev.map(b => b._id === bookingId ? { ...b, status: 'cancelled' } : b));
    } catch {
      toast.error('Failed to cancel');
    }
  };

  const handlePay = (bookingId) => {
    navigate(`/checkout/${bookingId}`);
  };

  const tabs = [
    { id: 'all', label: 'All' },
    { id: 'pending', label: 'Pending' },
    { id: 'accepted', label: 'Confirmed' },
    { id: 'in_progress', label: 'In Progress' },
    { id: 'completed', label: 'Completed' },
    { id: 'cancelled', label: 'Cancelled' },
  ];

  if (loading) {
    return (
      <div className="container py-8">
        <div className="flex items-center justify-between mb-6">
          <h1 className="text-2xl font-bold">My Bookings</h1>
        </div>
        <div className="space-y-4">
          {[1,2,3].map(i => (
            <div key={i} className="card animate-pulse p-6">
              <div className="flex gap-4">
                <div className="w-24 h-24 bg-gray-200 rounded-lg" />
                <div className="flex-1 space-y-3">
                  <div className="h-4 bg-gray-200 rounded w-1/2" />
                  <div className="h-4 bg-gray-200 rounded w-1/3" />
                  <div className="h-4 bg-gray-200 rounded w-1/4" />
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="container py-8">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold">My Bookings</h1>
          <p className="text-gray-600">{total} total bookings</p>
        </div>
      </div>

      <div className="card overflow-hidden">
        <div className="border-b border-gray-100 overflow-x-auto">
          <nav className="flex gap-1 p-1 min-w-max" role="tablist">
            {tabs.map(tab => (
              <button
                key={tab.id}
                role="tab"
                aria-selected={activeTab === tab.id}
                onClick={() => { setActiveTab(tab.id); setPage(1); }}
                className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${activeTab === tab.id ? 'bg-primary-600 text-white' : 'text-gray-600 hover:bg-gray-100'}`}
              >
                {tab.label}
              </button>
            ))}
          </nav>
        </div>

        {bookings.length === 0 ? (
          <div className="p-12 text-center">
            <Calendar className="w-16 h-16 text-gray-300 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900">No bookings found</h3>
            <p className="text-gray-500 mt-1">{activeTab !== 'all' ? `No ${activeTab} bookings` : 'Start by booking a service'}</p>
            <Link to="/services" className="mt-4 btn-primary inline-block">Browse Services</Link>
          </div>
        ) : (
          <div className="divide-y divide-gray-100">
            {bookings.map(booking => (
              <div key={booking._id} className="p-6 hover:bg-gray-50 transition-colors">
                <div className="flex flex-col sm:flex-row sm:items-center gap-4">
                  <div className="w-24 h-24 sm:w-24 sm:h-24 flex-shrink-0 rounded-lg bg-gray-100 overflow-hidden relative">
                    {booking.service?.images?.[0] ? (
                      <img src={booking.service.images[0]} alt={booking.service.title} className="w-full h-full object-cover" />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center text-3xl">🔧</div>
                    )}
                    <span className={`absolute bottom-1 right-1 text-xs px-2 py-0.5 rounded ${statusColors[booking.status]}`}>
                      {booking.status.replace('_', ' ')}
                    </span>
                  </div>

                  <div className="flex-1 min-w-0">
                    <div className="flex items-start justify-between gap-4">
                      <div>
                        <Link to={`/bookings/${booking._id}`} className="font-semibold text-gray-900 hover:text-primary-600">
                          {booking.service?.title || 'Service'}
                        </Link>
                        <p className="text-sm text-gray-500 mt-1">{booking.provider?.name || 'Provider'}</p>
                        <div className="flex flex-wrap gap-3 mt-2 text-sm text-gray-600">
                          <span className="flex items-center gap-1"><Calendar className="w-4 h-4" /> {format(parseISO(booking.scheduledAt), 'MMM d, yyyy')}</span>
                          <span className="flex items-center gap-1"><Clock className="w-4 h-4" /> {format(parseISO(booking.scheduledAt), 'h:mm a')}</span>
                          <span className="flex items-center gap-1"><MapPin className="w-4 h-4" /> {booking.address}</span>
                        </div>
                      </div>
                      <div className="text-right sm:pl-4">
                        <p className="text-lg font-bold text-primary-600">${booking.price}</p>
                        <p className="text-xs text-gray-500">/{booking.service?.priceType === 'hourly' ? 'hr' : 'job'}</p>
                      </div>
                    </div>
                  </div>

                  <div className="flex flex-wrap gap-2 sm:ml-auto">
                    <Link to={`/bookings/${booking._id}`} className="btn-secondary text-sm">
                      <MessageSquare className="w-4 h-4 mr-1" /> Details
                    </Link>
                    {booking.status === 'pending' && (
                      <button onClick={() => handleCancel(booking._id)} className="btn-danger text-sm">
                        <XCircle className="w-4 h-4 mr-1" /> Cancel
                      </button>
                    )}
                    {booking.status === 'accepted' && booking.paymentStatus === 'pending' && (
                      <button onClick={() => handlePay(booking._id)} className="btn-primary text-sm">
                        <CreditCard className="w-4 h-4 mr-1" /> Pay
                      </button>
                    )}
                    {booking.status === 'completed' && !booking.reviewed && (
                      <button className="btn-outline text-sm">
                        <Star className="w-4 h-4 mr-1" /> Review
                      </button>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}

        {pages > 1 && (
          <div className="px-6 py-4 border-t border-gray-100 flex items-center justify-center gap-2">
            <button onClick={() => setPage(p => Math.max(1, p - 1))} disabled={page === 1} className="btn-secondary text-sm">Previous</button>
            <span className="text-sm text-gray-600">Page {page} of {pages}</span>
            <button onClick={() => setPage(p => Math.min(pages, p + 1))} disabled={page === pages} className="btn-secondary text-sm">Next</button>
          </div>
        )}
      </div>
    </div>
  );
}