<template>
  <Section variant="plain">
    <Stack gap="6">
      <PageHeader :title="t('clientTeam.header.title')" :actions="teamHeaderActions" />

      <Alert v-if="hasError" variant="error">
        <Stack gap="2">
          <Heading :level="4" weight="semibold">{{ t('clientTeam.error.title') }}</Heading>
          <Text tone="muted">{{ error }}</Text>
          <Button @click="loadUserTeams">{{ t('clientTeam.error.retry') }}</Button>
        </Stack>
      </Alert>

      <Card v-else-if="isLoading" tone="muted" padding="lg">
        <Stack align="center" justify="center" gap="3">
          <Spinner />
          <Text tone="muted">{{ t('clientTeam.loading.message') }}</Text>
        </Stack>
      </Card>

      <!-- No team - prompt to create KYC application -->
      <EmptyState
        v-else-if="!currentTeam"
        icon="👥"
        :title="t('clientTeam.empty.title')"
        :description="t('clientTeam.empty.description')"
        :action-label="t('clientTeam.empty.cta')"
        :action-to="localePath('/clientarea/kyc')"
        action-icon="lucide:plus"
      />

      <template v-else>
        <Card padding="lg">
          <Stack gap="4">
            <Stack direction="row" gap="4" align="start" justify="between">
                <Stack direction="row" gap="3" align="center">
                  <IconCircle tone="neutral" size="lg">
                    {{ currentTeam.name?.charAt(0)?.toUpperCase() || '?' }}
                  </IconCircle>
                  <Heading :level="2" weight="semibold">{{ currentTeam.name }}</Heading>
                </Stack>
              </Stack>

          </Stack>
        </Card>

        <Stack gap="3">
          <Heading :level="2">{{ t('clientTeam.members.title') }}</Heading>
          <Grid :cols="1" :md="2" :lg="3" :gap="4">
            <Card
              v-for="member in currentTeam?.members || []"
              :key="member.user?.id"
              padding="lg"
            >
              <Stack gap="3">
                <Stack direction="row" gap="3" align="center">
                  <IconCircle tone="neutral">{{ getMemberInitials(member.user) }}</IconCircle>
                  <Stack gap="1">
                    <Text weight="semibold">{{ member.user?.firstName }} {{ member.user?.lastName || '—' }}</Text>
                  </Stack>
                </Stack>
                <Stack direction="row" gap="2" wrap>
                  <Pill variant="primary">{{ roleText(member.role) }}</Pill>
                </Stack>
              </Stack>
            </Card>

            <!-- Pending invitations -->
            <Card
              v-for="invitation in currentTeam?.invitations || []"
              :key="invitation.uuid"
              padding="lg"
              class="border-dashed border-warning"
            >
              <Stack gap="3">
                <Stack direction="row" gap="3" align="center">
                  <IconCircle tone="warning">
                    <Icon name="lucide:mail" size="16" />
                  </IconCircle>
                  <Stack gap="1">
                    <Text weight="semibold">{{ invitation.email }}</Text>
                    <Text tone="muted" size="sm">{{ t('clientTeam.invitations.pending') }}</Text>
                  </Stack>
                </Stack>
                <Stack direction="row" gap="2" wrap>
                  <Pill variant="outline" tone="warning">{{ roleText(invitation.role) }}</Pill>
                  <Pill variant="ghost" tone="muted">{{ t('clientTeam.invitations.sent') }}</Pill>
                </Stack>
              </Stack>
            </Card>

            <Card
              padding="lg"
              class="border-2 border-dashed border-base-300 hover:border-primary cursor-pointer transition-colors"
              @click="inviteMember"
            >
              <Stack gap="3" align="center" justify="center" class="h-full min-h-[100px]">
                <div class="w-10 h-10 rounded-full bg-base-200 flex items-center justify-center text-base-content/50">
                  <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                  </svg>
                </div>
                <Text weight="semibold" tone="muted">{{ t('clientTeam.inviteCard.title') }}</Text>
              </Stack>
            </Card>
          </Grid>
        </Stack>
      </template>
    </Stack>
  </Section>
</template>

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

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<any[]>([])
const currentTeam = ref<any>(null)
const isLoading = ref(true)
const hasError = ref(false)
const error = ref('')

const teamHeaderActions = computed(() => {
  const actions: Array<{ label: string; icon?: string; to?: string }> = []
  actions.push({ label: t('clientTeam.actions.addCompany'), icon: 'lucide:plus', to: localePath('/clientarea/kyc') })
  if (userTeams.value.length > 1) {
    actions.push({ label: t('clientTeam.actions.switch'), icon: 'lucide:arrow-left-right', to: localePath('/clientarea/company-switch') })
  }
  return actions
})
const roleText = (role?: string) => {
  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')
}

const getMemberInitials = (user?: any) => {
  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 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]
      setActiveTeam(firstTeam?.id || null, firstTeam?.logtoOrgId)
      currentTeam.value = firstTeam
    }
    // Если нет команды - currentTeam остаётся null, показываем EmptyState
  } catch (err: any) {
    hasError.value = true
    error.value = err.message || t('clientTeam.error.load')
  } finally {
    isLoading.value = false
  }
}

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

await loadUserTeams()
</script>
