<template>
  <CatalogPage
    :items="mapPoints"
    :loading="isLoading"
    :use-server-clustering="false"
    map-id="team-map"
    point-color="#8b5cf6"
    :show-panel="true"
    panel-width="w-96"
    :hide-view-toggle="true"
  >
    <template #panel>
      <!-- Error state -->
      <div v-if="hasError" class="p-4">
        <div class="bg-error/20 border border-error/30 rounded-lg p-4">
          <div class="font-semibold text-white mb-2">{{ t('clientTeam.error.title') }}</div>
          <div class="text-sm text-white/70 mb-3">{{ error }}</div>
          <button class="btn btn-sm bg-white/10 border-white/20 text-white" @click="loadUserTeams">
            {{ t('clientTeam.error.retry') }}
          </button>
        </div>
      </div>

      <!-- No team - prompt to create -->
      <div v-else-if="!currentTeam && !isLoading" class="flex flex-col items-center justify-center h-full p-6 text-center">
        <div class="text-4xl mb-3">👥</div>
        <div class="font-semibold text-white mb-2">{{ t('clientTeam.empty.title') }}</div>
        <div class="text-sm text-white/60 mb-4">{{ t('clientTeam.empty.description') }}</div>
        <NuxtLink :to="localePath('/clientarea/kyc')">
          <button class="btn btn-sm bg-white/10 border-white/20 text-white hover:bg-white/20">
            <Icon name="lucide:plus" size="14" class="mr-1" />
            {{ t('clientTeam.empty.cta') }}
          </button>
        </NuxtLink>
      </div>

      <template v-else>
        <!-- Panel header -->
        <div class="p-4 border-b border-white/10 flex-shrink-0">
          <div class="flex items-center gap-3 mb-3">
            <div class="w-10 h-10 rounded-full bg-primary/20 flex items-center justify-center text-primary font-semibold">
              {{ currentTeam?.name?.charAt(0)?.toUpperCase() || '?' }}
            </div>
            <div class="flex-1 min-w-0">
              <div class="font-semibold text-white truncate">{{ currentTeam?.name }}</div>
              <div class="text-xs text-white/50">{{ t('clientTeam.members.title') }}</div>
            </div>
          </div>

          <!-- Actions -->
          <div class="flex gap-2">
            <NuxtLink :to="localePath('/clientarea/kyc')" class="flex-1">
              <button class="btn btn-sm w-full bg-white/10 border-white/20 text-white hover:bg-white/20">
                <Icon name="lucide:plus" size="14" class="mr-1" />
                {{ t('clientTeam.actions.addCompany') }}
              </button>
            </NuxtLink>
            <NuxtLink v-if="userTeams.length > 1" :to="localePath('/clientarea/company-switch')">
              <button class="btn btn-sm bg-white/10 border-white/20 text-white hover:bg-white/20">
                <Icon name="lucide:arrow-left-right" size="14" />
              </button>
            </NuxtLink>
          </div>
        </div>

        <!-- Members list -->
        <div class="flex-1 overflow-y-auto p-3 space-y-2">
          <!-- Team members -->
          <div
            v-for="(member, index) in currentTeamMembers"
            :key="member.user?.id ?? `member-${index}`"
            class="bg-white/10 rounded-lg p-3"
          >
            <div class="flex items-center gap-3">
              <div class="avatar placeholder">
                <div class="w-9 h-9 rounded-full bg-primary text-primary-content text-sm">
                  <span>{{ getMemberInitials(member.user) }}</span>
                </div>
              </div>
              <div class="flex-1 min-w-0">
                <div class="font-medium text-sm text-white truncate">
                  {{ member.user?.firstName }} {{ member.user?.lastName || '' }}
                </div>
                <div class="text-xs text-white/50">{{ roleText(member.role) }}</div>
              </div>
              <span class="badge badge-primary badge-sm">{{ roleText(member.role) }}</span>
            </div>
          </div>

          <!-- Pending invitations -->
          <div
            v-for="invitation in currentTeamInvitations"
            :key="invitation.uuid"
            class="bg-warning/10 border border-warning/30 rounded-lg p-3"
          >
            <div class="flex items-center gap-3">
              <div class="avatar placeholder">
                <div class="w-9 h-9 rounded-full bg-warning/20 text-warning flex items-center justify-center">
                  <Icon name="lucide:mail" size="16" />
                </div>
              </div>
              <div class="flex-1 min-w-0">
                <div class="font-medium text-sm text-white truncate">{{ invitation.email }}</div>
                <div class="text-xs text-warning">{{ t('clientTeam.invitations.pending') }}</div>
              </div>
              <span class="badge badge-warning badge-outline badge-sm">{{ roleText(invitation.role) }}</span>
            </div>
          </div>

          <!-- Add member button -->
          <button
            class="w-full bg-white/5 border-2 border-dashed border-white/20 rounded-lg p-4 hover:bg-white/10 hover:border-white/30 transition-colors"
            @click="inviteMember"
          >
            <div class="flex flex-col items-center gap-2 text-white/50">
              <Icon name="lucide:user-plus" size="20" />
              <span class="text-sm font-medium">{{ t('clientTeam.inviteCard.title') }}</span>
            </div>
          </button>
        </div>

        <!-- Footer -->
        <div class="p-3 border-t border-white/10 flex-shrink-0">
          <span class="text-xs text-white/50">
            {{ currentTeamMembers.length }} {{ t('clientTeam.members.title').toLowerCase() }}
            <template v-if="currentTeamInvitations.length > 0">
              + {{ currentTeamInvitations.length }} {{ t('clientTeam.invitations.pending').toLowerCase() }}
            </template>
          </span>
        </div>
      </template>
    </template>
  </CatalogPage>
</template>

<script setup lang="ts">
import { GetTeamDocument, type GetTeamQueryResult } from '~/composables/graphql/user/teams-generated'

interface UserTeam {
  id?: string | null
  name: string
  logtoOrgId?: string | null
}

type TeamWithMembers = NonNullable<GetTeamQueryResult['getTeam']>

const { t } = useI18n()
const router = useRouter()

definePageMeta({
  layout: 'topnav',
  middleware: ['auth-oidc']
})

const localePath = useLocalePath()
const me = useState<{
  teams?: Array<{ id?: string | null; name: string; logtoOrgId?: string | null } | null> | null
  activeTeamId?: string | null
  activeTeam?: { logtoOrgId?: string | null } | null
} | null>('me', () => null)
const { setActiveTeam } = useActiveTeam()

const userTeams = ref<UserTeam[]>([])
const currentTeam = ref<TeamWithMembers | UserTeam | null>(null)
const isLoading = ref(true)
const hasError = ref(false)
const error = ref('')

const roleText = (role?: string | null) => {
  const map: Record<string, string> = {
    OWNER: t('clientTeam.roles.owner'),
    ADMIN: t('clientTeam.roles.admin'),
    MANAGER: t('clientTeam.roles.manager'),
    MEMBER: t('clientTeam.roles.member'),
  }
  return map[role || ''] || role || t('clientTeam.roles.member')
}

interface TeamMember {
  id?: string | null
  firstName?: string | null
  lastName?: string | null
}

const getMemberInitials = (user?: TeamMember | null) => {
  if (!user) return '??'
  const first = user.firstName?.charAt(0) || ''
  const last = user.lastName?.charAt(0) || ''
  return (first + last).toUpperCase() || user.id?.charAt(0).toUpperCase() || '??'
}

// Type-safe accessors for TeamWithMembers properties
const currentTeamMembers = computed(() => {
  const team = currentTeam.value
  return team && 'members' in team ? (team.members || []).filter((m): m is NonNullable<typeof m> => m !== null) : []
})

const currentTeamInvitations = computed(() => {
  const team = currentTeam.value
  return team && 'invitations' in team ? (team.invitations || []).filter((i): i is NonNullable<typeof i> => i !== null) : []
})

// Map points - empty for now, could show team addresses
const mapPoints = computed(() => {
  return []
})

const loadUserTeams = async () => {
  try {
    isLoading.value = true
    hasError.value = false

    if (!me.value) {
      throw new Error(t('clientTeam.error.load'))
    }

    userTeams.value = me.value.teams?.filter((t): t is NonNullable<typeof t> => t !== null) || []

    if (me.value.activeTeamId && me.value.activeTeam) {
      setActiveTeam(me.value.activeTeamId, me.value.activeTeam.logtoOrgId)
      const { data: teamData } = await useServerQuery('team-page-team', GetTeamDocument, { teamId: me.value.activeTeamId }, 'user', 'teams')
      currentTeam.value = teamData.value?.getTeam || null
    } else if (userTeams.value.length > 0) {
      const firstTeam = userTeams.value[0]
      if (firstTeam) {
        setActiveTeam(firstTeam.id || null, firstTeam.logtoOrgId)
        currentTeam.value = firstTeam
      }
    }
  } catch (err: unknown) {
    hasError.value = true
    error.value = err instanceof Error ? err.message : t('clientTeam.error.load')
  } finally {
    isLoading.value = false
  }
}

const inviteMember = () => {
  router.push(localePath('/clientarea/team/invite'))
}

await loadUserTeams()
</script>
