<template>
  <div class="p-6">
    <div class="mb-6">
      <h1 class="text-3xl font-bold">Dashboard</h1>
      <p class="text-muted-foreground">Welcome back, {{ user?.first_name }}! You're logged in as {{ formatRole(user?.role) }}.</p>
    </div>
    
    <!-- Role-specific stats cards -->
    <div class="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
      <!-- Artist Dashboard -->
      <template v-if="userRole === 'artist'">
        <div class="rounded-lg border bg-card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-muted-foreground">My Active Tasks</p>
              <p class="text-2xl font-bold">{{ dashboardStats.activeTasks }}</p>
            </div>
            <CheckSquare class="h-8 w-8 text-muted-foreground" />
          </div>
        </div>
        
        <div class="rounded-lg border bg-card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-muted-foreground">Pending Reviews</p>
              <p class="text-2xl font-bold">{{ dashboardStats.pendingReviews }}</p>
            </div>
            <Clock class="h-8 w-8 text-muted-foreground" />
          </div>
        </div>
        
        <div class="rounded-lg border bg-card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-muted-foreground">Completed Tasks</p>
              <p class="text-2xl font-bold">{{ dashboardStats.completedTasks }}</p>
            </div>
            <CheckCircle class="h-8 w-8 text-muted-foreground" />
          </div>
        </div>
        
        <div class="rounded-lg border bg-card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-muted-foreground">My Projects</p>
              <p class="text-2xl font-bold">{{ dashboardStats.myProjects }}</p>
            </div>
            <FolderOpen class="h-8 w-8 text-muted-foreground" />
          </div>
        </div>
      </template>

      <!-- Coordinator Dashboard -->
      <template v-else-if="userRole === 'coordinator'">
        <div class="rounded-lg border bg-card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-muted-foreground">Total Projects</p>
              <p class="text-2xl font-bold">{{ dashboardStats.totalProjects }}</p>
            </div>
            <FolderOpen class="h-8 w-8 text-muted-foreground" />
          </div>
        </div>
        
        <div class="rounded-lg border bg-card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-muted-foreground">Overdue Tasks</p>
              <p class="text-2xl font-bold text-red-600">{{ dashboardStats.overdueTasks }}</p>
            </div>
            <AlertTriangle class="h-8 w-8 text-red-600" />
          </div>
        </div>
        
        <div class="rounded-lg border bg-card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-muted-foreground">Active Artists</p>
              <p class="text-2xl font-bold">{{ dashboardStats.activeArtists }}</p>
            </div>
            <Users class="h-8 w-8 text-muted-foreground" />
          </div>
        </div>
        
        <div class="rounded-lg border bg-card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-muted-foreground">Completion Rate</p>
              <p class="text-2xl font-bold">{{ dashboardStats.completionRate }}%</p>
            </div>
            <TrendingUp class="h-8 w-8 text-green-600" />
          </div>
        </div>
      </template>

      <!-- Director Dashboard -->
      <template v-else-if="userRole === 'director'">
        <div class="rounded-lg border bg-card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-muted-foreground">Pending Reviews</p>
              <p class="text-2xl font-bold">{{ dashboardStats.pendingReviews }}</p>
            </div>
            <Eye class="h-8 w-8 text-muted-foreground" />
          </div>
        </div>
        
        <div class="rounded-lg border bg-card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-muted-foreground">Approved Today</p>
              <p class="text-2xl font-bold text-green-600">{{ dashboardStats.approvedToday }}</p>
            </div>
            <CheckCircle class="h-8 w-8 text-green-600" />
          </div>
        </div>
        
        <div class="rounded-lg border bg-card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-muted-foreground">Retakes Requested</p>
              <p class="text-2xl font-bold text-orange-600">{{ dashboardStats.retakesRequested }}</p>
            </div>
            <RotateCcw class="h-8 w-8 text-orange-600" />
          </div>
        </div>
        
        <div class="rounded-lg border bg-card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-muted-foreground">Projects</p>
              <p class="text-2xl font-bold">{{ dashboardStats.totalProjects }}</p>
            </div>
            <FolderOpen class="h-8 w-8 text-muted-foreground" />
          </div>
        </div>
      </template>

      <!-- Developer Dashboard -->
      <template v-else-if="userRole === 'developer'">
        <div class="rounded-lg border bg-card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-muted-foreground">API Keys</p>
              <p class="text-2xl font-bold">{{ dashboardStats.apiKeys }}</p>
            </div>
            <Key class="h-8 w-8 text-muted-foreground" />
          </div>
        </div>
        
        <div class="rounded-lg border bg-card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-muted-foreground">API Calls Today</p>
              <p class="text-2xl font-bold">{{ dashboardStats.apiCallsToday }}</p>
            </div>
            <Activity class="h-8 w-8 text-muted-foreground" />
          </div>
        </div>
        
        <div class="rounded-lg border bg-card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-muted-foreground">Total Projects</p>
              <p class="text-2xl font-bold">{{ dashboardStats.totalProjects }}</p>
            </div>
            <Database class="h-8 w-8 text-muted-foreground" />
          </div>
        </div>
        
        <div class="rounded-lg border bg-card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-muted-foreground">Total Tasks</p>
              <p class="text-2xl font-bold">{{ dashboardStats.totalTasks }}</p>
            </div>
            <CheckSquare class="h-8 w-8 text-muted-foreground" />
          </div>
        </div>
      </template>


    </div>

    <!-- Admin Features Section (shown when user has admin permission) -->
    <div v-if="isAdmin" class="mt-6">
      <h2 class="text-xl font-semibold mb-4">Administrative Overview</h2>
      <div class="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
        <div class="rounded-lg border bg-card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-muted-foreground">Total Users</p>
              <p class="text-2xl font-bold">{{ dashboardStats.totalUsers }}</p>
            </div>
            <Users class="h-8 w-8 text-muted-foreground" />
          </div>
        </div>
        
        <div class="rounded-lg border bg-card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-muted-foreground">Pending Approvals</p>
              <p class="text-2xl font-bold text-orange-600">{{ dashboardStats.pendingApprovals }}</p>
            </div>
            <UserCheck class="h-8 w-8 text-orange-600" />
          </div>
        </div>
        
        <div class="rounded-lg border bg-card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-muted-foreground">Active Projects</p>
              <p class="text-2xl font-bold">{{ dashboardStats.activeProjects }}</p>
            </div>
            <FolderOpen class="h-8 w-8 text-muted-foreground" />
          </div>
        </div>
        
        <div class="rounded-lg border bg-card p-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-muted-foreground">System Health</p>
              <p class="text-2xl font-bold text-green-600">Good</p>
            </div>
            <Shield class="h-8 w-8 text-green-600" />
          </div>
        </div>
      </div>
    </div>
    
    <!-- Role-specific content sections -->
    <div class="mt-6 grid gap-6 lg:grid-cols-2">
      <!-- Artist: My Tasks -->
      <template v-if="userRole === 'artist'">
        <div class="rounded-lg border bg-card">
          <div class="p-6 pb-4">
            <h3 class="text-lg font-semibold">My Active Tasks</h3>
          </div>
          <div class="px-6 pb-6">
            <div v-if="recentTasks.length === 0" class="text-center py-8">
              <CheckSquare class="h-12 w-12 mx-auto text-muted-foreground mb-4" />
              <p class="text-muted-foreground">No active tasks assigned</p>
            </div>
            <div v-else class="space-y-4">
              <div v-for="task in recentTasks" :key="task.id" class="flex items-center gap-3 p-3 rounded-lg bg-muted/50">
                <div class="h-2 w-2 rounded-full" :class="getTaskStatusColor(task.status)"></div>
                <div class="flex-1">
                  <p class="font-medium">{{ task.name }}</p>
                  <p class="text-sm text-muted-foreground">{{ task.project_name }}</p>
                </div>
                <div class="text-sm text-muted-foreground">{{ formatDeadline(task.deadline) }}</div>
              </div>
            </div>
          </div>
        </div>
      </template>

      <!-- Coordinator: Project Overview -->
      <template v-else-if="userRole === 'coordinator'">
        <div class="rounded-lg border bg-card">
          <div class="p-6 pb-4">
            <h3 class="text-lg font-semibold">Project Status Overview</h3>
          </div>
          <div class="px-6 pb-6">
            <div v-if="projectOverview.length === 0" class="text-center py-8">
              <FolderOpen class="h-12 w-12 mx-auto text-muted-foreground mb-4" />
              <p class="text-muted-foreground">No projects available</p>
            </div>
            <div v-else class="space-y-4">
              <div v-for="project in projectOverview" :key="project.id" class="flex items-center gap-3 p-3 rounded-lg bg-muted/50">
                <div class="h-2 w-2 rounded-full" :class="getProjectStatusColor(project.status)"></div>
                <div class="flex-1">
                  <p class="font-medium">{{ project.name }}</p>
                  <p class="text-sm text-muted-foreground">{{ project.completion_rate }}% complete</p>
                </div>
                <div class="text-sm text-muted-foreground">{{ project.member_count }} members</div>
              </div>
            </div>
          </div>
        </div>
      </template>

      <!-- Director: Pending Reviews -->
      <template v-else-if="userRole === 'director'">
        <div class="rounded-lg border bg-card">
          <div class="p-6 pb-4">
            <h3 class="text-lg font-semibold">Pending Reviews</h3>
          </div>
          <div class="px-6 pb-6">
            <div v-if="pendingReviews.length === 0" class="text-center py-8">
              <Eye class="h-12 w-12 mx-auto text-muted-foreground mb-4" />
              <p class="text-muted-foreground">No submissions pending review</p>
            </div>
            <div v-else class="space-y-4">
              <div v-for="submission in pendingReviews" :key="submission.id" class="flex items-center gap-3 p-3 rounded-lg bg-muted/50">
                <div class="h-2 w-2 rounded-full bg-orange-500"></div>
                <div class="flex-1">
                  <p class="font-medium">{{ submission.task_name }}</p>
                  <p class="text-sm text-muted-foreground">by {{ submission.artist_name }}</p>
                </div>
                <div class="text-sm text-muted-foreground">{{ formatSubmissionTime(submission.submitted_at) }}</div>
              </div>
            </div>
          </div>
        </div>
      </template>

      <!-- Developer: API Usage -->
      <template v-else-if="userRole === 'developer'">
        <div class="rounded-lg border bg-card">
          <div class="p-6 pb-4">
            <h3 class="text-lg font-semibold">Recent API Activity</h3>
          </div>
          <div class="px-6 pb-6">
            <div v-if="apiActivity.length === 0" class="text-center py-8">
              <Activity class="h-12 w-12 mx-auto text-muted-foreground mb-4" />
              <p class="text-muted-foreground">No recent API activity</p>
            </div>
            <div v-else class="space-y-4">
              <div v-for="activity in apiActivity" :key="activity.id" class="flex items-center gap-3 p-3 rounded-lg bg-muted/50">
                <div class="h-2 w-2 rounded-full bg-blue-500"></div>
                <div class="flex-1">
                  <p class="font-medium">{{ activity.endpoint }}</p>
                  <p class="text-sm text-muted-foreground">{{ activity.method }}</p>
                </div>
                <div class="text-sm text-muted-foreground">{{ formatTime(activity.timestamp) }}</div>
              </div>
            </div>
          </div>
        </div>
      </template>

      <!-- Admin: System Overview (when user has admin permission) -->
      <template v-else-if="isAdmin">
        <div class="rounded-lg border bg-card">
          <div class="p-6 pb-4">
            <h3 class="text-lg font-semibold">System Activity</h3>
          </div>
          <div class="px-6 pb-6">
            <div class="space-y-4">
              <div v-for="activity in systemActivity" :key="activity.id" class="flex items-center gap-3 p-3 rounded-lg bg-muted/50">
                <div class="h-2 w-2 rounded-full bg-green-500"></div>
                <div class="flex-1">
                  <p class="font-medium">{{ activity.action }}</p>
                  <p class="text-sm text-muted-foreground">{{ activity.description }}</p>
                </div>
                <div class="text-sm text-muted-foreground">{{ formatTime(activity.timestamp) }}</div>
              </div>
            </div>
          </div>
        </div>
      </template>

      <!-- Quick Actions Panel (for all roles) -->
      <div class="rounded-lg border bg-card">
        <div class="p-6 pb-4">
          <h3 class="text-lg font-semibold">Quick Actions</h3>
        </div>
        <div class="px-6 pb-6">
          <div class="grid gap-2">
            <!-- Artist Actions -->
            <template v-if="userRole === 'artist'">
              <Button variant="outline" class="justify-start" @click="navigateTo('/tasks')">
                <CheckSquare class="h-4 w-4 mr-2" />
                View My Tasks
              </Button>
              <Button variant="outline" class="justify-start" @click="navigateTo('/profile')">
                <User class="h-4 w-4 mr-2" />
                Update Profile
              </Button>
            </template>

            <!-- Coordinator Actions -->
            <template v-else-if="userRole === 'coordinator'">
              <Button variant="outline" class="justify-start" @click="navigateTo('/projects')">
                <FolderOpen class="h-4 w-4 mr-2" />
                Manage Projects
              </Button>
              <Button variant="outline" class="justify-start" @click="navigateTo('/tasks')">
                <CheckSquare class="h-4 w-4 mr-2" />
                Assign Tasks
              </Button>
            </template>

            <!-- Director Actions -->
            <template v-else-if="userRole === 'director'">
              <Button variant="outline" class="justify-start" @click="navigateTo('/reviews')">
                <Eye class="h-4 w-4 mr-2" />
                Review Submissions
              </Button>
              <Button variant="outline" class="justify-start" @click="navigateTo('/projects')">
                <FolderOpen class="h-4 w-4 mr-2" />
                View Projects
              </Button>
            </template>

            <!-- Developer Actions -->
            <template v-else-if="userRole === 'developer'">
              <Button variant="outline" class="justify-start" @click="navigateTo('/profile')">
                <Key class="h-4 w-4 mr-2" />
                Manage API Keys
              </Button>
              <Button variant="outline" class="justify-start" @click="navigateTo('/developer/docs')">
                <FileText class="h-4 w-4 mr-2" />
                API Documentation
              </Button>
            </template>

            <!-- Admin Actions (when user has admin permission) -->
            <template v-if="isAdmin">
              <Button variant="outline" class="justify-start" @click="navigateTo('/users')">
                <Users class="h-4 w-4 mr-2" />
                Manage Users
              </Button>
              <Button variant="outline" class="justify-start" @click="navigateTo('/projects')">
                <FolderOpen class="h-4 w-4 mr-2" />
                Manage Projects
              </Button>
            </template>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  CheckSquare, Clock, CheckCircle, FolderOpen, User, AlertTriangle, Users, 
  TrendingUp, Eye, RotateCcw, Key, Activity, Database, UserCheck, Shield,
  FileText
} from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()
const router = useRouter()

const user = computed(() => authStore.user)
const userRole = computed(() => authStore.userRole)
const isAdmin = computed(() => authStore.isAdmin)

// Dashboard stats (mock data for now - would be fetched from API)
const dashboardStats = ref({
  // Artist stats
  activeTasks: 0,
  pendingReviews: 0,
  completedTasks: 0,
  myProjects: 0,
  
  // Coordinator stats
  totalProjects: 0,
  overdueTasks: 0,
  activeArtists: 0,
  completionRate: 0,
  
  // Director stats
  approvedToday: 0,
  retakesRequested: 0,
  
  // Developer stats
  apiKeys: 0,
  apiCallsToday: 0,
  totalTasks: 0,
  
  // Admin stats
  totalUsers: 0,
  pendingApprovals: 0,
  activeProjects: 0
})

// Role-specific data
const recentTasks = ref([])
const projectOverview = ref([])
const pendingReviews = ref([])
const apiActivity = ref([])
const systemActivity = ref([
  {
    id: 1,
    action: 'User Registration',
    description: 'New user registered and awaiting approval',
    timestamp: new Date().toISOString()
  },
  {
    id: 2,
    action: 'Project Created',
    description: 'New project "Animation Series" created',
    timestamp: new Date(Date.now() - 3600000).toISOString()
  }
])

// Methods
const formatRole = (role?: string) => {
  if (!role) return ''
  return role.charAt(0).toUpperCase() + role.slice(1)
}

const formatDeadline = (deadline?: string) => {
  if (!deadline) return 'No deadline'
  const date = new Date(deadline)
  const now = new Date()
  const diffTime = date.getTime() - now.getTime()
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays < 0) return 'Overdue'
  if (diffDays === 0) return 'Due today'
  if (diffDays === 1) return 'Due tomorrow'
  return `${diffDays} days left`
}

const formatSubmissionTime = (timestamp: string) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diffTime = now.getTime() - date.getTime()
  const diffHours = Math.floor(diffTime / (1000 * 60 * 60))
  
  if (diffHours < 1) return 'Just now'
  if (diffHours === 1) return '1 hour ago'
  return `${diffHours} hours ago`
}

const formatTime = (timestamp: string) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diffTime = now.getTime() - date.getTime()
  const diffMinutes = Math.floor(diffTime / (1000 * 60))
  
  if (diffMinutes < 1) return 'Just now'
  if (diffMinutes < 60) return `${diffMinutes}m ago`
  const diffHours = Math.floor(diffMinutes / 60)
  if (diffHours < 24) return `${diffHours}h ago`
  const diffDays = Math.floor(diffHours / 24)
  return `${diffDays}d ago`
}

const getTaskStatusColor = (status: string) => {
  switch (status) {
    case 'not_started': return 'bg-gray-500'
    case 'in_progress': return 'bg-blue-500'
    case 'submitted': return 'bg-orange-500'
    case 'approved': return 'bg-green-500'
    case 'retake': return 'bg-red-500'
    default: return 'bg-gray-500'
  }
}

const getProjectStatusColor = (status: string) => {
  switch (status) {
    case 'planning': return 'bg-gray-500'
    case 'in_progress': return 'bg-blue-500'
    case 'on_hold': return 'bg-orange-500'
    case 'completed': return 'bg-green-500'
    case 'cancelled': return 'bg-red-500'
    default: return 'bg-gray-500'
  }
}

const navigateTo = (path: string) => {
  router.push(path)
}

const loadDashboardData = async () => {
  // Mock data loading - in real implementation, this would fetch from API based on user role
  try {
    // Load role-specific stats
    dashboardStats.value = {
      activeTasks: 5,
      pendingReviews: 2,
      completedTasks: 28,
      myProjects: 3,
      totalProjects: 8,
      overdueTasks: 3,
      activeArtists: 12,
      completionRate: 75,
      approvedToday: 8,
      retakesRequested: 2,
      apiKeys: 3,
      apiCallsToday: 156,
      totalTasks: 245,
      totalUsers: 25,
      pendingApprovals: 2,
      activeProjects: 5
    }
  } catch (error) {
    console.error('Failed to load dashboard data:', error)
  }
}

onMounted(() => {
  loadDashboardData()
})
</script>