<template>
  <div class="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4">
    <Label class="text-sm font-medium">Episode:</Label>
    <div class="flex items-center gap-2">
      <Select 
        :model-value="selectedEpisodeId?.toString() || 'all'" 
        @update:model-value="handleEpisodeChange"
        :disabled="isLoading"
      >
        <SelectTrigger class="w-full sm:w-64">
          <SelectValue placeholder="Select episode..." />
        </SelectTrigger>
      <SelectContent>
        <!-- All Episodes Option -->
        <SelectItem value="all">
          All Episodes
        </SelectItem>
        
        <SelectSeparator v-if="episodes.length > 0" />
        
        <!-- Loading State -->
        <SelectItem v-if="isLoading" value="loading" disabled>
          <div class="flex items-center gap-2">
            <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-current"></div>
            <span>Loading episodes...</span>
          </div>
        </SelectItem>
        
        <!-- Error State -->
        <SelectItem v-else-if="error" value="error" disabled>
          <div class="flex items-center gap-2">
            <AlertCircle class="h-4 w-4 text-destructive" />
            <span class="text-destructive">{{ error }}</span>
          </div>
        </SelectItem>
        
        <!-- Episodes List -->
        <SelectItem 
          v-else
          v-for="episode in sortedEpisodes" 
          :key="episode.id" 
          :value="episode.id.toString()"
        >
          {{ episode.name }}
        </SelectItem>
        
        <SelectSeparator v-if="canCreateEpisodes && episodes.length > 0" />
        
        <!-- Create Episode Option -->
        <SelectItem 
          v-if="canCreateEpisodes"
          value="create" 
          @click="handleCreateEpisode"
        >
          <div class="flex items-center gap-2">
            <Plus class="h-4 w-4" />
            <span>Create Episode</span>
          </div>
        </SelectItem>
      </SelectContent>
      </Select>
      
      <!-- Refresh Button -->
      <Button 
        variant="outline" 
        size="sm" 
        @click="refreshEpisodes"
        :disabled="isLoading"
      >
        <RefreshCw :class="['h-4 w-4', isLoading && 'animate-spin']" />
      </Button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Plus, AlertCircle, RefreshCw } from 'lucide-vue-next'
import { 
  Select, SelectContent, SelectItem, SelectSeparator, 
  SelectTrigger, SelectValue 
} from '@/components/ui/select'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { useAuthStore } from '@/stores/auth'
import { episodeService, type Episode } from '@/services/episode'

interface Props {
  projectId: number
  selectedEpisodeId?: number | null
}

interface Emits {
  (e: 'episode-selected', episodeId: number | null): void
  (e: 'create-episode'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const router = useRouter()
const authStore = useAuthStore()

// Reactive state
const episodes = ref<Episode[]>([])
const isLoading = ref(false)
const error = ref<string | null>(null)

// Computed properties
const canCreateEpisodes = computed(() => {
  const userRole = authStore.userRole
  const isAdmin = authStore.user?.is_admin
  return userRole === 'coordinator' || isAdmin
})

const sortedEpisodes = computed(() => {
  return [...episodes.value].sort((a, b) => {
    // Sort by episode number if available, otherwise by name
    if (a.episode_number && b.episode_number) {
      return a.episode_number - b.episode_number
    }
    return a.name.localeCompare(b.name)
  })
})

// Methods
const loadEpisodes = async () => {
  try {
    isLoading.value = true
    error.value = null
    episodes.value = await episodeService.getProjectEpisodes(props.projectId)
  } catch (err) {
    error.value = err instanceof Error ? err.message : 'Failed to load episodes'
  } finally {
    isLoading.value = false
  }
}

const refreshEpisodes = async () => {
  await loadEpisodes()
}

const handleEpisodeChange = (value: string) => {
  if (value === 'create') {
    handleCreateEpisode()
    return
  }
  
  if (value === 'all') {
    emit('episode-selected', null)
  } else {
    const episodeId = parseInt(value)
    if (!isNaN(episodeId)) {
      emit('episode-selected', episodeId)
    }
  }
}

const handleCreateEpisode = () => {
  emit('create-episode')
}

// Watchers
watch(() => props.projectId, (newProjectId) => {
  if (newProjectId) {
    loadEpisodes()
  }
}, { immediate: true })

// Lifecycle
onMounted(() => {
  if (props.projectId) {
    loadEpisodes()
  }
})
</script>