import React, { useEffect, useState } from 'react';
import { useNavigate, useLocation } 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, CheckCircle, Clock, Mail, Eye } from 'lucide-react';

const AdminUsers = () => {
  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('all');
  const [resendingUserId, setResendingUserId] = useState(null);

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

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

  const fetchUsers = async () => {
    try {
      const response = await api.get('/admin/users');
      setUsers(response.data);
    } catch (error) {
      toast.error('Failed to fetch users');
    } 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 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>
    );
  };

  const handleAdminResendVerification = async (userId, userEmail) => {
    const confirmed = window.confirm(
      `Resend verification email to ${userEmail}?`
    );

    if (!confirmed) return;

    setResendingUserId(userId);
    try {
      await api.post(`/admin/users/${userId}/resend-verification`);
      toast.success(`Verification email sent to ${userEmail}`);
    } catch (error) {
      const errorMessage = error.response?.data?.detail || 'Failed to send verification email';
      toast.error(errorMessage);
    } finally {
      setResendingUserId(null);
    }
  };

  return (
    <>
      <div className="mb-8">
        <h1 className="text-4xl md:text-5xl font-semibold text-[#422268] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
          User Management
        </h1>
        <p className="text-lg text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
          View and manage all registered users.
        </p>
      </div>

      {/* Filters */}
        <Card className="p-6 bg-white rounded-2xl border border-[#ddd8eb] mb-8">
          <div className="grid 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-users-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="pending_email">Pending Email</SelectItem>
                <SelectItem value="pending_approval">Pending Approval</SelectItem>
                <SelectItem value="pre_approved">Pre-Approved</SelectItem>
                <SelectItem value="payment_pending">Payment Pending</SelectItem>
                <SelectItem value="active">Active</SelectItem>
                <SelectItem value="inactive">Inactive</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </Card>

        {/* Users List */}
        {loading ? (
          <div className="text-center py-20">
            <p className="text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Loading users...</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={`user-card-${user.id}`}
              >
                <div className="flex justify-between items-start flex-wrap gap-4">
                  <div className="flex-1">
                    <div className="flex items-center gap-3 mb-2">
                      <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>Role: <span className="capitalize">{user.role}</span></p>
                      <p>Joined: {new Date(user.created_at).toLocaleDateString()}</p>
                      {user.referred_by_member_name && (
                        <p className="col-span-2">Referred by: {user.referred_by_member_name}</p>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <Button
                      onClick={() => navigate(`/admin/users/${user.id}`)}
                      variant="ghost"
                      size="sm"
                      className="text-[#664fa3] hover:text-[#422268]"
                    >
                      <Eye className="h-4 w-4 mr-1" />
                      View
                    </Button>

                    {!user.email_verified && (
                      <Button
                        onClick={() => handleAdminResendVerification(user.id, user.email)}
                        disabled={resendingUserId === user.id}
                        variant="ghost"
                        size="sm"
                        className="text-[#ff9e77] hover:text-[#664fa3]"
                      >
                        <Mail className="h-4 w-4 mr-1" />
                        {resendingUserId === user.id ? 'Sending...' : 'Resend Verification'}
                      </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 Users Found
            </h3>
            <p className="text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
              {searchQuery || statusFilter !== 'all'
                ? 'Try adjusting your filters'
                : 'No users registered yet'}
            </p>
          </div>
        )}
    </>
  );
};

export default AdminUsers;
