<script setup lang="ts">
import { usePage, router, Head } from '@inertiajs/vue3'
import { computed, ref } from 'vue'
import AppLayout from "@/layouts/AppLayout.vue"
import type { BreadcrumbItem } from "@/types"

import { Card, CardHeader, CardContent, CardTitle, CardDescription } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'

const license = usePage().props.license as {
    valid: boolean
    key?: string
    message?: string,
    expires_at?: string | null
}

const key = ref('')
const saving = ref(false)
const editing = ref(false)

const maskedKey = computed(() => {
    if (!license.key) return ''

    if (license.key.length <= 8) return '****'

    return `${license.key.slice(0, 4)}****${license.key.slice(-4)}`
})

function save() {
    saving.value = true

    router.post('/license', { license_key: key.value }, {
        onSuccess: () => {
            key.value = ''
            editing.value = false
        },
        onFinish: () => saving.value = false
    })
}

const daysLeft = computed(() => {
    if (!license.expires_at) return null

    const now = new Date()
    const exp = new Date(license.expires_at)

    const diff = exp.getTime() - now.getTime()

    return Math.ceil(diff / (1000 * 60 * 60 * 24))
})

const formattedDate = computed(() => {
    if (!license.expires_at) return null

    return new Date(license.expires_at).toLocaleDateString()
})

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Панель управления', href: '/dashboard' },
    { title: 'Лицензия', href: '' },
]
</script>

<template>
    <Head title="Лицензия" />

    <AppLayout :breadcrumbs="breadcrumbs">
        <div class="w-full px-4 sm:px-6 lg:px-10 py-6 space-y-6">

            <Card class="w-full shadow-none">

                <CardHeader class="space-y-2">
                    <CardTitle>Лицензия</CardTitle>
                    <CardDescription>
                        Управление лицензионным ключом
                    </CardDescription>
                </CardHeader>

                <!-- WARNING -->
                <div
                    v-if="license.valid && daysLeft !== null && daysLeft <= 15"
                    class="p-3 rounded-md bg-yellow-100 text-yellow-800 text-sm"
                >
                    ⚠️ Пожалуйста, продлите лицензию заранее, чтобы не потерять доступ к системе
                </div>

                <CardContent class="space-y-4">

                    <!-- STATUS -->
                    <div class="flex items-center justify-between">
                        <span class="text-sm text-muted-foreground">Статус</span>

                        <Badge :variant="license.valid ? 'default' : 'destructive'">
                            {{ license.valid ? 'Активна' : 'Не активна' }}
                        </Badge>
                    </div>

                    <!-- ERROR -->
                    <div v-if="!license.valid && license.message"
                         class="text-sm text-red-600">
                        {{ license.message }}
                    </div>

                    <!-- СРОК ДЕЙСТВИЯ -->
                    <div v-if="license.valid && license.expires_at" class="space-y-1">
                        <p class="text-sm text-muted-foreground">Действует до</p>
                        <p class="font-medium">
                            {{ formattedDate }} ({{ daysLeft }} дней)
                        </p>
                    </div>

                    <!-- ЕСЛИ ЕСТЬ КЛЮЧ И НЕ РЕДАКТИРУЕМ -->
                    <div v-if="license.valid && !editing" class="space-y-3">

                        <div>
                            <p class="text-sm text-muted-foreground">Ваш ключ</p>
                            <p class="font-mono text-lg">
                                {{ maskedKey }}
                            </p>
                        </div>

                        <Button
                            variant="outline"
                            class="w-full"
                            @click="editing = true"
                        >
                            Изменить ключ
                        </Button>

                    </div>

                    <!-- ВВОД КЛЮЧА -->
                    <div v-else class="space-y-3">

                        <Input
                            v-model="key"
                            placeholder="Введите лицензионный ключ"
                        />

                        <Button
                            class="w-full"
                            :disabled="saving || !key"
                            @click="save"
                        >
                            {{ saving ? 'Сохранение...' : 'Сохранить ключ' }}
                        </Button>

                    </div>

                </CardContent>

            </Card>

        </div>
    </AppLayout>
</template>
