<script lang="ts" setup>
import { ref } from 'vue'
import { useForm, usePage, router } from '@inertiajs/vue3'
import type { SharedPageProps } from '@/types'

interface Props {
  twoFactorEnabled: boolean
}

defineProps<Props>()

const page = usePage<SharedPageProps>()

const isCurrentPasswordVisible = ref<boolean>(false)
const isNewPasswordVisible = ref<boolean>(false)
const isConfirmPasswordVisible = ref<boolean>(false)

const passwordForm = useForm({
  current_password: '',
  password: '',
  password_confirmation: '',
})

const submitPassword = (): void => {
  passwordForm.put('/profile/password', {
    preserveScroll: true,
    onSuccess: () => {
      passwordForm.reset()
    },
  })
}

const resetPasswordForm = (): void => {
  passwordForm.reset()
  passwordForm.clearErrors()
}

const passwordRequirements: string[] = [
  'Minimum 8 characters long - the more, the better',
  'At least one lowercase character',
  'At least one uppercase character',
  'At least one number, symbol, or whitespace character',
]

// Two-factor authentication
const enabling = ref<boolean>(false)
const confirming = ref<boolean>(false)
const disabling = ref<boolean>(false)
const qrCode = ref<string>('')
const recoveryCodes = ref<string[]>([])

const confirmationForm = useForm({
  code: '',
})

const enableTwoFactor = (): void => {
  enabling.value = true
  router.post('/user/two-factor-authentication', {}, {
    preserveScroll: true,
    onSuccess: () => {
      confirming.value = true
      showQrCode()
      showRecoveryCodes()
    },
    onFinish: () => {
      enabling.value = false
    },
  })
}

const showQrCode = (): void => {
  fetch('/user/two-factor-qr-code')
    .then(r => r.json())
    .then((data: { svg: string }) => { qrCode.value = data.svg })
}

const showRecoveryCodes = (): void => {
  fetch('/user/two-factor-recovery-codes')
    .then(r => r.json())
    .then((data: string[]) => { recoveryCodes.value = data })
}

const confirmTwoFactor = (): void => {
  confirmationForm.post('/user/confirmed-two-factor-authentication', {
    preserveScroll: true,
    onSuccess: () => {
      confirming.value = false
    },
  })
}

const disableTwoFactor = (): void => {
  disabling.value = true
  router.delete('/user/two-factor-authentication', {
    preserveScroll: true,
    onSuccess: () => {
      qrCode.value = ''
      recoveryCodes.value = []
    },
    onFinish: () => {
      disabling.value = false
    },
  })
}
</script>

<template>
  <VRow>
    <!-- Change Password -->
    <VCol cols="12">
      <VCard title="Change Password">
        <VForm @submit.prevent="submitPassword">
          <VCardText class="pt-0">
            <VRow>
              <VCol
                cols="12"
                md="6"
              >
                <VTextField
                  v-model="passwordForm.current_password"
                  :type="isCurrentPasswordVisible ? 'text' : 'password'"
                  :append-inner-icon="isCurrentPasswordVisible ? 'tabler-eye-off' : 'tabler-eye'"
                  label="Current Password"
                  autocomplete="current-password"
                  placeholder="............"
                  :error-messages="passwordForm.errors.current_password ? [passwordForm.errors.current_password] : []"
                  @click:append-inner="isCurrentPasswordVisible = !isCurrentPasswordVisible"
                />
              </VCol>
            </VRow>

            <VRow>
              <VCol
                cols="12"
                md="6"
              >
                <VTextField
                  v-model="passwordForm.password"
                  :type="isNewPasswordVisible ? 'text' : 'password'"
                  :append-inner-icon="isNewPasswordVisible ? 'tabler-eye-off' : 'tabler-eye'"
                  label="New Password"
                  autocomplete="new-password"
                  placeholder="............"
                  :error-messages="passwordForm.errors.password ? [passwordForm.errors.password] : []"
                  @click:append-inner="isNewPasswordVisible = !isNewPasswordVisible"
                />
              </VCol>

              <VCol
                cols="12"
                md="6"
              >
                <VTextField
                  v-model="passwordForm.password_confirmation"
                  :type="isConfirmPasswordVisible ? 'text' : 'password'"
                  :append-inner-icon="isConfirmPasswordVisible ? 'tabler-eye-off' : 'tabler-eye'"
                  label="Confirm New Password"
                  autocomplete="new-password"
                  placeholder="............"
                  :error-messages="passwordForm.errors.password_confirmation ? [passwordForm.errors.password_confirmation] : []"
                  @click:append-inner="isConfirmPasswordVisible = !isConfirmPasswordVisible"
                />
              </VCol>
            </VRow>
          </VCardText>

          <VCardText>
            <h6 class="text-h6 text-medium-emphasis mb-4">
              Password Requirements:
            </h6>

            <VList class="card-list">
              <VListItem
                v-for="item in passwordRequirements"
                :key="item"
                :title="item"
                class="text-medium-emphasis"
              >
                <template #prepend>
                  <VIcon
                    size="10"
                    icon="tabler-circle-filled"
                  />
                </template>
              </VListItem>
            </VList>
          </VCardText>

          <VCardText class="d-flex flex-wrap gap-4">
            <VBtn
              type="submit"
              :loading="passwordForm.processing"
              :disabled="passwordForm.processing"
            >
              Save changes
            </VBtn>

            <VBtn
              color="secondary"
              variant="tonal"
              @click="resetPasswordForm"
            >
              Reset
            </VBtn>
          </VCardText>
        </VForm>
      </VCard>
    </VCol>

    <!-- Two-Factor Authentication -->
    <VCol cols="12">
      <VCard title="Two-Factor Authentication">
        <VCardText>
          <div v-if="!twoFactorEnabled && !confirming">
            <h5 class="text-h5 text-medium-emphasis mb-4">
              Two-factor authentication is not enabled yet.
            </h5>
            <p class="mb-6">
              Two-factor authentication adds an additional layer of security to your account by
              requiring more than just a password to log in. You will need to enter a code from your
              authenticator app each time you sign in.
            </p>

            <VBtn
              :loading="enabling"
              :disabled="enabling"
              @click="enableTwoFactor"
            >
              Enable two-factor authentication
            </VBtn>
          </div>

          <!-- QR Code confirmation step -->
          <div v-if="confirming">
            <div class="text-body-2 text-medium-emphasis mb-4">
              Scan this QR code with your authenticator app, then enter the code below to confirm.
            </div>

            <!-- eslint-disable-next-line vue/no-v-html -->
            <div
              v-if="qrCode"
              v-html="qrCode"
              class="mb-4 d-inline-block pa-4 rounded"
              style="background: white;"
            />

            <VForm
              @submit.prevent="confirmTwoFactor"
              style="max-width: 300px;"
            >
              <VTextField
                v-model="confirmationForm.code"
                label="Confirmation Code"
                type="text"
                inputmode="numeric"
                placeholder="000000"
                :error-messages="confirmationForm.errors.code ? [confirmationForm.errors.code] : []"
                class="mb-4"
              />

              <VBtn
                type="submit"
                :loading="confirmationForm.processing"
                :disabled="confirmationForm.processing"
              >
                Confirm
              </VBtn>
            </VForm>
          </div>

          <!-- Recovery codes -->
          <div v-if="recoveryCodes.length > 0 && !confirming">
            <div class="text-subtitle-2 font-weight-bold mb-2">
              Recovery Codes
            </div>
            <div class="text-body-2 text-medium-emphasis mb-3">
              Store these codes in a safe place. They can be used to access your account if you lose your authenticator device.
            </div>
            <VSheet
              rounded
              color="surface-variant"
              class="pa-4 font-weight-medium"
              style="font-family: monospace;"
            >
              <div
                v-for="code in recoveryCodes"
                :key="code"
              >
                {{ code }}
              </div>
            </VSheet>
          </div>

          <!-- 2FA enabled state -->
          <div v-if="twoFactorEnabled && !confirming">
            <VAlert
              type="success"
              variant="tonal"
              class="mb-4"
            >
              Two-factor authentication is enabled.
            </VAlert>

            <VBtn
              color="error"
              variant="tonal"
              :loading="disabling"
              :disabled="disabling"
              @click="disableTwoFactor"
            >
              Disable Two-Factor Authentication
            </VBtn>
          </div>
        </VCardText>
      </VCard>
    </VCol>

    <!-- Recent Devices (placeholder) -->
    <VCol cols="12">
      <VCard title="Recent Devices">
        <VDivider />
        <VCardText>
          <VTable>
            <thead>
              <tr>
                <th>BROWSER</th>
                <th>DEVICE</th>
                <th>LOCATION</th>
                <th>RECENT ACTIVITY</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td colspan="4" class="text-center text-medium-emphasis pa-6">
                  Session tracking will be available soon.
                </td>
              </tr>
            </tbody>
          </VTable>
        </VCardText>
      </VCard>
    </VCol>
  </VRow>
</template>

<style lang="scss" scoped>
.card-list {
  --v-card-list-gap: 16px;
}
</style>
