<template>
  <Section variant="plain">
    <Stack gap="6">
      <!-- Header с кнопками -->
      <Stack direction="row" align="center" justify="between">
        <Heading :level="1">Ваша компания</Heading>
        <Stack direction="row" gap="2" v-if="currentTeam">
          <NuxtLink
            v-if="userTeams.length > 1"
            :to="localePath('/dashboard/company-switch')"
            class="inline-flex items-center gap-1 text-primary hover:text-primary-hover font-semibold text-sm"
          >
            <Icon name="lucide:arrow-left-right" size="16" />
            Сменить компанию
          </NuxtLink>
          <button
            type="button"
            class="inline-flex items-center gap-1 text-primary hover:text-primary-hover font-semibold text-sm"
            @click="showCreateForm = true"
          >
            <Icon name="lucide:plus" size="16" />
            Добавить
          </button>
        </Stack>
      </Stack>

      <!-- Ошибка -->
      <Alert v-if="hasError" variant="error">
        <Stack gap="2">
          <Heading :level="4" weight="semibold">Ошибка</Heading>
          <Text tone="muted">{{ error }}</Text>
          <Button @click="loadUserTeams">Повторить</Button>
        </Stack>
      </Alert>

      <!-- Загрузка -->
      <Card v-else-if="isLoading" tone="muted" padding="lg">
        <Stack align="center" justify="center" gap="3">
          <Spinner />
          <Text tone="muted">Загружаем компании...</Text>
        </Stack>
      </Card>

      <!-- Форма создания компании -->
      <TeamCreateForm
        v-else-if="showCreateForm"
        @team-created="handleTeamCreated"
        @cancel="showCreateForm = false"
      />

      <!-- Нет компании -->
      <Card v-else-if="!currentTeam" padding="lg">
        <Stack align="center" gap="4">
          <IconCircle tone="primary" size="lg">🏢</IconCircle>
          <Heading :level="3" align="center">У вас нет компании</Heading>
          <Text tone="muted" align="center">Создайте компанию для работы на платформе</Text>
          <Button @click="showCreateForm = true">
            Стать участником
          </Button>
        </Stack>
      </Card>

      <!-- Текущая компания -->
      <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="isKycApproved ? 'primary' : 'neutral'" size="lg">
                  {{ currentTeam.name?.charAt(0)?.toUpperCase() || '?' }}
                </IconCircle>
                <Stack gap="1">
                  <Heading :level="2" weight="semibold">{{ currentTeam.name }}</Heading>
                  <Stack direction="row" gap="2" align="center">
                    <Text size="base">{{ kycIcon(currentTeam.status) }}</Text>
                    <Text tone="muted" size="base">{{ kycTitle(currentTeam.status) }}</Text>
                  </Stack>
                </Stack>
              </Stack>
            </Stack>

            <!-- KYC блок если не пройден -->
            <template v-if="!isKycApproved">
              <hr class="border-gray-200" />
              <Stack gap="3">
                <Text tone="muted">
                  Для работы на платформе необходимо пройти верификацию компании (KYC)
                </Text>
                <div>
                  <Button :as="'NuxtLink'" :to="localePath('/dashboard/kyc')">
                    Пройти верификацию →
                  </Button>
                </div>
              </Stack>
            </template>
          </Stack>
        </Card>

        <!-- Участники (только если KYC пройден) -->
        <template v-if="isKycApproved">
          <Stack gap="3">
            <Heading :level="2">Участники</Heading>
            <Grid :cols="1" :md="2" :lg="3" :gap="4">
              <!-- Карточки участников -->
              <Card
                v-for="member in currentTeam?.members || []"
                :key="member.user?.id || member.email"
                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>
                      <Text tone="muted" size="base">{{ member.email }}</Text>
                    </Stack>
                  </Stack>
                  <Stack direction="row" gap="2" wrap>
                    <Pill variant="primary">{{ roleText(member.role) }}</Pill>
                    <Pill v-if="member.status === 'invited'" variant="outline" tone="warning">
                      Приглашен
                    </Pill>
                  </Stack>
                </Stack>
              </Card>

              <!-- Карточка "Пригласить" -->
              <Card
                padding="lg"
                class="border-2 border-dashed border-gray-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-gray-100 flex items-center justify-center text-gray-400">
                    <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">Пригласить</Text>
                </Stack>
              </Card>
            </Grid>
          </Stack>
        </template>

        <!-- Участники заблокированы если KYC не пройден -->
        <Card v-else padding="lg" tone="muted" class="border-dashed">
          <Stack gap="3" align="center">
            <Text tone="muted" weight="semibold">🔒 Участники</Text>
            <Text tone="muted" align="center">
              Управление участниками будет доступно после прохождения верификации
            </Text>
          </Stack>
        </Card>
      </template>
    </Stack>
  </Section>
</template>

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

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

const localePath = useLocalePath()
const { loggedIn } = useAuth()
const { execute } = useGraphQL()
const { setActiveTeam } = useActiveTeam()

const userTeams = ref<any[]>([])
const currentTeam = ref<any>(null)
const showCreateForm = ref(false)
const isLoading = ref(true)
const hasError = ref(false)
const error = ref('')

const isKycApproved = computed(() => currentTeam.value?.status === 'KYC_APPROVED')

const kycIcon = (status?: string) => {
  if (status === 'KYC_APPROVED') return '✅'
  if (status === 'KYC_IN_REVIEW') return '⏳'
  if (status === 'PENDING_KYC') return '⏳'
  if (status === 'KYC_REJECTED') return '❌'
  return 'ℹ️'
}

const kycTitle = (status?: string) => {
  const map: Record<string, string> = {
    KYC_APPROVED: 'Верифицирована',
    KYC_IN_REVIEW: 'На проверке',
    PENDING_KYC: 'Требуется верификация',
    KYC_REJECTED: 'Верификация отклонена',
  }
  return map[status || ''] || 'Требуется верификация'
}

const roleText = (role?: string) => {
  const map: Record<string, string> = {
    OWNER: 'Владелец',
    ADMIN: 'Администратор',
    MANAGER: 'Менеджер',
    MEMBER: 'Участник',
  }
  return map[role || ''] || role || 'Участник'
}

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

    const meResult = await execute(GetMeDocument, {}, 'user', 'teams')
    const me = meResult.me
    userTeams.value = me?.teams?.filter((t): t is NonNullable<typeof t> => t !== null) || []

    if (me?.activeTeamId && me?.activeTeam) {
      setActiveTeam(me.activeTeamId, me.activeTeam.logtoOrgId)
      const teamResult = await execute(GetTeamDocument, { teamId: me.activeTeamId }, 'user', 'teams')
      currentTeam.value = teamResult.getTeam
    } else if (userTeams.value.length > 0) {
      const firstTeam = userTeams.value[0]
      setActiveTeam(firstTeam?.id || null, firstTeam?.logtoOrgId)
      currentTeam.value = firstTeam
    }
  } catch (err: any) {
    hasError.value = true
    error.value = err.message || 'Не удалось загрузить компании'
  } finally {
    isLoading.value = false
  }
}

const handleTeamCreated = async (team: any) => {
  showCreateForm.value = false
  currentTeam.value = team
  if (team?.id) {
    setActiveTeam(team.id, team.logtoOrgId)
  }
  await loadUserTeams()
}

const inviteMember = () => {
  // TODO: Открыть модалку приглашения
  alert('Функция приглашения участника в разработке')
}

onMounted(() => {
  if (loggedIn.value) {
    loadUserTeams()
  }
})
</script>
