<template>
  <div>
    <CatalogPage
      :items="[]"
      :loading="false"
      :use-server-clustering="false"
      map-id="team-map"
      point-color="#8b5cf6"
      :show-panel="false"
      :hide-view-toggle="true"
    />

    <!-- Bottom Sheet -->
    <div class="fixed inset-x-0 bottom-0 z-50 flex flex-col" style="height: 70vh">
      <!-- Glass sheet -->
      <div class="relative flex-1 bg-black/40 backdrop-blur-xl rounded-t-2xl border-t border-white/20 shadow-2xl overflow-hidden">
        <!-- Drag handle -->
        <div class="flex justify-center py-2">
          <div class="w-12 h-1.5 bg-white/30 rounded-full" />
        </div>

        <!-- Header -->
        <div class="px-6 pb-4 border-b border-white/10">
          <!-- Error state -->
          <div v-if="hasError" 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>

          <!-- No team -->
          <div v-else-if="!currentTeam && !isLoading" class="text-center py-4">
            <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>

          <!-- Team header -->
          <template v-else>
            <div class="flex items-center justify-between">
              <div class="flex items-center gap-3">
                <div class="w-12 h-12 rounded-xl bg-primary/20 flex items-center justify-center">
                  <Icon name="lucide:building-2" size="24" class="text-primary" />
                </div>
                <div>
                  <div class="font-bold text-lg text-white">{{ currentTeam?.name }}</div>
                  <div class="flex items-center gap-2 mt-0.5">
                    <span class="badge badge-success badge-sm">{{ t('catalog.info.active') }}</span>
                    <span class="text-xs text-white/50">{{ t('clientTeam.members.title') }}</span>
                  </div>
                </div>
              </div>
              <div class="flex gap-2">
                <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" />
                  </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>
          </template>
        </div>

        <!-- Scrollable content -->
        <div v-if="currentTeam" class="overflow-y-auto h-[calc(70vh-120px)] px-6 py-4">
          <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
            <!-- Team members -->
            <div class="bg-white/5 rounded-xl p-4 border border-white/10">
              <div class="font-semibold text-white mb-3 flex items-center gap-2">
                <Icon name="lucide:users" size="18" />
                {{ t('clientTeam.members.title') }}
              </div>
              <div class="space-y-2">
                <div
                  v-for="(member, index) in currentTeamMembers"
                  :key="member.user?.id ?? `member-${index}`"
                  class="flex items-center justify-between p-2 bg-white/5 rounded-lg"
                >
                  <div class="flex items-center gap-2">
                    <div class="avatar placeholder">
                      <div class="w-8 h-8 rounded-full bg-primary text-primary-content text-xs">
                        <span>{{ getMemberInitials(member.user) }}</span>
                      </div>
                    </div>
                    <div>
                      <div class="text-sm text-white">{{ member.user?.firstName }} {{ member.user?.lastName || '' }}</div>
                      <div class="text-xs text-white/50">{{ roleText(member.role) }}</div>
                    </div>
                  </div>
                  <span class="badge badge-primary badge-sm">{{ roleText(member.role) }}</span>
                </div>

                <!-- Empty state -->
                <div v-if="currentTeamMembers.length === 0" class="text-center py-4 text-white/50 text-sm">
                  {{ t('clientTeam.members.empty', 'No members yet') }}
                </div>
              </div>
            </div>

            <!-- Invitations -->
            <div class="bg-white/5 rounded-xl p-4 border border-white/10">
              <div class="font-semibold text-white mb-3 flex items-center gap-2">
                <Icon name="lucide:mail" size="18" />
                {{ t('clientTeam.invitations.title', 'Pending Invitations') }}
              </div>
              <div class="space-y-2">
                <div
                  v-for="invitation in currentTeamInvitations"
                  :key="invitation.uuid"
                  class="flex items-center justify-between p-2 bg-warning/10 rounded-lg border border-warning/20"
                >
                  <div class="flex items-center gap-2">
                    <div class="avatar placeholder">
                      <div class="w-8 h-8 rounded-full bg-warning/20 text-warning flex items-center justify-center">
                        <Icon name="lucide:mail" size="14" />
                      </div>
                    </div>
                    <div>
                      <div class="text-sm text-white">{{ invitation.email }}</div>
                      <div class="text-xs text-warning">{{ t('clientTeam.invitations.pending') }}</div>
                    </div>
                  </div>
                  <span class="badge badge-warning badge-outline badge-sm">{{ roleText(invitation.role) }}</span>
                </div>

                <!-- Empty state -->
                <div v-if="currentTeamInvitations.length === 0" class="text-center py-4 text-white/50 text-sm">
                  {{ t('clientTeam.invitations.empty', 'No pending invitations') }}
                </div>
              </div>

              <!-- Invite button -->
              <button
                class="mt-4 w-full bg-white/5 border border-dashed border-white/20 rounded-lg p-3 hover:bg-white/10 transition-colors"
                @click="inviteMember"
              >
                <div class="flex items-center justify-center gap-2 text-white/50">
                  <Icon name="lucide:user-plus" size="16" />
                  <span class="text-sm">{{ t('clientTeam.inviteCard.title') }}</span>
                </div>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</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() || '??'
}

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) : []
})

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>
