import { useState, useEffect } from 'react';
import { useAuth } from '../context/AuthContext';
import { api } from '../context/AuthContext';
import { Users, DollarSign, ShoppingBag, Calendar, Loader2, Filter, Search, MoreVertical, Edit, Trash2, Shield, Crown, Activity, CreditCard, BarChart2 } from 'lucide-react';
import { format, parseISO } from 'date-fns';
import toast from 'react-hot-toast';

const roleColors = {
  user: 'badge-user',
  provider: 'badge-provider',
  admin: 'badge-admin',
};

const roleIcons = {
  user: Users,
  provider: Shield,
  admin: Crown,
};

export default function AdminPanel() {
  const { user } = useAuth();
  const [stats, setStats] = useState(null);
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [pages, setPages] = useState(1);
  const [total, setTotal] = useState(0);
  const [search, setSearch] = useState('');
  const [roleFilter, setRoleFilter] = useState('');
  const [activeTab, setActiveTab] = useState('overview');

  useEffect(() => {
    if (user?.role !== 'admin') return;
    loadStats();
    loadUsers();
  }, [user, page, search, roleFilter]);

  const loadStats = async () => {
    try {
      const res = await api.get('/admin/stats');
      setStats(res.data);
    } catch (e) {
      console.error('Failed to load stats', e);
    }
  };

  const loadUsers = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({ page, limit: 20 });
      if (roleFilter) params.set('role', roleFilter);
      if (search) params.set('search', search);
      const res = await api.get(`/admin/users?${params}`);
      setUsers(res.data.users);
      setTotal(res.data.total);
      setPages(res.data.pages);
    } catch (e) {
      toast.error('Failed to load users');
    } finally {
      setLoading(false);
    }
  };

  const handleUpdateUser = async (userId, updates) => {
    try {
      await api.put(`/admin/users/${userId}`, updates);
      toast.success('User updated');
      loadUsers();
      loadStats();
    } catch (e) {
      toast.error('Failed to update user');
    }
  };

  const handleDeleteUser = async (userId) => {
    if (!confirm('Are you sure you want to delete this user?')) return;
    try {
      await api.delete(`/admin/users/${userId}`);
      toast.success('User deleted');
      loadUsers();
      loadStats();
    } catch (e) {
      toast.error('Failed to delete user');
    }
  };

  if (user?.role !== 'admin') {
    return <div className="container py-8">Access denied. Admin 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">Admin Panel</h1>
          <p className="text-gray-600">Manage users, providers, and platform analytics</p>
        </div>
      </div>

      <div className="border-b border-gray-100 mb-8">
        <nav className="flex gap-1 p-1 min-w-max" role="tablist">
          <button
            role="tab"
            aria-selected={activeTab === 'overview'}
            onClick={() => setActiveTab('overview')}
            className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${activeTab === 'overview' ? 'bg-primary-600 text-white' : 'text-gray-600 hover:bg-gray-100'}`}
          >
            <Activity className="w-4 h-4 mr-1 inline" /> Overview
          </button>
          <button
            role="tab"
            aria-selected={activeTab === 'users'}
            onClick={() => setActiveTab('users')}
            className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${activeTab === 'users' ? 'bg-primary-600 text-white' : 'text-gray-600 hover:bg-gray-100'}`}
          >
            <Users className="w-4 h-4 mr-1 inline" /> Users
          </button>
          <button
            role="tab"
            aria-selected={activeTab === 'providers'}
            onClick={() => setActiveTab('providers')}
            className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${activeTab === 'providers' ? 'bg-primary-600 text-white' : 'text-gray-600 hover:bg-gray-100'}`}
          >
            <Shield className="w-4 h-4 mr-1 inline" /> Providers
          </button>
          <button
            role="tab"
            aria-selected={activeTab === 'analytics'}
            onClick={() => setActiveTab('analytics')}
            className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${activeTab === 'analytics' ? 'bg-primary-600 text-white' : 'text-gray-600 hover:bg-gray-100'}`}
          >
            <BarChart2 className="w-4 h-4 mr-1 inline" /> Analytics
          </button>
        </nav>
      </div>

      {activeTab === 'overview' && stats && (
        <>
          <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-blue-100 rounded-xl flex items-center justify-center">
                  <Users className="w-6 h-6 text-blue-600" />
                </div>
                <div>
                  <p className="text-sm text-gray-600">Total Users</p>
                  <p className="text-2xl font-bold text-gray-900">{stats.users}</p>
                </div>
              </div>
            </div>
            <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">
                  <Shield className="w-6 h-6 text-green-600" />
                </div>
                <div>
                  <p className="text-sm text-gray-600">Providers</p>
                  <p className="text-2xl font-bold text-gray-900">{stats.providers}</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">
                  <ShoppingBag className="w-6 h-6 text-purple-600" />
                </div>
                <div>
                  <p className="text-sm text-gray-600">Services</p>
                  <p className="text-2xl font-bold text-gray-900">{stats.services}</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">
                  <DollarSign className="w-6 h-6 text-yellow-600" />
                </div>
                <div>
                  <p className="text-sm text-gray-600">Revenue</p>
                  <p className="text-2xl font-bold text-gray-900">${parseFloat(stats.revenue || 0).toFixed(2)}</p>
                </div>
              </div>
            </div>
          </div>

          <div className="card">
            <div className="p-6 border-b border-gray-100">
              <h3 className="font-semibold text-lg">Recent Bookings</h3>
            </div>
            <div className="divide-y divide-gray-100">
              {stats.recentBookings?.map(booking => (
                <div key={booking._id} className="p-4 flex items-center justify-between">
                  <div className="flex items-center gap-4">
                    <div className="w-12 h-12 bg-gray-100 rounded-lg flex items-center justify-center">
                      <ShoppingBag className="w-5 h-5 text-gray-500" />
                    </div>
                    <div>
                      <p className="font-medium">{booking.service?.title}</p>
                      <p className="text-sm text-gray-500">{booking.user?.name} → {booking.provider?.name}</p>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className="font-bold">${booking.price}</p>
                    <p className="text-xs text-gray-500 capitalize">{booking.status}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </>
      )}

      {activeTab === 'users' && (
        <div className="card">
          <div className="p-4 border-b border-gray-100 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <h3 className="font-semibold text-lg">User Management</h3>
            <div className="flex gap-2">
              <input
                type="text"
                placeholder="Search users..."
                value={search}
                onChange={e => { setSearch(e.target.value); setPage(1); }}
                className="input w-64"
              />
              <select
                value={roleFilter}
                onChange={e => { setRoleFilter(e.target.value); setPage(1); }}
                className="input w-40"
              >
                <option value="">All Roles</option>
                <option value="user">Customer</option>
                <option value="provider">Provider</option>
                <option value="admin">Admin</option>
              </select>
            </div>
          </div>
          {loading ? (
            <div className="p-6 space-y-4">
              {[1,2,3,4,5].map(i => (
                <div key={i} className="animate-pulse flex items-center gap-4 p-4">
                  <div className="w-10 h-10 bg-gray-200 rounded-full" />
                  <div className="flex-1">
                    <div className="h-4 bg-gray-200 rounded w-1/4" />
                    <div className="h-3 bg-gray-200 rounded w-1/6 mt-1" />
                  </div>
                  <div className="w-24 h-8 bg-gray-200 rounded" />
                </div>
              ))}
            </div>
          ) : users.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 users found</h3>
            </div>
          ) : (
            <div className="divide-y divide-gray-100">
              {users.map(u => (
                <div key={u._id} className="p-4 flex items-center justify-between">
                  <div className="flex items-center gap-4">
                    <div className="w-10 h-10 bg-primary-100 rounded-full flex items-center justify-center">
                      {u.avatar ? (
                        <img src={u.avatar} alt="" className="w-10 h-10 rounded-full" />
                      ) : (
                        <span className="text-lg font-bold text-primary-600">{u.name?.[0]}</span>
                      )}
                    </div>
                    <div>
                      <p className="font-medium">{u.name}</p>
                      <p className="text-sm text-gray-500">{u.email}</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-4">
                    <span className={`badge ${roleColors[u.role] || 'badge-user'} flex items-center gap-1`}>
                      <roleIcons[u.role] ? <roleIcons[u.role] className="w-3 h-3" /> : null}
                      {u.role}
                    </span>
                    <span className={`badge ${u.is_verified ? 'badge-completed' : 'badge-pending'}`}>
                      {u.is_verified ? 'Verified' : 'Unverified'}
                    </span>
                    <div className="flex gap-1">
                      <button
                        onClick={() => handleUpdateUser(u._id, { is_verified: !u.is_verified })}
                        className="btn-secondary text-sm p-2"
                        title={u.is_verified ? 'Unverify' : 'Verify'}
                      >
                        <Shield className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() => handleDeleteUser(u._id)}
                        className="btn-danger text-sm p-2"
                        title="Delete"
                      >
                        <Trash2 className="w-4 h-4" />
                      </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>
      )}

      {activeTab === 'analytics' && stats && (
        <div className="space-y-6">
          <div className="grid md:grid-cols-3 gap-6">
            <div className="card p-6 text-center">
              <CreditCard className="w-12 h-12 text-primary-600 mx-auto mb-4" />
              <h3 className="font-semibold text-lg">Revenue</h3>
              <p className="text-3xl font-bold text-gray-900 mt-2">${parseFloat(stats.revenue || 0).toFixed(2)}</p>
            </div>
            <div className="card p-6 text-center">
              <Calendar className="w-12 h-12 text-green-600 mx-auto mb-4" />
              <h3 className="font-semibold text-lg">Total Bookings</h3>
              <p className="text-3xl font-bold text-gray-900 mt-2">{stats.bookings}</p>
            </div>
            <div className="card p-6 text-center">
              <Users className="w-12 h-12 text-purple-600 mx-auto mb-4" />
              <h3 className="font-semibold text-lg">Active Users</h3>
              <p className="text-3xl font-bold text-gray-900 mt-2">{stats.users}</p>
            </div>
          </div>
          <div className="card p-6">
            <h3 className="font-semibold text-lg mb-4">Platform Metrics</h3>
            <div className="grid md:grid-cols-4 gap-4 text-center">
              <div className="p-4 bg-gray-50 rounded-xl">
                <p className="text-2xl font-bold text-primary-600">{stats.providers}</p>
                <p className="text-sm text-gray-600">Registered Providers</p>
              </div>
              <div className="p-4 bg-gray-50 rounded-xl">
                <p className="text-2xl font-bold text-primary-600">{stats.services}</p>
                <p className="text-sm text-gray-600">Active Services</p>
              </div>
              <div className="p-4 bg-gray-50 rounded-xl">
                <p className="text-2xl font-bold text-primary-600">{(stats.bookings / Math.max(stats.users, 1)).toFixed(1)}</p>
                <p className="text-sm text-gray-600">Avg Bookings/User</p>
              </div>
              <div className="p-4 bg-gray-50 rounded-xl">
                <p className="text-2xl font-bold text-primary-600">${(stats.revenue / Math.max(stats.bookings, 1)).toFixed(2)}</p>
                <p className="text-sm text-gray-600">Avg Revenue/Booking</p>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}