'use client';

import React, { useState, useEffect } from 'react';
import { Plus, Search, Filter, ArrowLeft } from 'lucide-react';
import { Role } from '@goodgo/types';
import { useUsersStore } from '../../../stores/users-store';
import { UsersTable, UserForm } from '../../../features/shared/components/users';
import { Button } from '../../../features/shared/components/ui/button';
import { Input } from '../../../features/shared/components/ui/input';
import { Card } from '../../../features/shared/components/ui/card';
import { ResponsiveLayout } from '../../../features/shared/components/layout/responsive-layout';
import { AuthGuard } from '../../../features/shared/middleware/auth-guard';
import { useAuthStore } from '../../../stores/auth-store';
import { useRouter } from 'next/navigation';

/**
 * EN: Admin Users List Page
 * VI: Trang danh sách Users cho Admin
 *
 * Features:
 * - List all users with pagination
 * - Search and filter functionality
 * - Bulk actions (activate/deactivate/delete)
 * - Create new user modal
 * - Edit user modal
 * - Role-based access control
 */
export default function AdminUsersPage() {
  const { user: currentUser } = useAuthStore();
  const router = useRouter();
  const {
    users,
    pagination,
    isLoading,
    error,
    fetchUsers,
    createUser,
    updateUser,
    deleteUser,
    bulkDeleteUsers,
    bulkUpdateUserRoles,
    clearError,
  } = useUsersStore();

  const [searchQuery, setSearchQuery] = useState('');
  const [selectedRole, setSelectedRole] = useState<string>('all');
  const [selectedStatus, setSelectedStatus] = useState<string>('all');
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [editingUser, setEditingUser] = useState<any>(null);

  // Check if current user has admin permissions
  const isAdmin = currentUser?.role === Role.ADMIN || currentUser?.role === Role.SUPER_ADMIN;
  const isSuperAdmin = currentUser?.role === Role.SUPER_ADMIN;

  // Load users on mount and when filters change
  useEffect(() => {
    if (isAdmin) {
      const params = {
        search: searchQuery || undefined,
        role: selectedRole !== 'all' ? (selectedRole as Role) : undefined,
        isActive: selectedStatus !== 'all' ? selectedStatus === 'active' : undefined,
        limit: 20,
      };
      fetchUsers(params as any);
    }
  }, [isAdmin, searchQuery, selectedRole, selectedStatus, fetchUsers]);

  const handleCreateUser = async (userData: any) => {
    try {
      await createUser(userData);
      setShowCreateModal(false);
      clearError();
    } catch (error) {
      // Error is handled in the store
    }
  };

  const handleEditUser = async (userData: any) => {
    if (!editingUser) return;

    try {
      await updateUser(editingUser.id, userData);
      setEditingUser(null);
      clearError();
    } catch (error) {
      // Error is handled in the store
    }
  };

  const handleDeleteUser = async (user: any) => {
    if (confirm(`Are you sure you want to delete ${user.email}?`)) {
      try {
        await deleteUser(user.id);
        clearError();
      } catch (error) {
        // Error is handled in the store
      }
    }
  };

  const handleToggleUserStatus = async (user: any) => {
    try {
      await updateUser(user.id, { isActive: !user.isActive });
      clearError();
    } catch (error) {
      // Error is handled in the store
    }
  };

  const handleBulkAction = async (action: string, userIds: string[]) => {
    const actionMessages = {
      delete: `Are you sure you want to delete ${userIds.length} user(s)?`,
      activate: `Are you sure you want to activate ${userIds.length} user(s)?`,
      deactivate: `Are you sure you want to deactivate ${userIds.length} user(s)?`,
    };

    if (!confirm(actionMessages[action as keyof typeof actionMessages])) {
      return;
    }

    try {
      if (action === 'delete') {
        await bulkDeleteUsers(userIds);
      } else if (action === 'activate' || action === 'deactivate') {
        const updates = userIds.map(id => ({
          id,
          role: users.find(u => u.id === id)?.role || 'USER',
        }));
        // Note: For status changes, we'd need a bulk update status method
        // For now, we'll handle individual updates
        for (const userId of userIds) {
          const user = users.find(u => u.id === userId);
          if (user) {
            await updateUser(userId, { isActive: action === 'activate' });
          }
        }
      }
      clearError();
    } catch (error) {
      // Error is handled in the store
    }
  };

  // Desktop Header
  const desktopHeader = (
    <div className="flex items-center justify-between w-full">
      <div className="flex items-center space-x-4">
        <Button
          variant="ghost"
          size="sm"
          onClick={() => router.back()}
          className="flex items-center space-x-2"
        >
          <ArrowLeft className="w-4 h-4" />
          <span>Back</span>
        </Button>
        <h1 className="text-xl font-semibold text-white">Users Management</h1>
      </div>
      <Button
        onClick={() => setShowCreateModal(true)}
        className="flex items-center space-x-2"
      >
        <Plus className="w-4 h-4" />
        <span>Add User</span>
      </Button>
    </div>
  );

  // Mobile Header
  const mobileHeader = (
    <div className="flex items-center justify-between w-full px-4">
      <div className="flex items-center space-x-3">
        <Button
          variant="ghost"
          size="sm"
          onClick={() => router.back()}
          className="p-2"
        >
          <ArrowLeft className="w-4 h-4 text-white" />
        </Button>
        <h1 className="text-lg font-semibold text-white">Users</h1>
      </div>
      <Button
        variant="ghost"
        size="sm"
        onClick={() => setShowCreateModal(true)}
        className="p-2"
      >
        <Plus className="w-5 h-5 text-white" />
      </Button>
    </div>
  );

  const pageContent = (
    <div className="p-6 max-w-7xl mx-auto">
      {/* Page Title (hidden on mobile, shown in header) */}
      <div className="hidden md:block mb-8">
        <h1 className="text-3xl font-bold text-gray-900">Users Management</h1>
        <p className="text-gray-600 mt-2">
          Manage user accounts, roles, and permissions
        </p>
      </div>

      {/* Filters */}
      <Card className="p-4 mb-6">
        <div className="flex flex-wrap gap-4">
          <div className="flex-1 min-w-[200px]">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
              <Input
                placeholder="Search users..."
                value={searchQuery}
                onChange={setSearchQuery}
                className="pl-10"
              />
            </div>
          </div>

          <select
            value={selectedRole}
            onChange={(e) => setSelectedRole(e.target.value)}
            className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="all">All Roles</option>
            <option value="USER">User</option>
            <option value="ADMIN">Admin</option>
            {isSuperAdmin && <option value="SUPER_ADMIN">Super Admin</option>}
          </select>

          <select
            value={selectedStatus}
            onChange={(e) => setSelectedStatus(e.target.value)}
            className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="all">All Status</option>
            <option value="active">Active</option>
            <option value="inactive">Inactive</option>
          </select>
        </div>
      </Card>

      {/* Error Display */}
      {error && (
        <Card className="p-4 mb-6 bg-red-50 border-red-200">
          <div className="flex items-center justify-between">
            <p className="text-red-800">{error}</p>
            <Button variant="secondary" size="sm" onClick={clearError}>
              Dismiss
            </Button>
          </div>
        </Card>
      )}

      {/* Users Table */}
      <UsersTable
        users={users}
        loading={isLoading}
        onEditUser={setEditingUser}
        onDeleteUser={handleDeleteUser}
        onToggleUserStatus={handleToggleUserStatus}
        onBulkAction={handleBulkAction}
        showBulkActions={isSuperAdmin}
      />

      {/* Pagination Info */}
      {pagination && (
        <div className="mt-6 text-center text-gray-600">
          Showing {users.length} of {pagination.total} users
          (Page {pagination.page} of {pagination.totalPages})
        </div>
      )}

      {/* Create User Modal */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="max-w-md w-full max-h-[90vh] overflow-y-auto">
            <UserForm
              isCreate
              loading={isLoading}
              onSubmit={handleCreateUser}
              onCancel={() => setShowCreateModal(false)}
            />
          </div>
        </div>
      )}

      {/* Edit User Modal */}
      {editingUser && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="max-w-md w-full max-h-[90vh] overflow-y-auto">
            <UserForm
              user={editingUser}
              loading={isLoading}
              onSubmit={handleEditUser}
              onCancel={() => setEditingUser(null)}
            />
          </div>
        </div>
      )}
    </div>
  );

  return (
    <AuthGuard requiredRoles={[Role.ADMIN, Role.SUPER_ADMIN]}>
      <ResponsiveLayout
        header={mobileHeader}
        showHeader={true}
        enablePullToRefresh={true}
        onRefresh={async () => {
          await fetchUsers();
        }}
      >
        {pageContent}
      </ResponsiveLayout>
    </AuthGuard>
  );
}