<template>
  <Section variant="plain">
    <Stack gap="6">
        <Stack gap="2">
          <Stack direction="row" gap="2" align="center">
            <IconCircle tone="primary">🇷🇺</IconCircle>
            <Heading :level="1">{{ t('kycRussia.header.title') }}</Heading>
          </Stack>
          <Text tone="muted" size="base">
            {{ t('kycRussia.header.subtitle') }}
          </Text>
        </Stack>

        <Card v-if="submitting" tone="muted" padding="lg">
          <Stack align="center" justify="center" gap="3">
            <Spinner />
            <Text tone="muted">{{ t('kycRussia.states.submitting') }}</Text>
          </Stack>
        </Card>

        <Alert v-else-if="submitError" variant="error">
          <Stack gap="2">
            <Heading :level="4" weight="semibold">{{ t('kycRussia.errors.title') }}</Heading>
            <Text tone="muted">{{ submitError }}</Text>
          </Stack>
        </Alert>

        <Card v-else-if="submitSuccess" tone="muted" padding="lg">
          <Stack gap="2">
            <Heading :level="3" weight="semibold">{{ t('kycRussia.success.title') }}</Heading>
            <Text tone="muted">
              {{ t('kycRussia.success.description') }}
            </Text>
            <Button :as="'NuxtLink'" to="/clientarea/kyc" variant="outline">
              {{ t('kycRussia.success.cta') }}
            </Button>
          </Stack>
        </Card>

        <KYCFormRussia v-else @submit="handleSubmit" />
      </Stack>
  </Section>
</template>

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

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

const { mutate } = useGraphQL()
const { t } = useI18n()

const submitting = ref(false)
const submitError = ref<string | null>(null)
const submitSuccess = ref(false)

const handleSubmit = async (formData: any) => {
  try {
    submitting.value = true
    submitError.value = null

    const submitData = {
      companyName: formData.company_name,
      companyFullName: formData.company_full_name,
      inn: formData.inn,
      kpp: formData.kpp || '',
      ogrn: formData.ogrn || '',
      address: formData.address,
      bankName: formData.bank_name,
      bik: formData.bik,
      correspondentAccount: formData.correspondent_account || '',
      contactPerson: formData.contact_person,
      contactEmail: formData.contact_email,
      contactPhone: formData.contact_phone,
    }

    const result = await mutate(CreateKycRequestRussiaDocument, { input: submitData }, 'user', 'kyc')

    if (result.createKycRequestRussia?.success) {
      submitSuccess.value = true
      setTimeout(() => navigateTo('/clientarea/kyc'), 3000)
    } else {
      throw new Error(t('kycRussia.errors.create_failed'))
    }
  } catch (err: any) {
    submitError.value = err.message || t('kycRussia.errors.submit_failed')
  } finally {
    submitting.value = false
  }
}
</script>
