import React, { useEffect, useState } from 'react';
import { useNavigate, useLocation, Link } from 'react-router-dom';
import api from '../../utils/api';
import { Card } from '../../components/ui/card';
import { Button } from '../../components/ui/button';
import { Badge } from '../../components/ui/badge';
import { Input } from '../../components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../components/ui/select';
import { toast } from 'sonner';
import { Users, Search, User, CreditCard, Eye, CheckCircle } from 'lucide-react';
import PaymentActivationDialog from '../../components/PaymentActivationDialog';

const AdminMembers = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [users, setUsers] = useState([]);
  const [filteredUsers, setFilteredUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('active');
  const [paymentDialogOpen, setPaymentDialogOpen] = useState(false);
  const [selectedUserForPayment, setSelectedUserForPayment] = useState(null);

  useEffect(() => {
    fetchMembers();
  }, []);

  useEffect(() => {
    filterUsers();
  }, [users, searchQuery, statusFilter]);

  const fetchMembers = async () => {
    try {
      const response = await api.get('/admin/users');
      // Filter to only members
      const members = response.data.filter(user => user.role === 'member');
      setUsers(members);
    } catch (error) {
      toast.error('Failed to fetch members');
    } finally {
      setLoading(false);
    }
  };

  const filterUsers = () => {
    let filtered = users;

    if (statusFilter && statusFilter !== 'all') {
      filtered = filtered.filter(user => user.status === statusFilter);
    }

    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(user =>
        user.first_name.toLowerCase().includes(query) ||
        user.last_name.toLowerCase().includes(query) ||
        user.email.toLowerCase().includes(query)
      );
    }

    setFilteredUsers(filtered);
  };

  const handleActivatePayment = (user) => {
    setSelectedUserForPayment(user);
    setPaymentDialogOpen(true);
  };

  const handlePaymentSuccess = () => {
    fetchMembers(); // Refresh list
  };

  const getStatusBadge = (status) => {
    const config = {
      pending_email: { label: 'Pending Email', className: 'bg-orange-100 text-orange-700' },
      pending_approval: { label: 'Pending Approval', className: 'bg-gray-200 text-gray-700' },
      pre_approved: { label: 'Pre-Approved', className: 'bg-[#81B29A] text-white' },
      payment_pending: { label: 'Payment Pending', className: 'bg-orange-500 text-white' },
      active: { label: 'Active', className: 'bg-[#81B29A] text-white' },
      inactive: { label: 'Inactive', className: 'bg-gray-400 text-white' }
    };

    const statusConfig = config[status] || config.inactive;
    return (
      <Badge className={`${statusConfig.className} px-3 py-1 rounded-full text-sm`}>
        {statusConfig.label}
      </Badge>
    );
  };

  return (
    <>
      <div className="mb-8">
        <h1 className="text-4xl md:text-5xl font-semibold text-[#422268] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
          Members Management
        </h1>
        <p className="text-lg text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
          Manage paying members and their subscriptions.
        </p>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4 mb-8">
        <Card className="p-6 bg-white rounded-2xl border border-[#ddd8eb]">
          <p className="text-sm text-[#664fa3] mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Total Members</p>
          <p className="text-3xl font-semibold text-[#422268]" style={{ fontFamily: "'Inter', sans-serif" }}>
            {users.length}
          </p>
        </Card>
        <Card className="p-6 bg-white rounded-2xl border border-[#ddd8eb]">
          <p className="text-sm text-[#664fa3] mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Active</p>
          <p className="text-3xl font-semibold text-[#422268]" style={{ fontFamily: "'Inter', sans-serif" }}>
            {users.filter(u => u.status === 'active').length}
          </p>
        </Card>
        <Card className="p-6 bg-white rounded-2xl border border-[#ddd8eb]">
          <p className="text-sm text-[#664fa3] mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Payment Pending</p>
          <p className="text-3xl font-semibold text-[#422268]" style={{ fontFamily: "'Inter', sans-serif" }}>
            {users.filter(u => u.status === 'payment_pending').length}
          </p>
        </Card>
        <Card className="p-6 bg-white rounded-2xl border border-[#ddd8eb]">
          <p className="text-sm text-[#664fa3] mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Inactive</p>
          <p className="text-3xl font-semibold text-[#422268]" style={{ fontFamily: "'Inter', sans-serif" }}>
            {users.filter(u => u.status === 'inactive').length}
          </p>
        </Card>
      </div>

      {/* Filters */}
      <Card className="p-6 bg-white rounded-2xl border border-[#ddd8eb] mb-8">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="relative">
            <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 h-5 w-5 text-[#664fa3]" />
            <Input
              placeholder="Search by name or email..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-12 h-14 rounded-xl border-2 border-[#ddd8eb] focus:border-[#664fa3]"
              data-testid="search-members-input"
            />
          </div>
          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger className="h-14 rounded-xl border-2 border-[#ddd8eb]" data-testid="status-filter-select">
              <SelectValue placeholder="Filter by status" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Statuses</SelectItem>
              <SelectItem value="active">Active</SelectItem>
              <SelectItem value="payment_pending">Payment Pending</SelectItem>
              <SelectItem value="pending_approval">Pending Approval</SelectItem>
              <SelectItem value="pre_approved">Pre-Approved</SelectItem>
              <SelectItem value="inactive">Inactive</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </Card>

      {/* Members List */}
      {loading ? (
        <div className="text-center py-20">
          <p className="text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Loading members...</p>
        </div>
      ) : filteredUsers.length > 0 ? (
        <div className="space-y-4">
          {filteredUsers.map((user) => (
            <Card
              key={user.id}
              className="p-6 bg-white rounded-2xl border border-[#ddd8eb] hover:shadow-md transition-shadow"
              data-testid={`member-card-${user.id}`}
            >
              <div className="flex justify-between items-start flex-wrap gap-4">
                <div className="flex items-start gap-4 flex-1">
                  {/* Avatar */}
                  <div className="h-14 w-14 rounded-full bg-[#DDD8EB] flex items-center justify-center text-[#422268] font-semibold text-lg flex-shrink-0">
                    {user.first_name?.[0]}{user.last_name?.[0]}
                  </div>

                  {/* Info */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-3 mb-2 flex-wrap">
                      <h3 className="text-xl font-semibold text-[#422268]" style={{ fontFamily: "'Inter', sans-serif" }}>
                        {user.first_name} {user.last_name}
                      </h3>
                      {getStatusBadge(user.status)}
                    </div>
                    <div className="grid md:grid-cols-2 gap-2 text-sm text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                      <p>Email: {user.email}</p>
                      <p>Phone: {user.phone}</p>
                      <p>Joined: {new Date(user.created_at).toLocaleDateString()}</p>
                      {user.referred_by_member_name && (
                        <p>Referred by: {user.referred_by_member_name}</p>
                      )}
                    </div>
                  </div>
                </div>

                {/* Actions */}
                <div className="flex gap-2">
                  <Link to={`/admin/users/${user.id}`}>
                    <Button
                      variant="outline"
                      size="sm"
                      className="border-[#664fa3] text-[#664fa3] hover:bg-[#664fa3] hover:text-white"
                    >
                      <Eye className="h-4 w-4 mr-1" />
                      View Profile
                    </Button>
                  </Link>

                  {/* Show Activate Payment button for payment_pending users */}
                  {user.status === 'payment_pending' && (
                    <Button
                      onClick={() => handleActivatePayment(user)}
                      size="sm"
                      className="bg-[#DDD8EB] text-[#422268] hover:bg-white"
                    >
                      <CheckCircle className="h-4 w-4 mr-1" />
                      Activate Payment
                    </Button>
                  )}

                  {/* Show Subscription button for active users */}
                  {user.status === 'active' && (
                    <Button
                      variant="outline"
                      size="sm"
                      className="border-[#81B29A] text-[#81B29A] hover:bg-[#81B29A] hover:text-white"
                    >
                      <CreditCard className="h-4 w-4 mr-1" />
                      Subscription
                    </Button>
                  )}
                </div>
              </div>
            </Card>
          ))}
        </div>
      ) : (
        <div className="text-center py-20">
          <Users className="h-20 w-20 text-[#ddd8eb] mx-auto mb-6" />
          <h3 className="text-2xl font-semibold text-[#422268] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
            No Members Found
          </h3>
          <p className="text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
            {searchQuery || statusFilter !== 'all'
              ? 'Try adjusting your filters'
              : 'No members yet'}
          </p>
        </div>
      )}

      {/* Payment Activation Dialog */}
      <PaymentActivationDialog
        open={paymentDialogOpen}
        onOpenChange={setPaymentDialogOpen}
        user={selectedUserForPayment}
        onSuccess={handlePaymentSuccess}
      />
    </>
  );
};

export default AdminMembers;
