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, DollarSign, Loader2, Filter, X, MoreVertical, CheckCircle, XCircle, AlertCircle, Plus, Trash2, Edit, Users, BarChart2, CreditCard, Wallet } 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',
};

const paymentStatusColors = {
  pending: 'badge-pending',
  paid: 'badge-completed',
  refunded: 'badge-cancelled',
  failed: 'badge-disputed',
};

export default function ProviderDashboard() {
  const { user } = useAuth();
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState('bookings');
  const [bookings, setBookings] = useState([]);
  const [services, setServices] = useState([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [pages, setPages] = useState(1);
  const [total, setTotal] = useState(0);
  const [stats, setStats] = useState({ totalEarnings: 0, completedJobs: 0, pendingBookings: 0, avgRating: 0 });

  useEffect(() => {
    if (user?.role !== 'provider') {
      navigate('/dashboard');
      return;
    }
    loadStats();
  }, [user]);

  useEffect(() => {
    if (activeTab === 'bookings') loadBookings();
    else if (activeTab === 'services') loadServices();
  }, [activeTab, page]);

  const loadStats = async () => {
    try {
      const bookingsRes = await api.get('/bookings?status=completed&limit=100');
      const completedBookings = bookingsRes.data.bookings.filter(b => b.paymentStatus === 'paid');
      const totalEarnings = completedBookings.reduce((sum, b) => sum + parseFloat(b.price), 0);
      const pendingRes = await api.get('/bookings?status=pending&limit=1');
      setStats({
        totalEarnings,
        completedJobs: completedBookings.length,
        pendingBookings: pendingRes.data.total,
        avgRating: user.rating || 0
      });
    } catch (e) {
      console.error('Failed to load stats', e);
    }
  };

  const loadBookings = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({ page, limit: 10 });
      const res = await api.get(`/bookings?${params}`);
      setBookings(res.data.bookings);
      setTotal(res.data.total);
      setPages(res.data.pages);
    } catch (e) {
      toast.error('Failed to load bookings');
    } finally {
      setLoading(false);
    }
  };

  const loadServices = async () => {
    setLoading(true);
    try {
      const res = await api.get('/services?provider=' + user.id);
      setServices(res.data.services);
    } catch (e) {
      toast.error('Failed to load services');
    } finally {
      setLoading(false);
    }
  };

  const handleStatusUpdate = async (bookingId, newStatus) => {
    try {
      await api.put(`/bookings/${bookingId}/status`, { status: newStatus });
      toast.success(`Booking ${newStatus}`);
      loadBookings();
      loadStats();
    } catch (e) {
      toast.error('Failed to update status');
    }
  };

  const handleDeleteService = async (serviceId) => {
    if (!confirm('Are you sure you want to delete this service?')) return;
    try {
      await api.delete(`/services/${serviceId}`);
      toast.success('Service deleted');
      loadServices();
    } catch (e) {
      toast.error('Failed to delete service');
    }
  };

  if (user?.role !== 'provider') {
    return <div className="container py-8">Access denied. Provider account required.</div>;
  }

  return (
    <div className="container py-8">
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-2xl font-bold">Provider Dashboard</h1>
          <p className="text-gray-600">Manage your services, bookings, and earnings</p>
        </div>
        {activeTab === 'services' && (
          <Link to="/services/new" className="btn-primary flex items-center gap-2">
            <Plus className="w-4 h-4" />
            Add Service
          </Link>
        )}
      </div>

      <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div className="card p-6">
          <div className="flex items-center gap-4">
            <div className="w-12 h-12 bg-green-100 rounded-xl flex items-center justify-center">
              <DollarSign className="w-6 h-6 text-green-600" />
            </div>
            <div>
              <p className="text-sm text-gray-600">Total Earnings</p>
              <p className="text-2xl font-bold text-gray-900">${stats.totalEarnings.toFixed(2)}</p>
            </div>
          </div>
        </div>
        <div className="card p-6">
          <div className="flex items-center gap-4">
            <div className="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center">
              <CheckCircle className="w-6 h-6 text-blue-600" />
            </div>
            <div>
              <p className="text-sm text-gray-600">Completed Jobs</p>
              <p className="text-2xl font-bold text-gray-900">{stats.completedJobs}</p>
            </div>
          </div>
        </div>
        <div className="card p-6">
          <div className="flex items-center gap-4">
            <div className="w-12 h-12 bg-yellow-100 rounded-xl flex items-center justify-center">
              <Calendar className="w-6 h-6 text-yellow-600" />
            </div>
            <div>
              <p className="text-sm text-gray-600">Pending Bookings</p>
              <p className="text-2xl font-bold text-gray-900">{stats.pendingBookings}</p>
            </div>
          </div>
        </div>
        <div className="card p-6">
          <div className="flex items-center gap-4">
            <div className="w-12 h-12 bg-purple-100 rounded-xl flex items-center justify-center">
              <Star className="w-6 h-6 text-purple-600 fill-current" />
            </div>
            <div>
              <p className="text-sm text-gray-600">Average Rating</p>
              <p className="text-2xl font-bold text-gray-900">{stats.avgRating?.toFixed(1) || '0.0'}</p>
            </div>
          </div>
        </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">
            <button
              role="tab"
              aria-selected={activeTab === 'bookings'}
              onClick={() => { setActiveTab('bookings'); setPage(1); }}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${activeTab === 'bookings' ? 'bg-primary-600 text-white' : 'text-gray-600 hover:bg-gray-100'}`}
            >
              <Calendar className="w-4 h-4 mr-1 inline" /> Bookings
            </button>
            <button
              role="tab"
              aria-selected={activeTab === 'services'}
              onClick={() => { setActiveTab('services'); setPage(1); }}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${activeTab === 'services' ? 'bg-primary-600 text-white' : 'text-gray-600 hover:bg-gray-100'}`}
            >
              <Users className="w-4 h-4 mr-1 inline" /> My Services
            </button>
            <button
              role="tab"
              aria-selected={activeTab === 'earnings'}
              onClick={() => { setActiveTab('earnings'); setPage(1); }}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${activeTab === 'earnings' ? 'bg-primary-600 text-white' : 'text-gray-600 hover:bg-gray-100'}`}
            >
              <Wallet className="w-4 h-4 mr-1 inline" /> Earnings
            </button>
          </nav>
        </div>

        {activeTab === 'bookings' && (
          <>
            {loading ? (
              <div className="space-y-4 p-6">
                {[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>
            ) : 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">Your bookings will appear here</p>
              </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.user?.name || 'Customer'}</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>
                            <span className={`text-xs px-2 py-0.5 rounded ${paymentStatusColors[booking.paymentStatus]}`}>
                              {booking.paymentStatus}
                            </span>
                          </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" /> Chat
                        </Link>
                        {booking.status === 'pending' && (
                          <>
                            <button onClick={() => handleStatusUpdate(booking._id, 'accepted')} className="btn-primary text-sm">
                              <CheckCircle className="w-4 h-4 mr-1" /> Accept
                            </button>
                            <button onClick={() => handleStatusUpdate(booking._id, 'cancelled')} className="btn-danger text-sm">
                              <XCircle className="w-4 h-4 mr-1" /> Decline
                            </button>
                          </>
                        )}
                        {booking.status === 'accepted' && (
                          <button onClick={() => handleStatusUpdate(booking._id, 'in_progress')} className="btn-primary text-sm">
                            <AlertCircle className="w-4 h-4 mr-1" /> Start Job
                          </button>
                        )}
                        {booking.status === 'in_progress' && (
                          <button onClick={() => handleStatusUpdate(booking._id, 'completed')} className="btn-success text-sm">
                            <CheckCircle className="w-4 h-4 mr-1" /> Complete
                          </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>
            )}
          </>
        )}

        {activeTab === 'services' && (
          <>
            {loading ? (
              <div className="grid md:grid-cols-3 gap-6 p-6">
                {[1,2,3].map(i => (
                  <div key={i} className="card animate-pulse">
                    <div className="aspect-video bg-gray-200" />
                    <div className="p-4 space-y-3">
                      <div className="h-4 bg-gray-200 rounded w-3/4" />
                      <div className="h-4 bg-gray-200 rounded w-1/2" />
                      <div className="h-6 bg-gray-200 rounded w-full" />
                    </div>
                  </div>
                ))}
              </div>
            ) : services.length === 0 ? (
              <div className="p-12 text-center">
                <Users className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                <h3 className="text-lg font-medium text-gray-900">No services yet</h3>
                <p className="text-gray-500 mt-1">Create your first service to start getting bookings</p>
                <Link to="/services/new" className="mt-4 btn-primary inline-block">Add Service</Link>
              </div>
            ) : (
              <div className="grid md:grid-cols-3 gap-6 p-6">
                {services.map(service => (
                  <div key={service._id} 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-4xl">🔧</div>
                      )}
                      <span className="absolute top-2 right-2 badge bg-white/90 backdrop-blur">{service.category}</span>
                    </div>
                    <div className="p-4">
                      <h3 className="font-semibold text-gray-900 line-clamp-1">{service.title}</h3>
                      <p className="text-sm text-gray-500 mt-1 line-clamp-2">{service.description}</p>
                      <div className="flex items-center justify-between mt-3 pt-3 border-t border-gray-100">
                        <div className="text-right">
                          <p className="text-lg font-bold text-primary-600">${service.price}</p>
                          <p className="text-xs text-gray-500">/{service.priceType === 'hourly' ? 'hr' : 'job'}</p>
                        </div>
                      </div>
                      <div className="flex gap-2 mt-4">
                        <Link to={`/services/${service._id}/edit`} className="btn-secondary text-sm flex-1 text-center">
                          <Edit className="w-4 h-4 mr-1" /> Edit
                        </Link>
                        <button onClick={() => handleDeleteService(service._id)} className="btn-danger text-sm flex-1">
                          <Trash2 className="w-4 h-4 mr-1" /> Delete
                        </button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </>
        )}

        {activeTab === 'earnings' && (
          <div className="p-6">
            <div className="card p-6 mb-6">
              <h3 className="font-semibold text-lg mb-4">Earnings Overview</h3>
              <div className="grid md:grid-cols-3 gap-6">
                <div className="text-center p-4 bg-green-50 rounded-xl">
                  <p className="text-sm text-gray-600">This Month</p>
                  <p className="text-3xl font-bold text-green-600 mt-1">${(stats.totalEarnings * 0.3).toFixed(2)}</p>
                </div>
                <div className="text-center p-4 bg-blue-50 rounded-xl">
                  <p className="text-sm text-gray-600">Last Month</p>
                  <p className="text-3xl font-bold text-blue-600 mt-1">${(stats.totalEarnings * 0.25).toFixed(2)}</p>
                </div>
                <div className="text-center p-4 bg-purple-50 rounded-xl">
                  <p className="text-sm text-gray-600">Pending Payout</p>
                  <p className="text-3xl font-bold text-purple-600 mt-1">${(stats.totalEarnings * 0.1).toFixed(2)}</p>
                </div>
              </div>
            </div>
            <div className="card">
              <div className="p-4 border-b border-gray-100">
                <h3 className="font-semibold">Recent Transactions</h3>
              </div>
              <div className="divide-y divide-gray-100">
                {bookings.filter(b => b.paymentStatus === 'paid').slice(0, 10).map(booking => (
                  <div key={booking._id} className="p-4 flex items-center justify-between">
                    <div>
                      <p className="font-medium">{booking.service?.title}</p>
                      <p className="text-sm text-gray-500">{booking.user?.name} • {format(parseISO(booking.completedAt || booking.updatedAt), 'MMM d, yyyy')}</p>
                    </div>
                    <div className="text-right">
                      <p className="font-bold text-green-600">+$${booking.price}</p>
                      <p className="text-xs text-gray-500">Paid</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}