<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' | 'table')"
        />

        <!-- Episode Filter -->
        <Popover v-if="episodes.length > 0">
          <PopoverTrigger as-child>
            <Button variant="outline" size="sm" class="h-8 border-dashed">
              <Film class="mr-2 h-4 w-4" />
              Episode
              <Badge
                v-if="episodeFilter !== null"
                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 episode..." />
              <CommandList>
                <CommandEmpty>No episode found.</CommandEmpty>
                <CommandGroup>
                  <CheckableCommandItem
                    value="all"
                    :model-value="episodeFilter === null"
                    @update:model-value="$emit('update:episode-filter', null)"
                  >
                    <span>All Episodes</span>
                  </CheckableCommandItem>
                  <CheckableCommandItem
                    v-for="episode in episodes"
                    :key="episode.id"
                    :value="episode.id.toString()"
                    :model-value="episodeFilter === episode.id"
                    @update:model-value="$emit('update:episode-filter', episode.id)"
                  >
                    <span>{{ episode.name }}</span>
                  </CheckableCommandItem>
                </CommandGroup>
              </CommandList>
            </Command>
          </PopoverContent>
        </Popover>

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

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

        <!-- Task Columns Toggle Button (only for table view) -->
        <Button
          v-if="viewMode === 'table'"
          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 table view) -->
        <DetailPanelToggleButton
          v-if="viewMode === 'table'"
          :enabled="isDetailPanelEnabled"
          @toggle="$emit('toggle-detail-panel')"
        />

        <!-- Lock First Columns Toggle Button (only for table view) -->
        <Button
          v-if="viewMode === 'table'"
          @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 shots..."
            class="pl-9 h-8"
          />
        </div>

        <!-- Action Buttons -->
        <Button @click="$emit('bulk-create')" variant="outline" size="icon-sm">
          <Layers class="h-4 w-4" />
        </Button>
        <Button @click="$emit('create-shot')" size="icon-sm" title="Create Shot">
          <Plus class="h-4 w-4" />
        </Button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import {
  LayoutGrid, List, Table2, Search, Film, Plus, Layers,
  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 { Episode } from '@/services/episode'
import type { Shot } from '@/services/shot'

interface Props {
  viewMode: 'grid' | 'list' | 'table'
  episodeFilter: number | null
  search: string
  columnVisibility: VisibilityState
  episodes: Episode[]
  allTaskTypes: string[]
  projectId: number
  selectedShot: Shot | null
  isDetailPanelEnabled: boolean
  isColumnsLocked: boolean
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:view-mode': [value: 'grid' | 'list' | 'table']
  'update:episode-filter': [value: number | null]
  'update:search': [value: string]
  'update:column-visibility': [value: VisibilityState]
  'task-status-filter-changed': [value: string]
  'toggle-detail-panel': []
  'toggle-column-lock': []
  'toggle-task-columns': []
  'bulk-create': []
  'create-shot': []
}>()

// Column definitions - computed to be reactive to allTaskTypes changes
const allColumns = computed(() => [
  { id: 'thumbnail', label: 'Thumbnail', type: 'default' },
  { id: 'name', label: 'Shot Name', type: 'default' },
  { id: 'episode', label: 'Episode', type: 'default' },
  { id: 'frames', label: 'Frames', type: 'default' },
  { id: 'status', label: 'Status', type: 'default' },
  ...props.allTaskTypes.map(taskType => ({
    id: taskType,
    label: taskType.charAt(0).toUpperCase() + taskType.slice(1),
    type: 'task'
  })),
  
])

// Computed
const hasFilters = computed(() => {
  return (
    props.episodeFilter !== null ||
    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' ? 'All Task Types' : undefined,
  }))
)

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

// 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:episode-filter', null)
  emit('update:search', '')
}
</script>