<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { dataService } from '../services/dataService'
import Skeleton from 'primevue/skeleton'
import Button from 'primevue/button'
import Dialog from 'primevue/dialog'
import InputText from 'primevue/inputtext'
import Textarea from 'primevue/textarea'
import ConfirmDialog from 'primevue/confirmdialog'
import Toast from 'primevue/toast'
import { useConfirm } from 'primevue/useconfirm'
import { useToast } from 'primevue/usetoast'

const router = useRouter()
const confirm = useConfirm()
const toast = useToast()

const characters = ref([])
const loading = ref(true)
const showCreateDialog = ref(false)
const creating = ref(false)
const newCharacter = ref({
    name: '',
    character_bio: '',
    avatar_image: '' // Optional for now
})

const API_URL = import.meta.env.VITE_API_URL

onMounted(async () => {
    await fetchCharacters()
})

const fetchCharacters = async () => {
    loading.value = true
    try {
        characters.value = await dataService.getCharacters()
    } catch (e) {
        console.error('Failed to load characters', e)
        toast.add({ severity: 'error', summary: 'Error', detail: 'Failed to load characters', life: 3000 })
    } finally {
        loading.value = false
    }
}

const goToDetail = (id) => {
    router.push({ name: 'character-detail', params: { id } })
}

const selectedAvatarFile = ref(null)

const onFileSelect = (event) => {
    const file = event.target.files[0]
    if (file) {
        selectedAvatarFile.value = file
    }
}

const openCreateDialog = () => {
    newCharacter.value = { name: '', character_bio: '', avatar_image: '' }
    selectedAvatarFile.value = null
    showCreateDialog.value = true
}

const createCharacter = async () => {
    if (!newCharacter.value.name.trim()) return

    creating.value = true
    try {
        // Upload avatar if selected
        if (selectedAvatarFile.value) {
            const uploadResult = await dataService.uploadAsset(selectedAvatarFile.value)
            // Assuming uploadAsset returns object with 'url' or 'path' or similar. 
            // The dataService.uploadAsset returns response.data. 
            // Let's assume response.data has 'url' or is the url string? 
            // Checking dataService.js: returns response.data. usage in other places implies it might be the asset object.
            // Let's check typical asset response. It likely has 'url' or 'file_path'.
            // I'll assume it returns an Asset object and I should use its url.
            if (uploadResult && uploadResult.url) {
                newCharacter.value.avatar_image = uploadResult.url
            } else if (uploadResult && uploadResult.file_path) {
                newCharacter.value.avatar_image = uploadResult.file_path
            }
        }

        await dataService.createCharacter(newCharacter.value)
        toast.add({ severity: 'success', summary: 'Success', detail: 'Character created', life: 3000 })
        showCreateDialog.value = false
        await fetchCharacters()
    } catch (e) {
        console.error('Failed to create character', e)
        toast.add({ severity: 'error', summary: 'Error', detail: 'Failed to create character', life: 3000 })
    } finally {
        creating.value = false
    }
}

const confirmDelete = (event, id) => {
    event.stopPropagation() // Prevent card click
    confirm.require({
        message: 'Are you sure you want to delete this character?',
        header: 'Delete Confirmation',
        icon: 'pi pi-exclamation-triangle',
        acceptClass: 'p-button-danger',
        rejectClass: 'p-button-secondary',
        acceptLabel: 'Delete',
        rejectLabel: 'Cancel',
        accept: async () => {
            try {
                await dataService.deleteCharacter(id)
                toast.add({ severity: 'success', summary: 'Success', detail: 'Character deleted', life: 3000 })
                await fetchCharacters()
            } catch (e) {
                console.error('Failed to delete character', e)
                toast.add({ severity: 'error', summary: 'Error', detail: 'Failed to delete character', life: 3000 })
            }
        }
    })
}
</script>

<template>
    <div class="flex flex-col h-full p-8 overflow-y-auto text-slate-100 relative">
        <Toast />
        <ConfirmDialog />

        <!-- Top Bar -->
        <header class="flex justify-between items-end mb-8">
            <div>
                <h1 class="text-4xl font-bold m-0">Characters</h1>
                <p class="mt-2 mb-0 text-slate-400">Manage your AI personas</p>
            </div>
            <Button label="Create Character" icon="pi pi-plus" @click="openCreateDialog" />
        </header>

        <!-- Loading State -->
        <div v-if="loading" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <div v-for="i in 6" :key="i" class="glass-panel rounded-2xl p-6 flex items-center gap-6">
                <Skeleton shape="circle" size="5rem" />
                <div class="flex-1">
                    <Skeleton class="mb-2" height="1.5rem" />
                    <Skeleton height="1rem" />
                </div>
            </div>
        </div>

        <!-- Characters Grid -->
        <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <div v-for="char in characters" :key="char.id"
                class="glass-panel rounded-2xl p-6 flex items-center gap-6 transition-all duration-300 cursor-pointer border border-white/5 hover:-translate-y-1 hover:bg-white/5 hover:border-white/10 relative group"
                @click="goToDetail(char.id)">

                <!-- Delete Button (Visible on Hover) -->
                <button
                    class="absolute top-2 right-2 p-2 rounded-full hover:bg-red-500/20 text-slate-400 hover:text-red-400 opacity-0 group-hover:opacity-100 transition-all z-10"
                    @click="(e) => confirmDelete(e, char.id)" title="Delete Character">
                    <i class="pi pi-trash"></i>
                </button>

                <div class="w-20 h-20 rounded-full overflow-hidden flex-shrink-0 border-3 border-white/10 bg-slate-800">
                    <img v-if="char.avatar_image" :src="API_URL + char.avatar_image" :alt="char.name"
                        class="w-full h-full object-cover" />
                    <div v-else class="w-full h-full flex items-center justify-center text-slate-500">
                        <i class="pi pi-user text-2xl"></i>
                    </div>
                </div>
                <div class="flex-1 overflow-hidden">
                    <h3 class="m-0 mb-2 text-xl font-semibold truncate pr-6">{{ char.name }}</h3>
                    <p class="m-0 text-sm text-slate-400 line-clamp-2">
                        {{ char.character_bio || 'No bio provided.' }}
                    </p>
                </div>
            </div>
        </div>

        <!-- Create Character Dialog -->
        <Dialog v-model:visible="showCreateDialog" modal header="Create New Character" :style="{ width: '30rem' }">
            <div class="flex flex-col gap-4 pt-4">
                <div class="flex flex-col gap-2">
                    <label class="font-semibold">Avatar</label>
                    <input type="file" accept="image/*" @change="onFileSelect"
                        class="text-slate-300 text-sm file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-violet-500/10 file:text-violet-400 hover:file:bg-violet-500/20 file:cursor-pointer" />
                </div>
                <div class="flex flex-col gap-2">
                    <label for="name" class="font-semibold">Name</label>
                    <InputText id="name" v-model="newCharacter.name" class="w-full" autofocus />
                </div>
                <div class="flex flex-col gap-2">
                    <label for="bio" class="font-semibold">Bio</label>
                    <Textarea id="bio" v-model="newCharacter.character_bio" rows="3" class="w-full" />
                </div>
            </div>
            <template #footer>
                <Button label="Cancel" text severity="secondary" @click="showCreateDialog = false" />
                <Button label="Create" icon="pi pi-check" @click="createCharacter" :loading="creating"
                    :disabled="!newCharacter.name.trim()" />
            </template>
        </Dialog>
    </div>
</template>

<style scoped>
/* Line clamp utility for older browsers */
.line-clamp-2 {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}
</style>
