<template>
  <SidebarGroup v-if="!isCollapsed">
    <SidebarGroupLabel>View</SidebarGroupLabel>
    <SidebarGroup class="py-0" as-child>
      <Collapsible v-model:open="isBaseColumnsOpen" class="group/collapsible">
        <CollapsibleTrigger as-child>
          <SidebarGroupLabel class="px-2 hover:bg-sidebar-accent text-sm hover:text-sidebar-accent-foreground cursor-pointer">
            <div class="flex items-center justify-between w-full">
              Columns
              <ChevronRight 
                class="h-4 w-4 transition-transform duration-200" 
                :class="isBaseColumnsOpen ? 'rotate-90' : ''"
              />
            </div>
          </SidebarGroupLabel>
        </CollapsibleTrigger>
        <CollapsibleContent>
          <SidebarGroupContent>
            <Command class="bg-transparent border-0 p-0">
              <CommandList>
                <CommandGroup>
                  <template v-for="column in baseColumns" :key="column.id">
                    <CommandItem
                      :value="column.id"
                      @select="toggleColumn(column.id, !isColumnVisible(column.id))"
                    >
                      <div
                        :class="[
                          'mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary',
                          isColumnVisible(column.id)
                            ? 'bg-primary text-primary-foreground'
                            : 'opacity-50 [&_svg]:invisible'
                        ]"
                      >
                        <Check class="h-4 w-4" />
                      </div>
                      <span class="text-sm text-sidebar-foreground">{{ column.label }}</span>
                    </CommandItem>
                  </template>
                </CommandGroup>
              </CommandList>
            </Command>
          </SidebarGroupContent>
        </CollapsibleContent>
      </Collapsible>
    </SidebarGroup>
    <SidebarGroup class="py-0">
      <Collapsible v-model:open="isTaskColumnsOpen" class="group/collapsible">
        <CollapsibleTrigger as-child>
          <SidebarGroupLabel class="px-2 hover:bg-sidebar-accent text-sm hover:text-sidebar-accent-foreground cursor-pointer">
            <div class="flex items-center justify-between w-full">
              Task Columns
              <ChevronRight 
                class="h-4 w-4 transition-transform duration-200" 
                :class="isTaskColumnsOpen ? 'rotate-90' : ''"
              />
            </div>
          </SidebarGroupLabel>
        </CollapsibleTrigger>
        <CollapsibleContent>
          <SidebarGroupContent>
            <Command class="bg-transparent border-0 p-0">
              <CommandList>
                <CommandGroup>
                  <template v-for="column in taskColumns" :key="column.id">
                    <CommandItem
                      :value="column.id"
                      @select="toggleColumn(column.id, !isColumnVisible(column.id))"
                    >
                      <div
                        :class="[
                          'mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary',
                          isColumnVisible(column.id)
                            ? 'bg-primary text-primary-foreground'
                            : 'opacity-50 [&_svg]:invisible'
                        ]"
                      >
                        <Check class="h-4 w-4" />
                      </div>
                      <span class="text-sm text-sidebar-foreground">{{ column.label }}</span>
                    </CommandItem>
                  </template>
                </CommandGroup>
              </CommandList>
            </Command>
          </SidebarGroupContent>
        </CollapsibleContent>
      </Collapsible>
    </SidebarGroup>
  </SidebarGroup>

  <SidebarGroup v-else>
    <SidebarMenu>
      <SidebarMenuItem>
        <DropdownMenu>
          <DropdownMenuTrigger as-child>
            <SidebarMenuButton tooltip="Columns">
              <Columns class="size-4" />
            </SidebarMenuButton>
          </DropdownMenuTrigger>
          <DropdownMenuContent side="right" align="start" class="w-56">
            <DropdownMenuCheckboxItem
              v-for="column in baseColumns"
              :key="column.id"
              :model-value="isColumnVisible(column.id)"
              @update:model-value="(val: boolean) => toggleColumn(column.id, val)"
            >
              {{ column.label }}
            </DropdownMenuCheckboxItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </SidebarMenuItem>
      <SidebarMenuItem>
        <DropdownMenu>
          <DropdownMenuTrigger as-child>
            <SidebarMenuButton tooltip="Task Columns">
              <ListChecks class="size-4" />
            </SidebarMenuButton>
          </DropdownMenuTrigger>
          <DropdownMenuContent side="right" align="start" class="w-56">
            <DropdownMenuCheckboxItem
              v-for="column in taskColumns"
              :key="column.id"
              :model-value="isColumnVisible(column.id)"
              @update:model-value="(val: boolean) => toggleColumn(column.id, val)"
            >
              {{ column.label }}
            </DropdownMenuCheckboxItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </SidebarMenuItem>
    </SidebarMenu>
  </SidebarGroup>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { Check, ChevronDown, ChevronRight, Columns, ListChecks } from 'lucide-vue-next'
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandItem,
  CommandList,
  CommandSeparator,
} from '@/components/ui/command'
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from '@/components/ui/collapsible'
import {
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarMenu,
  SidebarMenuItem,
  SidebarMenuButton,
  useSidebar,
} from '@/components/ui/sidebar'
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuCheckboxItem,
} from '@/components/ui/dropdown-menu'
import { useColumnVisibilityStore } from '@/stores/columnVisibility'
import { customTaskTypeService } from '@/services/customTaskType'

const route = useRoute()
const columnVisibilityStore = useColumnVisibilityStore()
const { state } = useSidebar()
const isCollapsed = computed(() => state.value === 'collapsed')

// Collapsible state
const isBaseColumnsOpen = ref(true)
const isTaskColumnsOpen = ref(true)

// Task types state
const taskTypes = ref<string[]>([])

// Base columns - synced with Shot Data Table default columns
const baseColumns = [
  { id: 'thumbnail', label: 'Thumbnail' },
  { id: 'name', label: 'Shot Name' },
  { id: 'episode', label: 'Episode' },
  { id: 'frames', label: 'Frames' },
  { id: 'status', label: 'Status' },
]
const taskColumns = computed(() => {
  const columns = taskTypes.value.map(taskType => ({
    id: taskType,
    label: taskType.charAt(0).toUpperCase() + taskType.slice(1),
  }))
  return [...columns]
})
// All columns including task types
const allColumns = computed(() => {
  const taskColumns = taskTypes.value.map(taskType => ({
    id: taskType,
    label: taskType.charAt(0).toUpperCase() + taskType.slice(1),
  }))
  return [...baseColumns, ...taskColumns]
})

// Local reactive state
const localVisibility = ref<Record<string, boolean>>({})

// Watch for store changes and update local state
watch(
  () => columnVisibilityStore.columnVisibility,
  (newVal) => {
    localVisibility.value = { ...newVal }
  },
  { immediate: true, deep: true }
)

const isColumnVisible = (columnId: string): boolean => {
  // If not in visibility state, column is visible by default
  return localVisibility.value[columnId] !== false
}

const toggleColumn = (columnId: string, value: boolean) => {
  columnVisibilityStore.updateColumn(columnId, value)
}

// Fetch task types based on project ID from route
const fetchTaskTypes = async () => {
  // Extract projectId from route params
  const projectId = route.params.projectId as string | undefined
  
  // Clear task types if no projectId
  if (!projectId) {
    taskTypes.value = []
    return
  }
  
  try {
    const projectIdNum = parseInt(projectId, 10)
    if (!isNaN(projectIdNum)) {
      const data = await customTaskTypeService.getAllTaskTypes(projectIdNum)
      taskTypes.value = data.shot_task_types || []
    } else {
      taskTypes.value = []
    }
  } catch (err) {
    console.error('Failed to fetch task types:', err)
    taskTypes.value = []
  }
}

// Lifecycle - initialize store and fetch task types
onMounted(() => {
  columnVisibilityStore.initialize()
  fetchTaskTypes()
})

// Watch for route changes to refetch task types
watch(() => route.params.projectId, () => {
  fetchTaskTypes()
})
</script>
