<template>
  <div class="space-y-4">
    <!-- Filters -->
    <div class="flex flex-wrap gap-4 items-center">
      <div class="flex-1 min-w-[200px]">
        <Input
          v-model="searchQuery"
          placeholder="Search tasks..."
          class="w-full"
        />
      </div>
      
      <Select v-model="statusFilter">
        <SelectTrigger class="w-[180px]">
          <SelectValue placeholder="Filter by status" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="all">All Statuses</SelectItem>
          <SelectItem value="not_started">Not Started</SelectItem>
          <SelectItem value="in_progress">In Progress</SelectItem>
          <SelectItem value="submitted">Submitted</SelectItem>
          <SelectItem value="approved">Approved</SelectItem>
          <SelectItem value="retake">Retake</SelectItem>
        </SelectContent>
      </Select>

      <Select v-model="taskTypeFilter">
        <SelectTrigger class="w-[180px]">
          <SelectValue placeholder="Filter by type" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="all">All Types</SelectItem>
          <SelectItem value="layout">Layout</SelectItem>
          <SelectItem value="animation">Animation</SelectItem>
          <SelectItem value="simulation">Simulation</SelectItem>
          <SelectItem value="lighting">Lighting</SelectItem>
          <SelectItem value="compositing">Compositing</SelectItem>
          <SelectItem value="modeling">Modeling</SelectItem>
          <SelectItem value="surfacing">Surfacing</SelectItem>
          <SelectItem value="rigging">Rigging</SelectItem>
        </SelectContent>
      </Select>

      <Select v-if="showDepartmentFilter" v-model="departmentFilter">
        <SelectTrigger class="w-[180px]">
          <SelectValue placeholder="Filter by department" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="all">All Departments</SelectItem>
          <SelectItem value="layout">Layout</SelectItem>
          <SelectItem value="animation">Animation</SelectItem>
          <SelectItem value="lighting">Lighting</SelectItem>
          <SelectItem value="composite">Composite</SelectItem>
          <SelectItem value="modeling">Modeling</SelectItem>
          <SelectItem value="surfacing">Surfacing</SelectItem>
          <SelectItem value="rigging">Rigging</SelectItem>
        </SelectContent>
      </Select>

      <Select v-model="sortBy">
        <SelectTrigger class="w-[180px]">
          <SelectValue placeholder="Sort by" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="deadline">Deadline</SelectItem>
          <SelectItem value="status">Status</SelectItem>
          <SelectItem value="name">Name</SelectItem>
          <SelectItem value="updated">Last Updated</SelectItem>
        </SelectContent>
      </Select>

      <Button
        variant="outline"
        size="sm"
        @click="clearFilters"
      >
        Clear Filters
      </Button>
    </div>

    <!-- Task Table -->
    <div class="border rounded-lg">
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>Task</TableHead>
            <TableHead>Type</TableHead>
            <TableHead>Status</TableHead>
            <TableHead>Deadline</TableHead>
            <TableHead>Project</TableHead>
            <TableHead>Context</TableHead>
            <TableHead>Actions</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          <TableRow
            v-for="task in filteredAndSortedTasks"
            :key="task.id"
            class="cursor-pointer hover:bg-muted/50"
            @click="selectTask(task)"
          >
            <TableCell>
              <div class="font-medium">{{ task.name }}</div>
              <div v-if="task.assigned_user_name" class="flex items-center gap-2 mt-1">
                <Avatar class="h-5 w-5">
                  <AvatarImage
                    v-if="task.assigned_user_id"
                    :src="getAvatarUrl(task.assigned_user_avatar_url, task.assigned_user_first_name, task.assigned_user_last_name)"
                  />
                  <AvatarImage
                    v-else
                    :src="`getInitialsAvatarUrl(task.assigned_user_name)`"
                  />
                  <AvatarFallback class="text-[10px]">{{ getAssignedUserInitials(task.assigned_user_name) }}</AvatarFallback>
                </Avatar>
                <span class="text-sm text-muted-foreground">{{ task.assigned_user_name }}</span>
              </div>
            </TableCell>
            <TableCell>
              <Badge variant="outline">{{ formatTaskType(task.task_type) }}</Badge>
            </TableCell>
            <TableCell @click.stop>
              <Select
                :model-value="task.status"
                @update:model-value="(value) => handleStatusUpdate(task.id, value)"
              >
                <SelectTrigger class="w-[130px]">
                  <SelectValue>
                    <TaskStatusBadge :status="task.status" />
                  </SelectValue>
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="not_started">
                    <div class="flex items-center gap-2">
                      <div class="w-2 h-2 rounded-full bg-gray-400"></div>
                      <span>Not Started</span>
                    </div>
                  </SelectItem>
                  <SelectItem value="in_progress">
                    <div class="flex items-center gap-2">
                      <div class="w-2 h-2 rounded-full bg-blue-500"></div>
                      <span>In Progress</span>
                    </div>
                  </SelectItem>
                  <SelectItem value="submitted">
                    <div class="flex items-center gap-2">
                      <div class="w-2 h-2 rounded-full bg-purple-500"></div>
                      <span>Submitted</span>
                    </div>
                  </SelectItem>
                  <SelectItem value="approved">
                    <div class="flex items-center gap-2">
                      <div class="w-2 h-2 rounded-full bg-green-500"></div>
                      <span>Approved</span>
                    </div>
                  </SelectItem>
                  <SelectItem value="retake">
                    <div class="flex items-center gap-2">
                      <div class="w-2 h-2 rounded-full bg-red-500"></div>
                      <span>Retake</span>
                    </div>
                  </SelectItem>
                </SelectContent>
              </Select>
            </TableCell>
            <TableCell>
              <div v-if="task.deadline" class="flex items-center gap-2">
                <div :class="getDeadlineContainerClass(task.deadline, task.status)" class="flex items-center gap-2 px-2 py-1 rounded">
                  <AlertCircle
                    v-if="isOverdue(task.deadline, task.status)"
                    class="h-4 w-4"
                  />
                  <Clock
                    v-else-if="isUrgent(task.deadline, task.status)"
                    class="h-4 w-4"
                  />
                  <span :class="getDeadlineTextClass(task.deadline, task.status)">
                    {{ formatDate(task.deadline) }}
                  </span>
                </div>
              </div>
              <span v-else class="text-muted-foreground">No deadline</span>
            </TableCell>
            <TableCell>
              <div class="text-sm">{{ task.project_name }}</div>
            </TableCell>
            <TableCell>
              <div class="text-sm text-muted-foreground">
                <div v-if="task.shot_name">Shot: {{ task.shot_name }}</div>
                <div v-if="task.asset_name">Asset: {{ task.asset_name }}</div>
                <div v-if="task.episode_name" class="text-xs">{{ task.episode_name }}</div>
              </div>
            </TableCell>
            <TableCell @click.stop>
              <div class="flex items-center gap-2">
                <Button
                  v-if="canAssignTasks"
                  variant="ghost"
                  size="sm"
                  @click="openAssignDialog(task)"
                  title="Assign task to a team member"
                >
                  <UserPlus class="h-4 w-4 mr-1" />
                  <span class="hidden sm:inline">Assign</span>
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  @click="selectTask(task)"
                  title="View task details"
                >
                  <Eye class="h-4 w-4 mr-1" />
                  <span class="hidden sm:inline">View</span>
                </Button>
              </div>
            </TableCell>
          </TableRow>
          <TableRow v-if="filteredAndSortedTasks.length === 0">
            <TableCell colspan="7" class="text-center text-muted-foreground py-8">
              No tasks found
            </TableCell>
          </TableRow>
        </TableBody>
      </Table>
    </div>

    <!-- Task Assignment Dialog -->
    <Dialog v-model:open="assignDialogOpen">
      <DialogContent class="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Assign Task</DialogTitle>
          <DialogDescription>
            Assign "{{ selectedTaskForAssignment?.name }}" to a team member
          </DialogDescription>
        </DialogHeader>
        <div class="space-y-4 py-4">
          <div class="space-y-2">
            <Label>Filter by Department</Label>
            <Select v-model="assignmentDepartmentFilter">
              <SelectTrigger>
                <SelectValue placeholder="All departments" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Departments</SelectItem>
                <SelectItem value="layout">Layout</SelectItem>
                <SelectItem value="animation">Animation</SelectItem>
                <SelectItem value="lighting">Lighting</SelectItem>
                <SelectItem value="composite">Composite</SelectItem>
                <SelectItem value="modeling">Modeling</SelectItem>
                <SelectItem value="surfacing">Surfacing</SelectItem>
                <SelectItem value="rigging">Rigging</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div class="space-y-2">
            <Label>Assign to</Label>
            <Select v-model="selectedUserId">
              <SelectTrigger>
                <SelectValue placeholder="Select a user" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem
                  v-for="member in filteredProjectMembers"
                  :key="member.user_id"
                  :value="member.user_id.toString()"
                >
                  <div class="flex items-center gap-2 w-full">
                    <Avatar class="h-6 w-6">
                      <AvatarImage
                        v-if="member.user_id"
                        :src="getAvatarUrl(member.user_avatar_url, member.user_first_name, member.user_last_name)"
                      />
                      <AvatarImage
                        v-else
                        :src="`https://ui-avatars.com/api/?name=${member.user_first_name} ${member.user_last_name}`"
                      />
                      <AvatarFallback class="text-xs">{{ member.user_first_name.charAt(0) }}{{ member.user_last_name.charAt(0) }}</AvatarFallback>
                    </Avatar>
                    <span>{{ member.user_first_name }} {{ member.user_last_name }}</span>
                    <Badge variant="outline" class="ml-auto">{{ formatDepartmentRole(member.department_role) }}</Badge>
                  </div>
                </SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" @click="assignDialogOpen = false">Cancel</Button>
          <Button @click="handleAssignTask" :disabled="!selectedUserId || assigningTask">
            <Loader2 v-if="assigningTask" class="mr-2 h-4 w-4 animate-spin" />
            Assign Task
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useTasksStore } from '@/stores/tasks'
import { useAuthStore } from '@/stores/auth'
import { AlertCircle, Clock, UserPlus, Loader2, Eye } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Badge } from '@/components/ui/badge'
import TaskStatusBadge from './TaskStatusBadge.vue'
import type { TaskListItem } from '@/services/task'
import { taskService } from '@/services/task'
import { projectService, type ProjectMember } from '@/services/project'
import { useToast } from '@/components/ui/toast/use-toast'

const props = defineProps<{
  projectId?: number
}>()

const emit = defineEmits<{
  taskSelected: [task: TaskListItem]
}>()

const tasksStore = useTasksStore()
const authStore = useAuthStore()
const { toast } = useToast()

const searchQuery = ref('')
const statusFilter = ref('all')
const taskTypeFilter = ref('all')
const departmentFilter = ref('all')
const sortBy = ref('deadline')

// Task assignment
const assignDialogOpen = ref(false)
const selectedTaskForAssignment = ref<TaskListItem | null>(null)
const selectedUserId = ref<string>('')
const assignmentDepartmentFilter = ref('all')
const projectMembers = ref<ProjectMember[]>([])
const assigningTask = ref(false)

const canAssignTasks = computed(() => {
  return authStore.user?.is_admin || authStore.user?.role === 'coordinator'
})

const showDepartmentFilter = computed(() => {
  return canAssignTasks.value
})

const filteredProjectMembers = computed(() => {
  if (!selectedTaskForAssignment.value) return projectMembers.value
  
  if (assignmentDepartmentFilter.value === 'all') {
    return projectMembers.value
  }
  
  return projectMembers.value.filter(
    member => member.department_role === assignmentDepartmentFilter.value
  )
})

const filteredAndSortedTasks = computed(() => {
  let filtered = tasksStore.tasks

  // Search filter
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(task =>
      task.name.toLowerCase().includes(query) ||
      task.project_name?.toLowerCase().includes(query) ||
      task.shot_name?.toLowerCase().includes(query) ||
      task.asset_name?.toLowerCase().includes(query)
    )
  }

  // Status filter
  if (statusFilter.value !== 'all') {
    filtered = filtered.filter(task => task.status === statusFilter.value)
  }

  // Task type filter
  if (taskTypeFilter.value !== 'all') {
    filtered = filtered.filter(task => task.task_type === taskTypeFilter.value)
  }

  // Department filter (for coordinators/admins)
  if (departmentFilter.value !== 'all' && canAssignTasks.value) {
    // This would require backend support to filter by department role
    // For now, we'll skip this filter as it requires additional API support
  }

  // Sort
  const sorted = [...filtered].sort((a, b) => {
    switch (sortBy.value) {
      case 'deadline':
        if (!a.deadline) return 1
        if (!b.deadline) return -1
        return new Date(a.deadline).getTime() - new Date(b.deadline).getTime()
      case 'status':
        return a.status.localeCompare(b.status)
      case 'name':
        return a.name.localeCompare(b.name)
      case 'updated':
        return new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime()
      default:
        return 0
    }
  })

  return sorted
})

function selectTask(task: any) {
  emit('taskSelected', task)
}

function formatTaskType(type: string): string {
  return type.charAt(0).toUpperCase() + type.slice(1).replace('_', ' ')
}

function formatDepartmentRole(role: string): string {
  return role.charAt(0).toUpperCase() + role.slice(1)
}

function formatDate(dateString: string): string {
  const date = new Date(dateString)
  const now = new Date()
  const daysUntil = Math.ceil((date.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
  
  const dateStr = date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
  
  if (daysUntil < 0) {
    return `${dateStr} (${Math.abs(daysUntil)}d overdue)`
  } else if (daysUntil === 0) {
    return `${dateStr} (Today)`
  } else if (daysUntil === 1) {
    return `${dateStr} (Tomorrow)`
  } else if (daysUntil <= 7) {
    return `${dateStr} (${daysUntil}d)`
  }
  
  return dateStr
}

function isOverdue(deadline: string, status: string): boolean {
  if (status === 'approved') return false
  const now = new Date()
  const deadlineDate = new Date(deadline)
  return deadlineDate < now
}

function isUrgent(deadline: string, status: string): boolean {
  if (status === 'approved') return false
  const now = new Date()
  const deadlineDate = new Date(deadline)
  const daysUntil = Math.ceil((deadlineDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
  return daysUntil >= 0 && daysUntil <= 3
}

function getDeadlineContainerClass(deadline: string, status: string): string {
  if (status === 'approved') return 'bg-muted/50'
  
  const now = new Date()
  const deadlineDate = new Date(deadline)
  const daysUntil = Math.ceil((deadlineDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
  
  if (daysUntil < 0) return 'bg-destructive/10'
  if (daysUntil <= 3) return 'bg-orange-500/10'
  if (daysUntil <= 7) return 'bg-yellow-500/10'
  return ''
}

function getDeadlineTextClass(deadline: string, status: string): string {
  if (status === 'approved') return 'text-muted-foreground'
  
  const now = new Date()
  const deadlineDate = new Date(deadline)
  const daysUntil = Math.ceil((deadlineDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
  
  if (daysUntil < 0) return 'text-destructive font-semibold'
  if (daysUntil <= 3) return 'text-orange-600 font-semibold'
  if (daysUntil <= 7) return 'text-yellow-600 font-medium'
  return 'text-foreground'
}

async function handleStatusUpdate(taskId: number, newStatus: string) {
  try {
    await tasksStore.updateTaskStatus(taskId, newStatus)
    toast({
      title: 'Status Updated',
      description: 'Task status has been updated successfully.',
    })
  } catch (error: any) {
    toast({
      title: 'Error',
      description: error.response?.data?.detail || 'Failed to update task status',
      variant: 'destructive',
    })
  }
}

async function openAssignDialog(task: TaskListItem) {
  selectedTaskForAssignment.value = task
  selectedUserId.value = task.assigned_user_id?.toString() || ''
  assignmentDepartmentFilter.value = 'all'
  
  // Fetch project members
  if (task.project_id) {
    try {
      projectMembers.value = await projectService.getProjectMembers(task.project_id)
    } catch (error) {
      console.error('Failed to fetch project members:', error)
      toast({
        title: 'Error',
        description: 'Failed to load project members',
        variant: 'destructive',
      })
    }
  }
  
  assignDialogOpen.value = true
}

async function handleAssignTask() {
  if (!selectedTaskForAssignment.value || !selectedUserId.value) return
  
  assigningTask.value = true
  try {
    await taskService.assignTask(
      selectedTaskForAssignment.value.id,
      parseInt(selectedUserId.value)
    )
    
    toast({
      title: 'Task Assigned',
      description: 'Task has been assigned successfully.',
    })
    
    // Refresh tasks
    await tasksStore.fetchTasks({ projectId: props.projectId })
    
    assignDialogOpen.value = false
  } catch (error: any) {
    toast({
      title: 'Error',
      description: error.response?.data?.detail || 'Failed to assign task',
      variant: 'destructive',
    })
  } finally {
    assigningTask.value = false
  }
}

function clearFilters() {
  searchQuery.value = ''
  statusFilter.value = 'all'
  taskTypeFilter.value = 'all'
  departmentFilter.value = 'all'
  sortBy.value = 'deadline'
}

import { useAvatarUrl } from '@/composables/useAvatarUrl'

const { getAvatarUrl, getInitialsAvatarUrl } = useAvatarUrl()

function getAssignedUserInitials(name: string) {
  const parts = name.split(' ')
  if (parts.length >= 2) {
    return `${parts[0].charAt(0)}${parts[1].charAt(0)}`.toUpperCase()
  }
  return name.charAt(0).toUpperCase()
}

onMounted(async () => {
  await tasksStore.fetchTasks({
    projectId: props.projectId
  })
})
</script>
