<script>
  import { onMount } from 'svelte';
  import { Plus, Trash2, RefreshCw, Search, Users } from 'lucide-svelte';
  import { 
    fetchUsers, 
    fetchUser, 
    createUser, 
    updateUser, 
    deleteUser 
  } from '$lib/api/users.js';
  import { success as toastSuccess, error as toastError } from '$lib/utils/toast.js';
  import { auth } from '$lib/stores/auth.js';
  import DataTable from '$lib/components/DataTable.svelte';
  import Modal from '$lib/components/Modal.svelte';
  import UserFormModal from './UserFormModal.svelte';

  // Search state
  let searchFilters = $state({
    search: '',
    role: '',
    status: ''
  });

  // List state
  let loading = $state(false);
  let users = $state([]);
  let currentPage = $state(1);
  let perPage = $state(20);
  let totalItems = $state(0);
  let totalPages = $state(1);

  // Modal states
  let userForm = $state({
    open: false,
    user: null,
    loading: false
  });

  let deleteModal = $state({
    open: false,
    user: null
  });

  // Load users on mount
  onMount(() => {
    loadUsers();
  });

  async function loadUsers() {
    loading = true;
    
    try {
      const params = { 
        page: currentPage, 
        perPage
      };

      // Add filters
      if (searchFilters.search.trim()) {
        params.search = searchFilters.search.trim();
      }
      if (searchFilters.role) {
        params.role = searchFilters.role;
      }
      if (searchFilters.status) {
        params.status = searchFilters.status;
      }

      const response = await fetchUsers(params);
      users = Array.isArray(response.data) ? response.data : [];

      if (response.pagination) {
        totalItems = response.pagination.total || 0;
        totalPages = Math.ceil(totalItems / perPage) || 1;
      } else {
        totalItems = users.length;
        totalPages = 1;
      }
    } catch (err) {
      toastError(err.message || 'Failed to load users');
      users = [];
    } finally {
      loading = false;
    }
  }

  async function handleSearch() {
    currentPage = 1;
    await loadUsers();
  }

  function handleClear() {
    searchFilters = {
      search: '',
      role: '',
      status: ''
    };
    currentPage = 1;
    loadUsers();
  }

  function handlePageChange(newPage) {
    if (newPage >= 1 && newPage <= totalPages) {
      currentPage = newPage;
      loadUsers();
    }
  }

  // CRUD Operations
  function openCreateModal() {
    userForm = { open: true, user: null, loading: false };
  }

  async function openEditModal(user) {
    userForm = { open: true, user: null, loading: true };
    try {
      const response = await fetchUser(user.UserID);
      userForm = { 
        ...userForm, 
        user: response.data || user, 
        loading: false 
      };
    } catch (err) {
      toastError(err.message || 'Failed to load user details');
      userForm = { 
        ...userForm, 
        user: user, 
        loading: false 
      };
    }
  }

  async function handleSaveUser(formData) {
    userForm.loading = true;
    
    try {
      if (userForm.user) {
        // Update existing user
        await updateUser(userForm.user.UserID, formData);
        toastSuccess('User updated successfully');
      } else {
        // Create new user
        await createUser(formData);
        toastSuccess('User created successfully');
      }
      
      userForm = { open: false, user: null, loading: false };
      await loadUsers();
    } catch (err) {
      toastError(err.message || 'Failed to save user');
      userForm.loading = false;
    }
  }

  function confirmDelete(user) {
    // Prevent self-deletion
    if (user.UserID === $auth.user?.id) {
      toastError('You cannot delete your own account');
      return;
    }
    deleteModal = { open: true, user };
  }

  async function handleDelete() {
    if (!deleteModal.user?.UserID) return;
    
    // Double-check self-deletion prevention
    if (deleteModal.user.UserID === $auth.user?.id) {
      toastError('You cannot delete your own account');
      deleteModal = { open: false, user: null };
      return;
    }
    
    try {
      await deleteUser(deleteModal.user.UserID);
      toastSuccess('User deleted successfully');
      deleteModal = { open: false, user: null };
      await loadUsers();
    } catch (err) {
      toastError(err.message || 'Failed to delete user');
    }
  }

  function handleRefresh() {
    loadUsers();
  }

  const columns = [
    { key: 'Username', label: 'Username', class: 'w-32' },
    { key: 'Name', label: 'Name', class: 'w-40' },
    { key: 'Email', label: 'Email', class: 'w-48' },
    { key: 'Role', label: 'Role', class: 'w-24' },
    { key: 'Status', label: 'Status', class: 'w-24' },
    { key: 'actions', label: 'Actions', class: 'w-32 text-center' }
  ];
</script>

<div class="h-[calc(100vh-4rem)] flex flex-col p-4 gap-3">
  <!-- Header -->
  <div class="flex items-center justify-between">
    <div class="flex items-center gap-3">
      <Users class="w-8 h-8 text-primary" />
      <div>
        <h1 class="text-2xl font-bold text-gray-800">User Management</h1>
        <p class="text-sm text-gray-600">Manage system users and roles</p>
      </div>
    </div>
    <div class="flex gap-2">
      <button 
        class="btn btn-ghost btn-sm" 
        onclick={handleRefresh}
        disabled={loading}
      >
        <RefreshCw class="w-4 h-4 mr-1" />
        Refresh
      </button>
      <button class="btn btn-primary btn-sm" onclick={openCreateModal}>
        <Plus class="w-4 h-4 mr-1" />
        New User
      </button>
    </div>
  </div>

  <!-- Search Bar -->
  <div class="bg-base-100 p-4 rounded-lg shadow-sm border border-base-200">
    <div class="flex flex-wrap gap-3 items-end">
      <label class="form-control flex-1 min-w-[200px]">
        <span class="label-text text-xs text-gray-500 mb-1">Search</span>
        <label class="input input-sm input-bordered flex items-center gap-2 w-full">
          <Search class="w-4 h-4 text-gray-400" />
          <input
            type="text"
            class="grow bg-transparent outline-none"
            placeholder="Search by username, email, or name..."
            bind:value={searchFilters.search}
            onkeydown={(e) => e.key === 'Enter' && handleSearch()}
          />
        </label>
      </label>

      <label class="form-control w-40">
        <span class="label-text text-xs text-gray-500 mb-1">Role</span>
        <select class="select select-sm select-bordered w-full" bind:value={searchFilters.role}>
          <option value="">All Roles</option>
          <option value="admin">Admin</option>
          <option value="technician">Technician</option>
          <option value="physician">Physician</option>
          <option value="nurse">Nurse</option>
        </select>
      </label>

      <label class="form-control w-40">
        <span class="label-text text-xs text-gray-500 mb-1">Status</span>
        <select class="select select-sm select-bordered w-full" bind:value={searchFilters.status}>
          <option value="">All Status</option>
          <option value="active">Active</option>
          <option value="inactive">Inactive</option>
        </select>
      </label>

      <div class="flex gap-2">
        <button class="btn btn-primary btn-sm" onclick={handleSearch}>
          <Search class="w-4 h-4 mr-1" />
          Search
        </button>
        <button class="btn btn-ghost btn-sm" onclick={handleClear}>
          Clear
        </button>
      </div>
    </div>
  </div>

  <!-- User List -->
  <div class="flex-1 bg-base-100 rounded-lg shadow border border-base-200 overflow-hidden">
    <DataTable
      {columns}
      data={users}
      {loading}
      emptyMessage="No users found"
      hover={true}
      bordered={false}
    >
      {#snippet cell({ column, row, value })}
        {#if column.key === 'Name'}
          {[row.NameFirst, row.NameLast].filter(Boolean).join(' ') || '-'}
        {:else if column.key === 'Status'}
          <span class="badge badge-sm {value === 'active' ? 'badge-success' : 'badge-ghost'}">
            {value || 'Inactive'}
          </span>
        {:else if column.key === 'actions'}
          <div class="flex justify-center gap-1">
            <button
              class="btn btn-xs btn-ghost"
              onclick={() => openEditModal(row)}
              title="Edit user"
            >
              Edit
            </button>
            <button
              class="btn btn-xs btn-ghost text-error"
              onclick={() => confirmDelete(row)}
              title="Delete user"
              disabled={row.UserID === $auth.user?.id}
            >
              <Trash2 class="w-3 h-3" />
            </button>
          </div>
        {:else}
          {value || '-'}
        {/if}
      {/snippet}
    </DataTable>

    <!-- Pagination -->
    {#if totalPages > 1}
      <div class="border-t border-base-200 p-3 flex justify-between items-center">
        <span class="text-sm text-gray-500">
          Showing {(currentPage - 1) * perPage + 1} - {Math.min(currentPage * perPage, totalItems)} of {totalItems}
        </span>
        <div class="join">
          <button 
            class="join-item btn btn-sm" 
            onclick={() => handlePageChange(currentPage - 1)}
            disabled={currentPage === 1}
          >
            «
          </button>
          <button class="join-item btn btn-sm">Page {currentPage} of {totalPages}</button>
          <button 
            class="join-item btn btn-sm" 
            onclick={() => handlePageChange(currentPage + 1)}
            disabled={currentPage === totalPages}
          >
            »
          </button>
        </div>
      </div>
    {/if}
  </div>
</div>

<!-- User Form Modal -->
<UserFormModal
  bind:open={userForm.open}
  user={userForm.user}
  loading={userForm.loading}
  onSave={handleSaveUser}
  onCancel={() => userForm = { open: false, user: null, loading: false }}
/>

<!-- Delete Confirmation Modal -->
<Modal bind:open={deleteModal.open} title="Confirm Delete" size="sm">
  <div class="py-2">
    <p>
      Delete user 
      <strong>{deleteModal.user?.Username}</strong>?
    </p>
    <p class="text-sm text-error mt-2">This action cannot be undone.</p>
  </div>
  {#snippet footer()}
    <button 
      class="btn btn-ghost btn-sm" 
      onclick={() => deleteModal.open = false}
    >
      Cancel
    </button>
    <button 
      class="btn btn-error btn-sm" 
      onclick={handleDelete}
    >
      <Trash2 class="w-4 h-4 mr-1" />
      Delete
    </button>
  {/snippet}
</Modal>
