import React, { useEffect, useState, useRef } from 'react';
import { Plus, Search, Edit, Trash2, X } from 'lucide-react';
import userService, { User } from '../../features/auth/services/userService';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import LoadingButton from '../../shared/components/LoadingButton';
import ErrorMessage from '../../shared/components/ErrorMessage';
import Pagination from '../../shared/components/Pagination';
import useAuthStore from '../../store/useAuthStore';
import { logger } from '../../shared/utils/logger';
import { useApiCall } from '../../shared/hooks/useApiCall';
import { useStepUpAuth } from '../../features/auth/contexts/StepUpAuthContext';

const UserManagementPage: React.FC = () => {
  const { userInfo } = useAuthStore();
  const { openStepUp } = useStepUpAuth();
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showModal, setShowModal] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [deletingUserId, setDeletingUserId] = useState<number | null>(null);
  const pendingSubmitDataRef = useRef<{ data: Record<string, unknown>; isEdit: boolean } | null>(null);
  
  const { execute: executeSubmit, isLoading: isSubmitting } = useApiCall(
    async (data: Record<string, unknown>, isEdit: boolean) => {
      if (isEdit && editingUser) {
        return await userService.updateUser(editingUser.id, data);
      } else {
        return await userService.createUser(data);
      }
    },
    {
      showSuccessToast: true,
      successMessage: (editingUser ? 'User updated' : 'User added') + ' successfully',
      onSuccess: () => {
        setShowModal(false);
        resetForm();
        setTimeout(() => fetchUsers(), 300);
      },
    }
  );
  const [filters, setFilters] = useState({
    search: '',
    role: '',
    status: '',
  });
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalItems, setTotalItems] = useState(0);
  const itemsPerPage = 5;
  const abortControllerRef = useRef<AbortController | null>(null);

  const [formData, setFormData] = useState({
    full_name: '',
    email: '',
    phone_number: '',
    password: '',
    role: 'customer',
    status: 'active',
  });

  useEffect(() => {
    setCurrentPage(1);
  }, [filters]);

  useEffect(() => {
    // Cancel previous request if exists
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }

    // Create new abort controller
    abortControllerRef.current = new AbortController();

    fetchUsers();

    // Cleanup: abort request on unmount
    return () => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filters, currentPage]);

  const fetchUsers = async () => {
    try {
      setLoading(true);
      setError(null);
      logger.debug('Fetching users', { filters, page: currentPage });
      const response = await userService.getUsers({
        ...filters,
        page: currentPage,
        limit: itemsPerPage,
      });
      setUsers(response.data.users);
      if (response.data.pagination) {
        setTotalPages(response.data.pagination.totalPages);
        setTotalItems(response.data.pagination.total);
      }
    } catch (error: unknown) {
      logger.error('Error fetching users', error);
      const errorMessage = getUserFriendlyError(error) || 'Unable to load users list';
      setError(errorMessage);
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!editingUser && (!formData.password || formData.password.trim() === '')) {
      toast.error('Please enter password');
      return;
    }
    
    const submitData: Record<string, unknown> = {
      full_name: formData.full_name,
      email: formData.email,
      phone_number: formData.phone_number,
      role: formData.role,
      status: formData.status,
    };
    
    if (editingUser) {
      if (formData.password && formData.password.trim() !== '') {
        submitData.password = formData.password;
      }
      logger.debug('Updating user', { userId: editingUser.id, updateData: submitData });
    } else {
      submitData.password = formData.password;
      logger.debug('Creating user', { formData: submitData });
    }

    // Store data for retry after step-up
    pendingSubmitDataRef.current = { data: submitData, isEdit: !!editingUser };
    
    try {
      await executeSubmit(submitData, !!editingUser);
    } catch (error: unknown) {
      logger.error('Error submitting user', error);
      
      // Check if step-up authentication is required
      // Check both the original response structure and the modified error from API client
      const errorData = error.response?.data;
      const errorDetail = errorData?.detail;
      
      // Check for step-up required in multiple ways
      const isStepUpRequired = 
        error.requiresStepUp === true ||
        error.stepUpAction !== undefined ||
        (getUserFriendlyError(error) === 403 && 
         (errorDetail?.error === 'step_up_required' ||
          errorData?.error === 'step_up_required' ||
          (typeof errorDetail === 'object' && errorDetail?.error === 'step_up_required') ||
          (typeof errorDetail === 'string' && errorDetail.includes('Step-up authentication required'))));
      
      if (isStepUpRequired) {
        const actionDescription = 
          error.stepUpAction ||
          (typeof errorDetail === 'object' ? errorDetail?.action : null) ||
          errorDetail?.action || 
          (typeof errorDetail === 'string' ? errorDetail : null) ||
          errorDetail?.message || 
          (editingUser ? 'user update' : 'user creation');
        
        logger.debug('Step-up required, opening modal', { 
          actionDescription, 
          error: {
            requiresStepUp: error.requiresStepUp,
            stepUpAction: error.stepUpAction,
            status: getUserFriendlyError(error),
            detail: errorDetail
          }
        });
        
        // Open step-up modal and retry after verification
        try {
          openStepUp(actionDescription, async () => {
            if (pendingSubmitDataRef.current) {
              logger.debug('Retrying request after step-up', { data: pendingSubmitDataRef.current });
              await executeSubmit(
                pendingSubmitDataRef.current.data, 
                pendingSubmitDataRef.current.isEdit
              );
            }
          });
        } catch (err) {
          logger.error('Error opening step-up modal', err);
          // Fallback: show error message
          toast.error('Step-up authentication required. Please verify your identity.');
        }
        return; // Don't show error toast, step-up modal will handle it
      }
    }
  };

  const handleEdit = (user: User) => {
    setEditingUser(user);
    setFormData({
      full_name: user.full_name,
      email: user.email,
      phone_number: user.phone_number || '',
      password: '',
      role: user.role,
      status: user.status || 'active',
    });
    setShowModal(true);
  };

  const handleDelete = async (id: number) => {
    if (userInfo?.id === id) {
      toast.error('You cannot delete your own account');
      return;
    }

    if (!window.confirm('Are you sure you want to delete this user?')) return;
    
    try {
      setDeletingUserId(id);
      logger.debug('Deleting user', { userId: id });
      await userService.deleteUser(id);
      toast.success('User deleted successfully');
      fetchUsers();
    } catch (error: unknown) {
      logger.error('Error deleting user', error);
      toast.error(getUserFriendlyError(error) || 'Unable to delete user');
    } finally {
      setDeletingUserId(null);
    }
  };

  const resetForm = () => {
    setEditingUser(null);
    setFormData({
      full_name: '',
      email: '',
      phone_number: '',
      password: '',
      role: 'customer',
      status: 'active',
    });
  };

  const getRoleBadge = (role: string) => {
    const badges: Record<string, { bg: string; text: string; label: string; border: string }> = {
      admin: { 
        bg: 'bg-gradient-to-r from-rose-50 to-red-50', 
        text: 'text-rose-800', 
        label: 'Admin',
        border: 'border-rose-200'
      },
      staff: { 
        bg: 'bg-gradient-to-r from-blue-50 to-indigo-50', 
        text: 'text-blue-800', 
        label: 'Staff',
        border: 'border-blue-200'
      },
      accountant: {
        bg: 'bg-gradient-to-r from-purple-50 to-violet-50',
        text: 'text-purple-800',
        label: 'Accountant',
        border: 'border-purple-200'
      },
      housekeeping: {
        bg: 'bg-gradient-to-r from-amber-50 to-orange-50',
        text: 'text-amber-800',
        label: 'Housekeeping',
        border: 'border-amber-200'
      },
      customer: { 
        bg: 'bg-gradient-to-r from-emerald-50 to-green-50', 
        text: 'text-emerald-800', 
        label: 'Customer',
        border: 'border-emerald-200'
      },
    };
    const badge = badges[role] || badges.customer;
    return (
      <span className={`px-4 py-1.5 rounded-full text-xs font-semibold border shadow-sm ${badge.bg} ${badge.text} ${badge.border}`}>
        {badge.label}
      </span>
    );
  };

  if (loading) {
    return <Loading />;
  }

  return (
    <div className="space-y-4 sm:space-y-6 md:space-y-8 bg-gradient-to-br from-slate-50 via-white to-slate-50 min-h-screen -m-3 sm:-m-4 md:-m-6 p-4 sm:p-6 md:p-8">
      {}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3 sm:gap-4 animate-fade-in">
        <div>
          <div className="flex items-center gap-2 sm:gap-3 mb-2">
            <div className="h-1 w-12 sm:w-16 bg-gradient-to-r from-amber-400 to-amber-600 rounded-full"></div>
            <h1 className="text-xl sm:text-2xl md:text-2xl font-bold bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 bg-clip-text text-transparent tracking-tight">
              User Management
            </h1>
          </div>
          <p className="text-slate-600 mt-2 sm:mt-3 text-xs sm:text-sm md:text-sm font-light">Manage accounts and permissions</p>
        </div>
        <button
          onClick={() => {
            resetForm();
            setShowModal(true);
          }}
          className="flex items-center gap-2 px-4 sm:px-6 py-2 sm:py-3 bg-gradient-to-r from-amber-500 to-amber-600 text-white rounded-lg sm:rounded-xl font-semibold hover:from-amber-600 hover:to-amber-700 transition-all duration-200 shadow-lg hover:shadow-xl text-xs sm:text-sm w-full sm:w-auto"
        >
          <Plus className="w-4 h-4 sm:w-5 sm:h-5" />
          Add User
        </button>
      </div>

      {}
      <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 p-6 animate-fade-in" style={{ animationDelay: '0.1s' }}>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
          <div className="relative group">
            <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 text-slate-400 w-5 h-5 group-focus-within:text-amber-500 transition-colors" />
            <input
              type="text"
              placeholder="Search by name, email..."
              value={filters.search}
              onChange={(e) => setFilters({ ...filters, search: e.target.value })}
              className="w-full pl-12 pr-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 placeholder-slate-400 font-medium shadow-sm hover:shadow-md"
            />
          </div>
          <select
            value={filters.role}
            onChange={(e) => setFilters({ ...filters, role: e.target.value })}
            className="px-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md cursor-pointer"
          >
            <option value="">All roles</option>
            <option value="admin">Admin</option>
            <option value="staff">Staff</option>
            <option value="accountant">Accountant</option>
            <option value="housekeeping">Housekeeping</option>
            <option value="customer">Customer</option>
          </select>
          <select
            value={filters.status}
            onChange={(e) => setFilters({ ...filters, status: e.target.value })}
            className="px-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md cursor-pointer"
          >
            <option value="">All statuses</option>
            <option value="active">Active</option>
            <option value="inactive">Inactive</option>
          </select>
        </div>
      </div>

      {error && (
        <ErrorMessage
          message={error}
          onDismiss={() => setError(null)}
          className="animate-fade-in"
        />
      )}

      {}
      <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 overflow-hidden animate-fade-in" style={{ animationDelay: '0.2s' }}>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900">
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">
                  Name
                </th>
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">
                  Email
                </th>
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">
                  Phone
                </th>
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">
                  Role
                </th>
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">
                  Created Date
                </th>
                <th className="px-8 py-5 text-right text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-slate-100">
              {users.map((user, index) => (
                <tr 
                  key={user.id} 
                  className="hover:bg-gradient-to-r hover:from-amber-50/30 hover:to-yellow-50/30 transition-all duration-200 group border-b border-slate-100"
                  style={{ animationDelay: `${index * 0.05}s` }}
                >
                  <td className="px-8 py-5 whitespace-nowrap">
                    <div className="text-sm font-semibold text-slate-900">{user.full_name}</div>
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    <div className="text-sm text-slate-700">{user.email}</div>
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    <div className="text-sm text-slate-600">{user.phone_number || 'N/A'}</div>
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    {getRoleBadge(user.role)}
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    <div className="text-sm text-slate-500">
                      {user.created_at ? new Date(user.created_at).toLocaleDateString('en-US') : 'N/A'}
                    </div>
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap text-right">
                    <div className="flex items-center justify-end gap-2">
                      <button
                        onClick={() => handleEdit(user)}
                        className="p-2 rounded-lg text-blue-600 hover:text-blue-700 hover:bg-blue-50 transition-all duration-200 shadow-sm hover:shadow-md border border-blue-200 hover:border-blue-300"
                        title="Edit"
                      >
                        <Edit className="w-5 h-5" />
                      </button>
                      <LoadingButton
                        onClick={() => handleDelete(user.id)}
                        isLoading={deletingUserId === user.id}
                        disabled={userInfo?.id === user.id || deletingUserId === user.id}
                        variant="danger"
                        size="sm"
                        className="p-2"
                        title="Delete"
                      >
                        <Trash2 className="w-5 h-5" />
                      </LoadingButton>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <Pagination
          currentPage={currentPage}
          totalPages={totalPages}
          onPageChange={setCurrentPage}
          totalItems={totalItems}
          itemsPerPage={itemsPerPage}
        />
      </div>

      {}
      {showModal && (
        <div className="fixed inset-0 bg-black/70 backdrop-blur-md z-50 overflow-y-auto p-3 sm:p-4 animate-fade-in">
          <div className="min-h-full flex items-start justify-center py-8">
            <div className="bg-white rounded-2xl sm:rounded-3xl shadow-2xl w-full max-w-md my-8 max-h-[calc(100vh-4rem)] overflow-hidden border border-slate-200 animate-scale-in">
            {}
            <div className="bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 px-6 py-5 border-b border-slate-700">
              <div className="flex justify-between items-center">
                <div>
                  <h2 className="text-lg sm:text-xl md:text-xl font-bold text-amber-100">
                    {editingUser ? 'Update User' : 'Add New User'}
                  </h2>
                  <p className="text-amber-200/80 text-sm font-light mt-1">
                    {editingUser ? 'Modify user information' : 'Create a new user account'}
                  </p>
                </div>
                <button 
                  onClick={() => setShowModal(false)}
                  className="w-10 h-10 flex items-center justify-center rounded-xl text-amber-100 hover:text-white hover:bg-slate-700/50 transition-all duration-200 border border-slate-600 hover:border-amber-400"
                >
                  <X className="w-6 h-6" />
                </button>
              </div>
            </div>
            
            <div className="overflow-y-auto max-h-[calc(100vh-12rem)]">
              <form onSubmit={handleSubmit} className="p-4 sm:p-6 space-y-4 sm:space-y-5">
                <div>
                  <label className="block text-xs font-semibold text-slate-600 uppercase tracking-wider mb-2">
                    Name
                  </label>
                  <input
                    type="text"
                    value={formData.full_name}
                    onChange={(e) => setFormData({ ...formData, full_name: e.target.value })}
                    className="w-full px-4 py-3 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm"
                    required
                  />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-slate-600 uppercase tracking-wider mb-2">
                    Email
                  </label>
                  <input
                    type="email"
                    value={formData.email}
                    onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                    className="w-full px-4 py-3 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm"
                    required
                  />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-slate-600 uppercase tracking-wider mb-2">
                    Phone Number
                  </label>
                  <input
                    type="tel"
                    value={formData.phone_number}
                    onChange={(e) => setFormData({ ...formData, phone_number: e.target.value })}
                    className="w-full px-4 py-3 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm"
                  />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-slate-600 uppercase tracking-wider mb-2">
                    Password {editingUser && <span className="text-slate-400 normal-case">(leave blank if not changing)</span>}
                  </label>
                  <input
                    type="password"
                    value={formData.password}
                    onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                    className="w-full px-4 py-3 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm"
                    required={!editingUser}
                  />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-slate-600 uppercase tracking-wider mb-2">
                    Role
                  </label>
                  <select
                    value={formData.role}
                    onChange={(e) => setFormData({ ...formData, role: e.target.value })}
                    className="w-full px-4 py-3 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm cursor-pointer"
                    required
                  >
                    <option value="customer">Customer</option>
                    <option value="staff">Staff</option>
                    <option value="accountant">Accountant</option>
                    <option value="housekeeping">Housekeeping</option>
                    <option value="admin">Admin</option>
                  </select>
                </div>
                <div>
                  <label className="block text-xs font-semibold text-slate-600 uppercase tracking-wider mb-2">
                    Status
                  </label>
                  <select
                    value={formData.status}
                    onChange={(e) => setFormData({ ...formData, status: e.target.value })}
                    className="w-full px-4 py-3 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm cursor-pointer"
                    required
                  >
                    <option value="active">Active</option>
                    <option value="inactive">Inactive</option>
                  </select>
                </div>
                <div className="flex flex-col sm:flex-row gap-3 pt-4 border-t border-slate-200">
                  <button
                    type="button"
                    onClick={() => setShowModal(false)}
                    disabled={isSubmitting}
                    className="w-full sm:flex-1 px-6 py-3 border-2 border-slate-300 rounded-xl text-slate-700 font-semibold hover:bg-slate-50 transition-all duration-200 shadow-sm hover:shadow-md disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    Cancel
                  </button>
                  <LoadingButton
                    type="submit"
                    isLoading={isSubmitting}
                    loadingText={editingUser ? 'Updating...' : 'Creating...'}
                    variant="primary"
                    className="flex-1"
                  >
                    {editingUser ? 'Update' : 'Create'}
                  </LoadingButton>
                </div>
              </form>
            </div>
          </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default UserManagementPage;
