<template>
  <div class="space-y-4">
    <!-- Header with filters -->
    <div class="flex items-center justify-between">
      <div class="flex items-center gap-4">
        <div class="relative">
          <Search class="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            v-model="searchQuery"
            placeholder="Search episodes..."
            class="pl-10 w-64"
          />
        </div>
        <Select :model-value="statusFilter" @update:model-value="statusFilter = $event">
          <SelectTrigger class="w-40">
            <SelectValue placeholder="All Status" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Status</SelectItem>
            <SelectItem value="planning">Planning</SelectItem>
            <SelectItem value="in_progress">In Progress</SelectItem>
            <SelectItem value="on_hold">On Hold</SelectItem>
            <SelectItem value="completed">Completed</SelectItem>
            <SelectItem value="cancelled">Cancelled</SelectItem>
          </SelectContent>
        </Select>
      </div>
      
      <div class="flex items-center gap-2">
        <Button variant="outline" size="sm" @click="toggleView">
          <component :is="viewMode === 'grid' ? List : Grid3X3" class="h-4 w-4 mr-2" />
          {{ viewMode === 'grid' ? 'List View' : 'Grid View' }}
        </Button>
        <Button @click="$emit('create')" v-if="canCreate">
          <Plus class="h-4 w-4 mr-2" />
          New Episode
        </Button>
      </div>
    </div>

    <!-- Loading State -->
    <div v-if="isLoading" class="flex items-center justify-center py-12">
      <div class="flex items-center gap-2">
        <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
        <span class="text-muted-foreground">Loading episodes...</span>
      </div>
    </div>

    <!-- Error State -->
    <div v-else-if="error" class="text-center py-12">
      <AlertCircle class="h-12 w-12 mx-auto text-destructive mb-4" />
      <h3 class="text-lg font-semibold mb-2">Failed to load episodes</h3>
      <p class="text-muted-foreground mb-4">{{ error }}</p>
      <Button @click="$emit('retry')" variant="outline">
        <RefreshCw class="h-4 w-4 mr-2" />
        Try Again
      </Button>
    </div>

    <!-- Episodes Grid/List -->
    <div v-else-if="filteredEpisodes.length > 0">
      <!-- Grid View -->
      <div v-if="viewMode === 'grid'" class="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
        <EpisodeCard
          v-for="episode in filteredEpisodes"
          :key="episode.id"
          :episode="episode"
          :can-delete="canDelete"
          @select="$emit('select', episode)"
          @edit="$emit('edit', episode)"
          @view-shots="$emit('view-shots', episode)"
          @delete="$emit('delete', episode)"
        />
      </div>
      
      <!-- List View -->
      <div v-else class="space-y-2">
        <div class="grid grid-cols-12 gap-4 px-4 py-2 text-sm font-medium text-muted-foreground border-b">
          <div class="col-span-1">#</div>
          <div class="col-span-4">Name</div>
          <div class="col-span-2">Status</div>
          <div class="col-span-2">Shots</div>
          <div class="col-span-2">Progress</div>
          <div class="col-span-1">Actions</div>
        </div>
        
        <div
          v-for="episode in filteredEpisodes"
          :key="episode.id"
          class="grid grid-cols-12 gap-4 px-4 py-3 hover:bg-muted/50 rounded-lg cursor-pointer transition-colors"
          @click="$emit('select', episode)"
        >
          <div class="col-span-1 flex items-center">
            <Badge variant="outline" class="text-xs">
              {{ episode.episode_number }}
            </Badge>
          </div>
          <div class="col-span-4 flex items-center">
            <div>
              <div class="font-medium">{{ episode.name }}</div>
              <div class="text-sm text-muted-foreground" v-if="episode.description">
                {{ episode.description.substring(0, 60) }}{{ episode.description.length > 60 ? '...' : '' }}
              </div>
            </div>
          </div>
          <div class="col-span-2 flex items-center">
            <Badge :variant="getStatusVariant(episode.status)">
              {{ formatStatus(episode.status) }}
            </Badge>
          </div>
          <div class="col-span-2 flex items-center">
            <span class="font-medium">{{ episode.shot_count || 0 }}</span>
          </div>
          <div class="col-span-2 flex items-center">
            <div class="flex items-center gap-2 w-full">
              <div class="flex-1 bg-secondary rounded-full h-2">
                <div 
                  class="bg-primary h-2 rounded-full transition-all duration-300"
                  :style="{ width: `${getProgressPercentage(episode)}%` }"
                ></div>
              </div>
              <span class="text-xs font-medium">{{ getProgressPercentage(episode) }}%</span>
            </div>
          </div>
          <div class="col-span-1 flex items-center">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="sm" @click.stop>
                  <MoreHorizontal class="h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem @click.stop="$emit('edit', episode)">
                  <Edit class="h-4 w-4 mr-2" />
                  Edit Episode
                </DropdownMenuItem>
                <DropdownMenuItem @click.stop="$emit('view-shots', episode)">
                  <Camera class="h-4 w-4 mr-2" />
                  View Shots
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem 
                  @click.stop="$emit('delete', episode)"
                  class="text-destructive"
                  v-if="canDelete"
                >
                  <Trash2 class="h-4 w-4 mr-2" />
                  Delete Episode
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
      </div>
    </div>

    <!-- Empty State -->
    <div v-else class="text-center py-12">
      <Film class="h-12 w-12 mx-auto text-muted-foreground mb-4" />
      <h3 class="text-lg font-semibold mb-2">
        {{ searchQuery || statusFilter !== 'all' ? 'No episodes found' : 'No episodes yet' }}
      </h3>
      <p class="text-muted-foreground mb-4">
        {{ searchQuery || statusFilter !== 'all' 
          ? 'Try adjusting your search or filter criteria' 
          : 'Create your first episode to start organizing shots and tasks' 
        }}
      </p>
      <Button @click="$emit('create')" v-if="canCreate && !searchQuery && statusFilter === 'all'">
        <Plus class="h-4 w-4 mr-2" />
        Create Episode
      </Button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { 
  Search, Plus, List, Grid3X3, AlertCircle, RefreshCw, Film,
  MoreHorizontal, Edit, Camera, Trash2
} from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { 
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue 
} from '@/components/ui/select'
import {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem, 
  DropdownMenuSeparator, DropdownMenuTrigger
} from '@/components/ui/dropdown-menu'
import EpisodeCard from './EpisodeCard.vue'
import type { Episode } from '@/services/episode'

interface Props {
  episodes: Episode[]
  isLoading?: boolean
  error?: string | null
  canCreate?: boolean
  canDelete?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  isLoading: false,
  error: null,
  canCreate: false,
  canDelete: false
})

defineEmits<{
  create: []
  select: [episode: Episode]
  edit: [episode: Episode]
  'view-shots': [episode: Episode]
  delete: [episode: Episode]
  retry: []
}>()

const searchQuery = ref('')
const statusFilter = ref('all')
const viewMode = ref<'grid' | 'list'>('grid')

const filteredEpisodes = computed(() => {
  let filtered = props.episodes

  // Filter by search query
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(episode => 
      episode.name.toLowerCase().includes(query) ||
      episode.description?.toLowerCase().includes(query) ||
      episode.episode_number.toString().includes(query)
    )
  }

  // Filter by status
  if (statusFilter.value !== 'all') {
    filtered = filtered.filter(episode => episode.status === statusFilter.value)
  }

  // Sort by episode number
  return filtered.sort((a, b) => a.episode_number - b.episode_number)
})

const toggleView = () => {
  viewMode.value = viewMode.value === 'grid' ? 'list' : 'grid'
}

const getStatusVariant = (status: string) => {
  switch (status) {
    case 'planning': return 'secondary'
    case 'in_progress': return 'default'
    case 'on_hold': return 'outline'
    case 'completed': return 'success'
    case 'cancelled': return 'destructive'
    default: return 'secondary'
  }
}

const formatStatus = (status: string) => {
  return status.split('_').map(word => 
    word.charAt(0).toUpperCase() + word.slice(1)
  ).join(' ')
}

const getProgressPercentage = (episode: Episode) => {
  // Mock progress calculation based on status
  // In a real implementation, this would be calculated from shot completion
  switch (episode.status) {
    case 'planning': return 0
    case 'in_progress': return 45
    case 'on_hold': return 30
    case 'completed': return 100
    case 'cancelled': return 0
    default: return 0
  }
}
</script>

<script lang="ts">
export default {
  name: 'EpisodeList'
}
</script>