<template>
    <div class="h-full overflow-y-auto custom-scrollbar">
        <div v-if="project" class="container mx-auto p-4 md:p-8 animate-fade-in">
            <!-- Header -->
            <div class="glass-panel p-8 rounded-xl mb-8 relative overflow-hidden">
                <div class="absolute top-0 right-0 p-4 opacity-10">
                    <i class="pi pi-folder text-9xl text-white"></i>
                </div>

                <div class="relative z-10">
                    <div class="flex items-center gap-3 mb-2">
                        <Button icon="pi pi-arrow-left" text rounded @click="router.push('/projects')" />
                        <span v-if="isCurrentProject"
                            class="bg-green-500/20 text-green-400 text-xs px-2 py-1 rounded-full border border-green-500/30 font-medium">
                            Active Project
                        </span>
                    </div>

                    <h1 class="text-4xl font-bold text-white mb-4">{{ project.name }}</h1>
                    <p class="text-slate-300 text-lg max-w-2xl mb-6">
                        {{ project.description || 'No description provided.' }}
                    </p>

                    <div class="flex gap-3">
                        <Button v-if="!isCurrentProject" label="Set as Active" icon="pi pi-check" @click="selectProject" />
                        <Button v-if="isOwner" label="Delete" icon="pi pi-trash" severity="danger" outlined
                            @click="confirmDelete" />
                        <Button label="Settings" icon="pi pi-cog" severity="secondary" outlined />
                    </div>
                </div>
            </div>

            <!-- Confirm Dialog -->
            <ConfirmDialog />

            <!-- Content Grid -->
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                <!-- Members Column -->
                <div class="lg:col-span-1">
                    <div class="glass-panel p-6 rounded-xl h-full">
                        <div class="flex justify-between items-center mb-6">
                            <h2 class="text-xl font-bold text-white">Team Members</h2>
                        </div>
                        <!-- Inline Add Member -->
                        <div v-if="isOwner" class="mb-6">
                            <div class="flex gap-2">
                                <InputText v-model="inviteUsername" placeholder="Username to add"
                                    class="w-full p-inputtext-sm" @keyup.enter="addMember" />
                                <Button label="Add" icon="pi pi-user-plus" size="small" @click="addMember"
                                    :loading="inviting" :disabled="!inviteUsername.trim()" />
                            </div>
                        </div>

                                            <div class="flex flex-col gap-4">
                                                <div v-for="member in project.members" :key="member.id"
                                                    class="flex items-center p-3 rounded-lg bg-slate-800/30 border border-slate-700/30">
                                                    <div
                                                        class="w-10 h-10 rounded-full bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center text-white font-bold mr-3">
                                                        <i class="pi pi-user"></i>
                                                    </div>
                                                    <div class="overflow-hidden">
                                                        <p class="text-white font-bold truncate">{{ member.username }}</p>
                                                        <p class="text-slate-500 text-[10px] truncate font-mono">ID: {{ member.id }}</p>
                                                    </div>
                                                    <div class="ml-auto" v-if="project.owner_id === member.id">
                                                        <i class="pi pi-crown text-yellow-500" title="Owner"></i>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                        
                                    <!-- Stats/Activity Column -->
                                    <div class="lg:col-span-2">
                                        <div class="glass-panel p-6 rounded-xl h-full flex flex-col">
                                            <div class="flex justify-between items-center mb-6">
                                                <h2 class="text-xl font-bold text-white">Usage Statistics</h2>
                                                <Button icon="pi pi-refresh" text rounded @click="fetchUsage" :loading="loadingUsage" />
                                            </div>
                        
                                            <div v-if="usageReport" class="flex-1 flex flex-col gap-8">
                                                <!-- Summary Cards -->
                                                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                                    <div class="p-4 rounded-xl bg-slate-800/40 border border-white/5 text-center">
                                                        <p class="text-slate-500 text-xs uppercase font-bold tracking-wider mb-1">Total Runs</p>
                                                        <p class="text-2xl font-bold text-white">{{ usageReport.summary?.total_runs || 0 }}</p>
                                                    </div>
                                                    <div class="p-4 rounded-xl bg-slate-800/40 border border-white/5 text-center">
                                                        <p class="text-slate-500 text-xs uppercase font-bold tracking-wider mb-1">Total Tokens</p>
                                                        <p class="text-2xl font-bold text-white">{{ (usageReport.summary?.total_tokens || 0).toLocaleString() }}</p>
                                                    </div>
                                                    <div class="p-4 rounded-xl bg-violet-500/10 border border-violet-500/20 text-center">
                                                        <p class="text-violet-400 text-xs uppercase font-bold tracking-wider mb-1">Total Spend</p>
                                                        <p class="text-2xl font-bold text-violet-300">${{ (usageReport.summary?.total_cost || 0).toFixed(2) }}</p>
                                                    </div>
                                                </div>
                        
                                                <!-- User Breakdown -->
                                                <div v-if="usageReport.by_user && usageReport.by_user.length > 0">
                                                    <h3 class="text-sm font-bold text-slate-400 uppercase tracking-wider mb-4">Usage by Member</h3>
                                                    <div class="flex flex-col gap-2">
                                                        <div v-for="item in usageReport.by_user" :key="item.entity_id" 
                                                            class="flex items-center justify-between p-3 rounded-lg bg-slate-800/20 border border-white/5">
                                                            <div class="flex items-center gap-3">
                                                                <div class="w-8 h-8 rounded-full bg-slate-700 flex items-center justify-center text-[10px] font-bold">
                                                                    {{ (getMemberUsername(item.entity_id) || '??').substring(0,2).toUpperCase() }}
                                                                </div>
                                                                <div class="flex flex-col">
                                                                    <span class="text-sm text-slate-300 font-bold truncate max-w-[150px]">{{ getMemberUsername(item.entity_id) || 'Unknown' }}</span>
                                                                    <span class="text-[9px] text-slate-500 font-mono">{{ item.entity_id }}</span>
                                                                </div>
                                                            </div>
                                                            <div class="flex gap-6 text-right">
                                                                <div>
                                                                    <p class="text-[10px] text-slate-500 uppercase font-bold">Runs</p>
                                                                    <p class="text-sm text-white">{{ item.stats.total_runs }}</p>
                                                                </div>
                                                                <div>
                                                                    <p class="text-[10px] text-slate-500 uppercase font-bold">Cost</p>
                                                                    <p class="text-sm text-violet-300">${{ item.stats.total_cost.toFixed(2) }}</p>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                        <div v-else-if="loadingUsage" class="flex-1 flex items-center justify-center py-20">
                             <i class="pi pi-spin pi-spinner text-4xl text-violet-500"></i>
                        </div>

                        <div v-else class="text-center py-12 text-slate-500 flex-1 flex flex-col justify-center">
                            <i class="pi pi-chart-line text-4xl mb-4 opacity-50"></i>
                            <p>No usage data available for this project.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div v-else class="flex justify-center items-center h-full">
            <div class="text-center">
                <i class="pi pi-spin pi-spinner text-4xl text-primary-500 mb-4"></i>
                <p class="text-slate-400">Loading project...</p>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useProjectsStore } from '@/stores/projectsStore';
import { storeToRefs } from 'pinia';
import { useAuthStore } from '@/stores/auth';
import { aiService } from '@/services/aiService';
import Button from 'primevue/button';
import InputText from 'primevue/inputtext';
import ConfirmDialog from 'primevue/confirmdialog';
import { useConfirm } from 'primevue/useconfirm';

const route = useRoute();
const router = useRouter(); // Missing import fixed
const projectsStore = useProjectsStore();
const authStore = useAuthStore();
const { projects, currentProject } = storeToRefs(projectsStore);

const projectId = route.params.id;
const project = computed(() => projectsStore.getProjectById(projectId));
const isCurrentProject = computed(() => currentProject.value?.id === projectId);
const isOwner = computed(() => authStore.user && project.value && authStore.user.id === project.value.owner_id);

const getMemberUsername = (memberId) => {
    if (!project.value || !project.value.members) return null;
    const member = project.value.members.find(m => m.id === memberId);
    return member ? member.username : null;
};

const inviteUsername = ref('');
const inviting = ref(false);

const usageReport = ref(null);
const loadingUsage = ref(false);

const fetchUsage = async () => {
    loadingUsage.value = true;
    try {
        // Pass projectId from route params to ensure we get stats for THIS project
        usageReport.value = await aiService.getUsageReport("user", projectId);
    } catch (e) {
        console.error("Failed to fetch usage report", e);
    } finally {
        loadingUsage.value = false;
    }
};

onMounted(async () => {
    // Ensure projects are loaded
    if (projects.value.length === 0) {
        await projectsStore.fetchProjects();
    }
    fetchUsage();
});

const selectProject = () => {
    if (project.value) {
        projectsStore.selectProject(project.value.id);
    }
}

const addMember = async () => {
    if (!inviteUsername.value.trim()) return;

    inviting.value = true;
    try {
        await projectsStore.addMember(projectId, inviteUsername.value);
        inviteUsername.value = '';
    } catch (e) {
        console.error(e);
        // Toast error here ideally
    } finally {
        inviting.value = false;
    }
}

const confirm = useConfirm();
const confirmDelete = () => {
    confirm.require({
        message: 'Are you sure you want to delete this project? This action cannot be undone.',
        header: 'Delete Confirmation',
        icon: 'pi pi-exclamation-triangle',
        acceptClass: 'p-button-danger',
        acceptLabel: 'Delete',
        rejectLabel: 'Cancel',
        accept: async () => {
            try {
                await projectsStore.deleteProject(projectId);
                router.push('/projects');
            } catch (e) {
                console.error("Failed to delete", e);
            }
        }
    });
}
</script>

<style scoped>
.custom-scrollbar::-webkit-scrollbar {
    width: 6px;
}

.custom-scrollbar::-webkit-scrollbar-track {
    background: transparent;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
    background: rgba(255, 255, 255, 0.1);
    border-radius: 3px;
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
    background: rgba(255, 255, 255, 0.2);
}
</style>
