<template>
  <Section variant="plain">
    <Stack gap="6">
        <Stack gap="2">
          <Heading :level="1">{{ $t('dashboard.switch_company') }}</Heading>
          <Text tone="muted" size="base">{{ $t('teams.switch_description') }}</Text>
        </Stack>

        <Alert v-if="hasError" variant="error">
          <Stack gap="2">
            <Heading :level="4" weight="semibold">{{ $t('common.error') }}</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>

        <Card v-else-if="!userTeams.length && !showCreateForm" padding="lg">
          <Stack align="center" gap="3">
            <IconCircle tone="primary">🏢</IconCircle>
            <Heading :level="3" align="center">{{ $t('teams.no_team') }}</Heading>
            <Text tone="muted" align="center">{{ $t('teams.no_team_description') }}</Text>
            <Button @click="showCreateForm = true">
              {{ $t('teams.create_first_team') }}
            </Button>
          </Stack>
        </Card>

        <template v-else>
          <Grid :cols="1" :md="2" :lg="3" :gap="4" v-if="!showCreateForm">
            <Card
              v-for="team in userTeams"
              :key="team.id"
              padding="lg"
              :class="[
                'cursor-pointer transition-all',
                team.isActive ? 'ring-2 ring-primary bg-primary/5' : 'hover:shadow-md'
              ]"
              @click="switchToTeam(team.id)"
            >
              <Stack gap="3">
                <Stack direction="row" gap="3" align="center">
                  <IconCircle :tone="team.isActive ? 'primary' : 'neutral'">
                    {{ team.name?.charAt(0)?.toUpperCase() || '?' }}
                  </IconCircle>
                  <Stack gap="1">
                    <Heading :level="4" weight="semibold">{{ team.name }}</Heading>
                    <Text tone="muted" size="base">{{ kycIcon(team.status) }} {{ kycShort(team.status) }}</Text>
                  </Stack>
                </Stack>
                <Pill v-if="team.isActive" variant="primary">{{ $t('teams.active') }}</Pill>
              </Stack>
            </Card>

            <Card padding="lg" class="border-2 border-dashed border-gray-300 hover:border-primary cursor-pointer transition-colors" @click="showCreateForm = true">
              <Stack align="center" gap="3">
                <IconCircle tone="neutral">＋</IconCircle>
                <Heading :level="4" weight="semibold">{{ $t('teams.create_new_team') }}</Heading>
                <Text tone="muted" align="center">{{ $t('teams.create_description') }}</Text>
              </Stack>
            </Card>
          </Grid>

          <TeamCreateForm
            v-else
            @team-created="handleTeamCreated"
            @cancel="showCreateForm = false"
          />
        </template>
      </Stack>
  </Section>
</template>

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

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

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

const userTeams = ref<Array<{ id: string; name: string; status: string; isActive?: boolean }>>([])
const isLoading = ref(true)
const hasError = ref(false)
const error = ref('')
const showCreateForm = ref(false)

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

const kycShort = (status?: string) => {
  if (status === 'KYC_APPROVED') return 'Верифицирована'
  if (status === 'KYC_IN_REVIEW') return 'На проверке'
  if (status === 'PENDING_KYC') return 'Требуется верификация'
  if (status === 'KYC_REJECTED') return 'Отклонена'
  return 'KYC'
}

const currentActiveTeam = computed(() => userTeams.value.find(team => team.isActive) || null)
const otherTeams = computed(() => userTeams.value.filter(team => !team.isActive))

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

    const result = await execute(GetMeDocument, {}, 'user', 'teams')
    const me = result.me
    if (me?.teams) {
      userTeams.value = me.teams
        .filter((t): t is NonNullable<typeof t> => t !== null)
        .map(t => ({
          id: t.id || '',
          name: t.name,
          status: t.status,
          isActive: t.id === me.activeTeamId
        }))
    }
  } catch (err: any) {
    hasError.value = true
    error.value = err.message || 'Не удалось загрузить команды'
  } finally {
    isLoading.value = false
  }
}

const switchToTeam = async (teamId: string) => {
  try {
    const result = await execute(SwitchTeamDocument, { teamId }, 'user', 'teams')
    if (result.switchTeam?.user) {
      navigateTo(localePath('/dashboard/team'))
    }
  } catch (err: any) {
    error.value = err.message || 'Не удалось переключить команду'
    hasError.value = true
  }
}

const handleTeamCreated = () => {
  showCreateForm.value = false
  navigateTo(localePath('/dashboard/team'))
}

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