<script setup lang="ts">
import { reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Card, Typography, Form, Input, Button, message } from 'ant-design-vue'
import { useUserStore } from '../stores/userStore'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const loading = computed(() => userStore.loading)

const formState = reactive({
    email: '',
    firstName: '',
    lastName: '',
    password: '',
    confirmPassword: '',
    managerCode: '',
})

const confirmRules = [
    { required: true, message: 'Confirm your password' },
    {
        validator: (_: unknown, value: string) =>
            value === formState.password
                ? Promise.resolve()
                : Promise.reject('Passwords do not match'),
    },
]

const submit = async () => {
    try {
        const isManager = formState.managerCode === 'MANAGER2026'
        await userStore.register({
            email_address: formState.email,
            password: formState.password,
            confirm_password: formState.confirmPassword,
            first_name: formState.firstName,
            last_name: formState.lastName,
            manager: isManager,
        })
        message.success('Account created')
        const redirect = (route.query.redirect as string) || '/organization'
        router.push(redirect)
    } catch (error: unknown) {
        let errorMsg = 'Registration failed'
        if (userStore.error) {
            errorMsg = userStore.error
        } else if (typeof error === 'string') {
            errorMsg = error
        } else if (error instanceof Error) {
            errorMsg = error.message || 'Registration failed'
        } else if (typeof error === 'object' && error !== null) {
            const errObj = error as { [k: string]: unknown }
            const maybeResp = errObj?.response as unknown
            if (typeof maybeResp === 'object' && maybeResp !== null) {
                const respObj = maybeResp as { data?: unknown }
                const data = respObj.data
                if (typeof data === 'object' && data !== null) {
                    const detail = (data as { detail?: unknown }).detail
                    const msg = (data as { message?: unknown }).message
                    if (typeof detail === 'string') {
                        errorMsg = detail
                    } else if (typeof msg === 'string') {
                        errorMsg = msg
                    }
                }
            }
        }
        message.error(errorMsg)
    }
}

onMounted(async () => {
    await userStore.fetchSession()
    if (userStore.isAuthenticated) {
        const redirect = (route.query.redirect as string) || '/organization'
        router.replace(redirect)
    }
})
</script>

<template>
    <div class="auth-page">
        <Card class="panel" :bordered="false">
            <Typography.Title :level="3">Register</Typography.Title>
            <Form layout="vertical" :model="formState" @finish="submit">
                <Form.Item
                    label="Email"
                    name="email"
                    :rules="[
                        { required: true, message: 'Enter your email' },
                        {
                            type: 'email',
                            message: 'Please enter a valid email',
                        },
                    ]"
                >
                    <Input
                        v-model:value="formState.email"
                        type="email"
                        placeholder="Email address"
                        :disabled="loading"
                    />
                </Form.Item>
                <Form.Item
                    label="First name"
                    name="firstName"
                    :rules="[{ required: true, message: 'Enter your first name' }]"
                >
                    <Input
                        v-model:value="formState.firstName"
                        placeholder="First name"
                        :disabled="loading"
                    />
                </Form.Item>
                <Form.Item
                    label="Last name"
                    name="lastName"
                    :rules="[{ required: true, message: 'Enter your last name' }]"
                >
                    <Input
                        v-model:value="formState.lastName"
                        placeholder="Last name"
                        :disabled="loading"
                    />
                </Form.Item>
                <Form.Item
                    label="Password"
                    name="password"
                    :rules="[{ required: true, message: 'Create a password' }]"
                >
                    <Input.Password
                        v-model:value="formState.password"
                        placeholder="Password"
                        :disabled="loading"
                    />
                </Form.Item>
                <Form.Item label="Confirm password" name="confirmPassword" :rules="confirmRules">
                    <Input.Password
                        v-model:value="formState.confirmPassword"
                        placeholder="Confirm password"
                        :disabled="loading"
                    />
                </Form.Item>

                <Form.Item label="Manager code (optional) -> MANAGER2026" name="managerCode">
                    <Input
                        v-model:value="formState.managerCode"
                        placeholder="Enter manager code (leave blank if none)"
                        :disabled="loading"
                    />
                </Form.Item>

                <Button type="primary" html-type="submit" block :loading="loading">Register</Button>
            </Form>
        </Card>
    </div>
</template>

<style scoped>
.auth-page {
    max-width: 520px;
    margin: 0 auto;
    padding: 1rem;
}
</style>
