<template>
  <div class="flex flex-col gap-4">
    <!-- Main Toolbar Row -->
    <div class="flex items-center justify-between gap-4">
      <!-- Left Side - Filters -->
      <div class="flex flex-wrap gap-2">
        <!-- View Toggle -->
        <SegmentedToggle
          :options="viewModeOptions"
          :model-value="viewMode"
          @update:model-value="$emit('update:view-mode', $event as 'grid' | 'list')"
        />

        <!-- Category Filter -->
        <Popover>
          <PopoverTrigger as-child>
            <Button variant="outline" size="sm" class="h-8 border-dashed">
              <Package class="mr-2 h-4 w-4" />
              Category
              <Badge
                v-if="categoryFilter !== 'all'"
                variant="secondary"
                class="ml-2 rounded-sm px-1 font-normal"
              >
                1
              </Badge>
            </Button>
          </PopoverTrigger>
          <PopoverContent class="w-[200px] p-0" align="start">
            <Command>
              <CommandInput placeholder="Search category..." />
              <CommandList>
                <CommandEmpty>No category found.</CommandEmpty>
                <CommandGroup>
                  <CheckableCommandItem
                    value="all"
                    :model-value="categoryFilter === 'all'"
                    @update:model-value="$emit('update:category-filter', 'all')"
                  >
                    <span>All Categories</span>
                  </CheckableCommandItem>
                  <CheckableCommandItem
                    v-for="category in categories"
                    :key="category.value"
                    :value="category.value"
                    :model-value="categoryFilter === category.value"
                    @update:model-value="$emit('update:category-filter', category.value)"
                  >
                    <component :is="category.icon" class="h-4 w-4 mr-2" />
                    <span>{{ category.label }}</span>
                  </CheckableCommandItem>
                </CommandGroup>
              </CommandList>
            </Command>
          </PopoverContent>
        </Popover>

        <!-- Task Status Filter (only for list view) -->
        <TaskStatusFilter
          v-if="viewMode === 'list'"
          :all-task-types="allTaskTypes"
          :project-id="projectId"
          @filter-changed="$emit('task-status-filter-changed', $event)"
        />

        <!-- Column Visibility Control (only for list view) -->
        <ColumnToggleList
          v-if="viewMode === 'list'"
          :columns="columnToggleOptions"
          :model-value="columnVisibility"
          @update:model-value="$emit('update:column-visibility', $event)"
        />

        <!-- Task Columns Toggle Button (only for list view) -->
        <Button
          v-if="viewMode === 'list'"
          variant="outline"
          size="sm"
          @click="toggleAllTaskColumns"
          class="h-8"
        >
          <ListTodo v-if="!allTaskColumnsVisible" class="h-4 w-4 mr-2" />
          <ListX v-else class="h-4 w-4 mr-2" />
          {{ allTaskColumnsVisible ? 'Hide' : 'Show' }} Tasks
        </Button>

        <!-- Detail Panel Enable/Disable Toggle Button (only for list view) -->
        <DetailPanelToggleButton
          v-if="viewMode === 'list'"
          :enabled="isDetailPanelEnabled"
          @toggle="$emit('toggle-detail-panel')"
        />

        <!-- Lock First Columns Toggle Button (only for list view) -->
        <Button
          v-if="viewMode === 'list'"
          @click="$emit('toggle-column-lock')"
          :variant="isColumnsLocked ? 'default' : 'outline'"
          size="icon-sm"
          :class="isColumnsLocked ? 'bg-primary text-primary-foreground hover:bg-primary/90' : ''"
          :title="isColumnsLocked ? 'Unlock columns' : 'Lock first columns'"
        >
          <Lock v-if="isColumnsLocked" class="h-4 w-4" />
          <Unlock v-else class="h-4 w-4" />
        </Button>

        <!-- Clear Filters -->
        <ClearFiltersButton v-if="hasFilters" @clear="clearFilters" />
      </div>

      <!-- Right Side - Search and Actions -->
      <div class="flex items-center gap-2 flex-shrink-0">
        <!-- Search -->
        <div class="relative w-64">
          <Search class="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            :model-value="search"
            @update:model-value="debouncedSearch"
            placeholder="Search assets..."
            class="pl-9 h-8"
          />
        </div>

        <!-- Thumbnail Toggle -->
        <Button
          variant="outline"
          size="icon-sm"
          @click="$emit('update:show-thumbnails', !showThumbnails)"
          :title="showThumbnails ? 'Hide Thumbnails' : 'Show Thumbnails'"
        >
          <ImageIcon v-if="!showThumbnails" class="h-4 w-4" />
          <ImageOff v-else class="h-4 w-4" />
        </Button>

        <!-- Create Asset Button -->
        <Button @click="$emit('create-asset')" size="icon-sm" title="Create Asset">
          <Plus class="h-4 w-4" />
        </Button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import {
  LayoutGrid, List, Search, Package, Plus, ImageIcon, ImageOff,
  ListTodo, ListX,
  Lock, Unlock
} from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover'
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandList,
  CheckableCommandItem,
} from '@/components/ui/command'
import TaskStatusFilter from '@/components/shared/TaskStatusFilter.vue'
import ColumnToggleList from '@/components/shared/ColumnToggleList.vue'
import SegmentedToggle from '@/components/shared/SegmentedToggle.vue'
import DetailPanelToggleButton from '@/components/shared/DetailPanelToggleButton.vue'
import ClearFiltersButton from '@/components/shared/ClearFiltersButton.vue'
import { useDebouncedSearch } from '@/composables/useDebouncedSearch'
import type { VisibilityState } from '@tanstack/vue-table'
import type { Asset, AssetCategory } from '@/services/asset'

interface CategoryOption {
  value: AssetCategory
  label: string
  icon: any
}

interface Props {
  viewMode: 'grid' | 'list'
  categoryFilter: AssetCategory | 'all'
  search: string
  columnVisibility: VisibilityState
  categories: CategoryOption[]
  allTaskTypes: string[]
  projectId: number
  selectedAsset: Asset | null
  isDetailPanelEnabled: boolean
  showThumbnails: boolean
  isColumnsLocked: boolean
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:view-mode': [value: 'grid' | 'list']
  'update:category-filter': [value: AssetCategory | 'all']
  'update:search': [value: string]
  'update:column-visibility': [value: VisibilityState]
  'update:show-thumbnails': [value: boolean]
  'task-status-filter-changed': [value: string]
  'toggle-detail-panel': []
  'toggle-column-lock': []
  'create-asset': []
}>()

// Column definitions - computed to be reactive to allTaskTypes changes
const allColumns = computed(() => [
  { id: 'thumbnail', label: 'Thumbnail', type: 'default' },
  { id: 'name', label: 'Asset Name', type: 'default' },
  { id: 'category', label: 'Category', type: 'default' },
  { id: 'status', label: 'Status', type: 'default' },
  { id: 'description', label: 'Description', type: 'default' },
  { id: 'updatedAt', label: 'Updated', type: 'default' },
  ...props.allTaskTypes.map(taskType => ({
    id: taskType,
    label: taskType.charAt(0).toUpperCase() + taskType.slice(1),
    type: 'task'
  })),
])

// Computed
const hasFilters = computed(() => {
  return (
    props.categoryFilter !== 'all' ||
    props.search !== ''
  )
})

// Column list shaped for ColumnToggleList (groups task-type columns under a labeled section)
const columnToggleOptions = computed(() =>
  allColumns.value.map(col => ({
    id: col.id,
    label: col.label,
    group: col.type === 'task' ? 'Task Types' : undefined,
  }))
)

const viewModeOptions = [
  { value: 'grid', icon: LayoutGrid },
  { value: 'list', icon: List },
]

// Check if all task columns are visible
const allTaskColumnsVisible = computed(() => {
  const taskColumns = allColumns.value.filter(col => col.type === 'task')
  return taskColumns.length > 0 && taskColumns.every(col => props.columnVisibility[col.id] !== false)
})

// Debounced search
const { debouncedSearch } = useDebouncedSearch((value) => emit('update:search', value))

// Methods
const toggleAllTaskColumns = () => {
  const newVisibility = { ...props.columnVisibility }
  const taskColumns = allColumns.value.filter(col => col.type === 'task')
  
  // If all task columns are visible, hide them; otherwise show them
  const shouldHide = allTaskColumnsVisible.value
  
  taskColumns.forEach(col => {
    newVisibility[col.id] = !shouldHide
  })
  
  emit('update:column-visibility', newVisibility)
}

const clearFilters = () => {
  emit('update:category-filter', 'all')
  emit('update:search', '')
}
</script>