<template>
  <div class="p-6 space-y-6">
    <div class="flex items-center justify-between">
      <div>
        <h1 class="text-3xl font-bold">Team Management</h1>
        <p class="text-muted-foreground">Manage users, roles, and permissions</p>
      </div>
      <div class="flex items-center space-x-2">
        <Button variant="outline" @click="refreshData" :disabled="isLoading">
          <RefreshCw class="h-4 w-4 mr-2" :class="{ 'animate-spin': isLoading }" />
          Refresh
        </Button>
        <Button v-if="isAdmin" @click="showCreateDialog = true">
          <UserPlus class="h-4 w-4 mr-2" />
          Add User
        </Button>
      </div>
    </div>

    <!-- Error Alert -->
    <Alert v-if="error" variant="destructive">
      <AlertCircle class="h-4 w-4" />
      <AlertTitle>Error</AlertTitle>
      <AlertDescription>{{ error }}</AlertDescription>
    </Alert>

    <!-- Loading State -->
    <div v-if="isLoading && !users.length && !pendingUsers.length" class="flex items-center justify-center py-12">
      <div class="text-center">
        <Loader2 class="h-8 w-8 animate-spin mx-auto mb-4" />
        <p class="text-muted-foreground">Loading users...</p>
      </div>
    </div>

    <!-- Content -->
    <div v-else class="space-y-8">
      <!-- Pending Users Section -->
      <div v-if="userStore.pendingCount > 0 || isAdmin">
        <PendingUsersDashboard
          :pending-users="pendingUsers"
          :is-processing="processingUserId"
          @approve="handleApproveUser"
          @reject="handleRejectUser"
        />
      </div>

      <!-- All Users Section -->
      <div v-if="users.length > 0">
        <UserManagementTable
          :users="users"
          :current-user="currentUser"
          :is-updating-role="updatingRoleUserId ?? undefined"
          :is-updating-admin-permission="updatingAdminPermissionUserId ?? undefined"
          @role-change="handleRoleChange"
          @admin-permission-change="handleAdminPermissionChange"
          @approve-user="handleApproveUser"
          @edit-user="handleEditUser"
          @reset-password="handleResetPassword"
          @delete-user="handleDeleteUser"
        />
      </div>

      <!-- Empty State -->
      <div v-if="!isLoading && users.length === 0 && pendingUsers.length === 0" class="text-center py-12">
        <div class="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-muted">
          <Users class="h-6 w-6 text-muted-foreground" />
        </div>
        <h3 class="mt-4 text-lg font-medium">No users found</h3>
        <p class="mt-2 text-sm text-muted-foreground">
          Get started by inviting team members to collaborate on your projects.
        </p>
        <Button class="mt-4" @click="() => $router.push('/register')">
          <UserPlus class="h-4 w-4 mr-2" />
          Invite First User
        </Button>
      </div>
    </div>

    <!-- User Create Dialog -->
    <UserCreateDialog
      :open="showCreateDialog"
      @update:open="showCreateDialog = $event"
      @submit="handleCreateUser"
      :is-submitting="isCreatingUser"
    />

    <!-- User Edit Dialog -->
    <UserEditDialog
      :open="showEditDialog"
      @update:open="showEditDialog = $event"
      :user="selectedUser"
      :current-user-id="currentUser?.id"
      @submit="handleEditUserSubmit"
      :is-submitting="isEditingUser"
    />

    <!-- Password Reset Dialog -->
    <PasswordResetDialog
      :open="showPasswordResetDialog"
      @update:open="showPasswordResetDialog = $event"
      :user="selectedUser"
      @submit="handlePasswordResetSubmit"
      :is-submitting="isResettingPassword"
    />

    <!-- User Delete Confirm Dialog -->
    <UserDeleteConfirmDialog
      :open="showDeleteDialog"
      @update:open="showDeleteDialog = $event"
      :user="selectedUser"
      @delete="handleDeleteUserConfirm"
      :is-deleting="isDeletingUser"
    />

    <!-- Success Toast -->
    <div v-if="successMessage" class="fixed bottom-4 right-4 z-50">
      <Alert class="w-80 bg-green-50 border-green-200 dark:bg-green-950 dark:border-green-800">
        <CheckCircle class="h-4 w-4 text-green-600 dark:text-green-400" />
        <AlertTitle class="text-green-800 dark:text-green-200">Success</AlertTitle>
        <AlertDescription class="text-green-700 dark:text-green-300">{{ successMessage }}</AlertDescription>
      </Alert>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Button } from '@/components/ui/button'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Users, UserPlus, RefreshCw, AlertCircle, Loader2, CheckCircle } from 'lucide-vue-next'
import { useUserStore } from '@/stores/user'
import { useAuthStore } from '@/stores/auth'
import PendingUsersDashboard from '@/components/user/PendingUsersDashboard.vue'
import UserManagementTable from '@/components/user/UserManagementTable.vue'
import UserCreateDialog from '@/components/user/UserCreateDialog.vue'
import UserEditDialog from '@/components/user/UserEditDialog.vue'
import PasswordResetDialog from '@/components/user/PasswordResetDialog.vue'
import UserDeleteConfirmDialog from '@/components/user/UserDeleteConfirmDialog.vue'
import type { User } from '@/types/auth'
import type { UserCreateData } from '@/components/user/UserCreateDialog.vue'
import type { UserEditData } from '@/components/user/UserEditDialog.vue'

const router = useRouter()
const userStore = useUserStore()
const authStore = useAuthStore()

// Local state
const processingUserId = ref<number | null>(null)
const updatingRoleUserId = ref<number | null>(null)
const updatingAdminPermissionUserId = ref<number | null>(null)
const selectedUser = ref<User | null>(null)
const successMessage = ref('')

// Dialog states
const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const showPasswordResetDialog = ref(false)
const showDeleteDialog = ref(false)

// Loading states
const isCreatingUser = ref(false)
const isEditingUser = ref(false)
const isResettingPassword = ref(false)
const isDeletingUser = ref(false)

// Computed
const users = computed(() => userStore.users)
const pendingUsers = computed(() => userStore.pendingUsers)
const isLoading = computed(() => userStore.isLoading)
const error = computed(() => userStore.error)
const isAdmin = computed(() => authStore.isAdmin)
const currentUser = computed(() => authStore.user)

// Methods
const refreshData = async () => {
  try {
    await Promise.all([
      userStore.fetchAllUsers(),
      userStore.fetchPendingUsers()
    ])
  } catch (err) {
    console.error('Failed to refresh data:', err)
  }
}

const handleApproveUser = async (userId: number) => {
  try {
    processingUserId.value = userId
    await userStore.approveUser(userId, true)
    showSuccessMessage('User approved successfully')
  } catch (err) {
    console.error('Failed to approve user:', err)
  } finally {
    processingUserId.value = null
  }
}

const handleRejectUser = async (userId: number) => {
  try {
    processingUserId.value = userId
    await userStore.approveUser(userId, false)
    showSuccessMessage('User rejected')
  } catch (err) {
    console.error('Failed to reject user:', err)
  } finally {
    processingUserId.value = null
  }
}

const handleRoleChange = async (userId: number, role: User['role']) => {
  try {
    updatingRoleUserId.value = userId
    await userStore.updateUserRole(userId, role)
    showSuccessMessage(`User role updated to ${role}`)
  } catch (err: any) {
    console.error('Failed to update user role:', err)
    // The error is already set in the store, but we can also show a toast-like message
    // The error will be displayed in the error alert at the top of the page
  } finally {
    updatingRoleUserId.value = null
  }
}

const handleAdminPermissionChange = async (userId: number, isAdmin: boolean) => {
  try {
    updatingAdminPermissionUserId.value = userId
    await userStore.updateUserAdminPermission(userId, isAdmin)
    showSuccessMessage(`Admin permission ${isAdmin ? 'granted' : 'revoked'}`)
  } catch (err: any) {
    console.error('Failed to update admin permission:', err)
    // The error is already set in the store and will be displayed in the error alert
  } finally {
    updatingAdminPermissionUserId.value = null
  }
}

const handleCreateUser = async (data: UserCreateData) => {
  try {
    isCreatingUser.value = true
    await userStore.createUser(data)
    showCreateDialog.value = false
    showSuccessMessage('User created successfully')
    await refreshData()
  } catch (err) {
    console.error('Failed to create user:', err)
  } finally {
    isCreatingUser.value = false
  }
}

const handleEditUser = (user: User) => {
  selectedUser.value = user
  showEditDialog.value = true
}

const handleEditUserSubmit = async (userId: number, data: UserEditData) => {
  try {
    isEditingUser.value = true
    console.log('Editing user with data:', data)
    await userStore.editUser(userId, data)
    showEditDialog.value = false
    showSuccessMessage('User updated successfully')
    await refreshData()
  } catch (err: any) {
    console.error('Failed to edit user:', err)
    console.error('Error response:', err.response?.data)
    
    // Handle FastAPI validation errors (422)
    let errorMessage = 'Failed to update user'
    if (err.response?.data?.detail) {
      if (Array.isArray(err.response.data.detail)) {
        // Pydantic validation errors are in array format
        const errors = err.response.data.detail.map((e: any) => {
          const field = e.loc?.join('.') || 'unknown'
          return `${field}: ${e.msg}`
        }).join(', ')
        errorMessage = errors
        console.error('Validation errors:', err.response.data.detail)
      } else {
        errorMessage = err.response.data.detail
      }
    }
    showErrorMessage(errorMessage)
  } finally {
    isEditingUser.value = false
  }
}

const handleResetPassword = (user: User) => {
  selectedUser.value = user
  showPasswordResetDialog.value = true
}

const handlePasswordResetSubmit = async (userId: number, password: string) => {
  try {
    isResettingPassword.value = true
    await userStore.resetUserPassword(userId, password)
    showPasswordResetDialog.value = false
    showSuccessMessage('Password reset successfully')
  } catch (err) {
    console.error('Failed to reset password:', err)
  } finally {
    isResettingPassword.value = false
  }
}

const handleDeleteUser = async (user: User) => {
  selectedUser.value = user
  
  // Check if user can be deleted
  try {
    const { userService } = await import('@/services/user')
    const checkResult = await userService.checkCanDeleteUser(user.id)
    
    if (!checkResult.can_delete) {
      // Show error message with details
      userStore.error = checkResult.reason || 'Cannot delete this user'
      return
    }
    
    // User can be deleted, show confirmation dialog
    showDeleteDialog.value = true
  } catch (err: any) {
    console.error('Failed to check user deletion eligibility:', err)
    const errorMessage = err.response?.data?.detail || 'Failed to check user deletion eligibility'
    userStore.error = errorMessage
  }
}

const handleDeleteUserConfirm = async (userId: number) => {
  try {
    isDeletingUser.value = true
    await userStore.deleteUser(userId)
    showDeleteDialog.value = false
    showSuccessMessage('User deleted successfully')
    await refreshData()
  } catch (err: any) {
    console.error('Failed to delete user:', err)
    // Show the error message from the backend
    const errorMessage = err.response?.data?.detail || 'Failed to delete user'
    userStore.error = errorMessage
  } finally {
    isDeletingUser.value = false
  }
}

const showSuccessMessage = (message: string) => {
  successMessage.value = message
  setTimeout(() => {
    successMessage.value = ''
  }, 3000)
}

const showErrorMessage = (message: string) => {
  // Use the store's error mechanism
  userStore.error = message
}

// Clear error when component unmounts
const clearError = () => {
  userStore.clearError()
}

// Lifecycle
onMounted(() => {
  refreshData()
})

// Watch for auth changes
watch(() => authStore.isAuthenticated, (isAuth) => {
  if (isAuth) {
    refreshData()
  }
})
</script>