<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useApi } from '@/composables/useApi'
import type { TeamMember, Role } from '@/types'
import { UserPlus, Shield, Mail, Trash2, RefreshCw } from 'lucide-vue-next'

const api = useApi()

const members = ref<TeamMember[]>([])
const roles = ref<Role[]>([])
const isLoading = ref(false)
const showInvite = ref(false)
const inviteEmail = ref('')
const inviteRole = ref('')
const inviting = ref(false)

function roleBadgeClass(roleName: string): string {
  switch (roleName.toLowerCase()) {
    case 'owner': return 'bg-oxide-500/15 text-oxide-400'
    case 'admin': return 'bg-purple-500/15 text-purple-400'
    case 'moderator': return 'bg-blue-500/15 text-blue-400'
    default: return 'bg-neutral-700/50 text-neutral-400'
  }
}

async function fetchTeam() {
  isLoading.value = true
  try {
    const data = await api.get<{ members: TeamMember[]; roles: Role[] }>('/team')
    members.value = data.members ?? []
    roles.value = data.roles ?? []
  } catch {
    // API not wired yet
  } finally {
    isLoading.value = false
  }
}

async function sendInvite() {
  if (!inviteEmail.value.trim() || !inviteRole.value) return
  inviting.value = true
  try {
    await api.post('/team/invite', {
      email: inviteEmail.value.trim(),
      role_id: inviteRole.value,
    })
    inviteEmail.value = ''
    inviteRole.value = ''
    showInvite.value = false
    await fetchTeam()
  } catch {
    // Handle error
  } finally {
    inviting.value = false
  }
}

async function removeMember(member: TeamMember) {
  if (!confirm(`Remove ${member.username} from the team?`)) return
  try {
    await api.del(`/team/${member.id}`)
    await fetchTeam()
  } catch {
    // Handle error
  }
}

onMounted(() => {
  fetchTeam()
})
</script>

<template>
  <div class="p-6 space-y-6">
    <!-- Header -->
    <div class="flex items-center justify-between">
      <div class="flex items-center gap-3">
        <UserPlus class="w-5 h-5 text-oxide-500" />
        <div>
          <h1 class="text-2xl font-bold text-neutral-100">Team Management</h1>
          <p class="text-sm text-neutral-500 mt-0.5">{{ members.length }} members</p>
        </div>
      </div>
      <div class="flex items-center gap-3">
        <button
          @click="fetchTeam"
          :disabled="isLoading"
          class="flex items-center gap-2 px-3 py-2 text-sm text-neutral-400 hover:text-neutral-200 bg-neutral-800 hover:bg-neutral-700 rounded-lg transition-colors"
        >
          <RefreshCw class="w-4 h-4" :class="{ 'animate-spin': isLoading }" />
        </button>
        <button
          @click="showInvite = !showInvite"
          class="flex items-center gap-2 px-4 py-2 bg-oxide-600 hover:bg-oxide-700 text-white text-sm font-medium rounded-lg transition-colors"
        >
          <Mail class="w-4 h-4" />
          Invite Member
        </button>
      </div>
    </div>

    <!-- Invite form -->
    <div v-if="showInvite" class="bg-neutral-900 border border-oxide-500/20 rounded-lg p-5">
      <h3 class="text-sm font-medium text-neutral-200 mb-3">Invite a Team Member</h3>
      <form @submit.prevent="sendInvite" class="flex items-end gap-3">
        <div class="flex-1">
          <label class="block text-xs text-neutral-500 mb-1">Email Address</label>
          <input
            v-model="inviteEmail"
            type="email"
            required
            placeholder="team@example.com"
            class="w-full px-3 py-2 bg-neutral-800 border border-neutral-700 rounded-lg text-sm text-neutral-100 placeholder-neutral-500 focus:outline-none focus:ring-2 focus:ring-oxide-500/50 focus:border-oxide-500 transition-colors"
          />
        </div>
        <div class="w-48">
          <label class="block text-xs text-neutral-500 mb-1">Role</label>
          <select
            v-model="inviteRole"
            required
            class="w-full px-3 py-2 bg-neutral-800 border border-neutral-700 rounded-lg text-sm text-neutral-100 focus:outline-none focus:ring-2 focus:ring-oxide-500/50 focus:border-oxide-500 transition-colors"
          >
            <option value="" disabled>Select role...</option>
            <option v-for="role in roles" :key="role.id" :value="role.id">
              {{ role.role_name }}
            </option>
          </select>
        </div>
        <button
          type="submit"
          :disabled="inviting"
          class="px-4 py-2 bg-oxide-600 hover:bg-oxide-700 disabled:opacity-50 text-white text-sm font-medium rounded-lg transition-colors"
        >
          {{ inviting ? 'Sending...' : 'Send Invite' }}
        </button>
      </form>
    </div>

    <!-- Team table -->
    <div class="bg-neutral-900 border border-neutral-800 rounded-lg overflow-hidden">
      <table class="w-full">
        <thead>
          <tr class="border-b border-neutral-800 text-left">
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Member</th>
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Email</th>
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Role</th>
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Status</th>
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider text-right">Actions</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-neutral-800">
          <tr v-if="members.length === 0">
            <td colspan="5" class="px-4 py-12 text-center text-neutral-500 text-sm">
              <template v-if="isLoading">Loading team...</template>
              <template v-else>No team members yet. Invite someone to get started.</template>
            </td>
          </tr>
          <tr
            v-for="member in members"
            :key="member.id"
            class="hover:bg-neutral-800/50 transition-colors"
          >
            <td class="px-4 py-3">
              <div class="flex items-center gap-2">
                <Shield class="w-4 h-4 text-neutral-600" />
                <span class="text-sm font-medium text-neutral-100">{{ member.username }}</span>
              </div>
            </td>
            <td class="px-4 py-3 text-sm text-neutral-400">{{ member.email }}</td>
            <td class="px-4 py-3">
              <span
                class="text-xs font-medium px-2 py-0.5 rounded-full"
                :class="roleBadgeClass(member.role_name)"
              >
                {{ member.role_name }}
              </span>
            </td>
            <td class="px-4 py-3">
              <span
                class="text-xs font-medium px-2 py-0.5 rounded-full"
                :class="member.accepted_at
                  ? 'bg-green-500/10 text-green-400'
                  : 'bg-yellow-500/10 text-yellow-400'"
              >
                {{ member.accepted_at ? 'Active' : 'Pending' }}
              </span>
            </td>
            <td class="px-4 py-3 text-right">
              <button
                @click="removeMember(member)"
                class="p-1.5 text-neutral-500 hover:text-red-400 rounded transition-colors"
                title="Remove member"
              >
                <Trash2 class="w-4 h-4" />
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>
