<template>
  <div class="space-y-6">
    <!-- Header -->
    <div class="flex items-center justify-between">
      <div>
        <h3 class="text-lg font-semibold">Episode Management</h3>
        <p class="text-sm text-muted-foreground mt-1">
          Create and manage episodes for organizing shots in this project
        </p>
      </div>
      <Button @click="showCreateDialog = true" v-if="canManage">
        <Plus class="h-4 w-4 mr-2" />
        New Episode
      </Button>
    </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="loadEpisodes" variant="outline">
        <RefreshCw class="h-4 w-4 mr-2" />
        Try Again
      </Button>
    </div>

    <!-- Episodes Table -->
    <div v-else-if="episodes.length > 0" class="border rounded-lg">
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead class="w-20">#</TableHead>
            <TableHead>Name</TableHead>
            <TableHead>Status</TableHead>
            <TableHead class="w-24 text-center">Shots</TableHead>
            <TableHead>Description</TableHead>
            <TableHead class="w-32 text-right">Actions</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          <TableRow v-for="episode in sortedEpisodes" :key="episode.id">
            <TableCell>
              <Badge variant="outline" class="text-xs">
                {{ episode.episode_number }}
              </Badge>
            </TableCell>
            <TableCell class="font-medium">{{ episode.name }}</TableCell>
            <TableCell>
              <Badge :variant="getStatusVariant(episode.status)">
                {{ formatStatus(episode.status) }}
              </Badge>
            </TableCell>
            <TableCell class="text-center">
              <span class="font-medium">{{ episode.shot_count || 0 }}</span>
            </TableCell>
            <TableCell class="text-muted-foreground text-sm">
              {{ episode.description || '-' }}
            </TableCell>
            <TableCell class="text-right">
              <div class="flex items-center justify-end gap-2">
                <Button
                  variant="ghost"
                  size="sm"
                  @click="editEpisode(episode)"
                  v-if="canManage"
                >
                  <Edit class="h-4 w-4" />
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  @click="confirmDelete(episode)"
                  v-if="canManage"
                  :disabled="(episode.shot_count || 0) > 0"
                >
                  <Trash2 class="h-4 w-4" :class="{ 'text-destructive': (episode.shot_count || 0) === 0 }" />
                </Button>
              </div>
            </TableCell>
          </TableRow>
        </TableBody>
      </Table>
    </div>

    <!-- Empty State -->
    <div v-else class="text-center py-12 border rounded-lg">
      <Film class="h-12 w-12 mx-auto text-muted-foreground mb-4" />
      <h3 class="text-lg font-semibold mb-2">No episodes yet</h3>
      <p class="text-muted-foreground mb-4">
        Create your first episode to start organizing shots
      </p>
      <Button @click="showCreateDialog = true" v-if="canManage">
        <Plus class="h-4 w-4 mr-2" />
        Create Episode
      </Button>
    </div>

    <!-- Create/Edit Dialog -->
    <Dialog :open="showCreateDialog || showEditDialog" @update:open="closeDialogs">
      <DialogContent class="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>
            {{ editingEpisode ? 'Edit Episode' : 'Create New Episode' }}
          </DialogTitle>
          <DialogDescription>
            {{ editingEpisode 
              ? 'Update episode information and status' 
              : 'Add a new episode to organize shots in this project' 
            }}
          </DialogDescription>
        </DialogHeader>

        <form @submit.prevent="handleSubmit" class="space-y-4">
          <div>
            <Label for="episode_number">Episode Number</Label>
            <Input
              id="episode_number"
              v-model.number="form.episode_number"
              type="number"
              min="1"
              placeholder="Enter episode number"
              required
            />
          </div>

          <div>
            <Label for="name">Episode Name</Label>
            <Input
              id="name"
              v-model="form.name"
              placeholder="Enter episode name"
              required
            />
          </div>

          <div>
            <Label for="description">Description</Label>
            <Textarea
              id="description"
              v-model="form.description"
              placeholder="Brief description of the episode"
              rows="3"
            />
          </div>

          <div>
            <Label for="status">Status</Label>
            <Select :model-value="form.status" @update:model-value="form.status = $event">
              <SelectTrigger>
                <SelectValue placeholder="Select status" />
              </SelectTrigger>
              <SelectContent>
                <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>

          <DialogFooter>
            <Button type="button" variant="outline" @click="closeDialogs">
              Cancel
            </Button>
            <Button type="submit" :disabled="isSubmitting">
              <div v-if="isSubmitting" class="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
              {{ editingEpisode ? 'Update Episode' : 'Create Episode' }}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>

    <!-- Delete Confirmation Dialog -->
    <AlertDialog :open="showDeleteDialog" @update:open="showDeleteDialog = $event">
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Delete Episode</AlertDialogTitle>
          <AlertDialogDescription>
            Are you sure you want to delete episode "{{ deletingEpisode?.name }}"?
            This action cannot be undone.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>Cancel</AlertDialogCancel>
          <AlertDialogAction @click="handleDelete" class="bg-destructive hover:bg-destructive/90">
            Delete
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { Plus, Edit, Trash2, AlertCircle, RefreshCw, Film } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { useEpisodesStore, type Episode, type EpisodeCreate, type EpisodeUpdate } from '@/stores/episodes'
import { useToast } from '@/components/ui/toast/use-toast'

interface Props {
  projectId: number
  canManage?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  canManage: false
})

const episodesStore = useEpisodesStore()
const { toast } = useToast()

// State
const isLoading = ref(false)
const isSubmitting = ref(false)
const error = ref<string | null>(null)
const episodes = ref<Episode[]>([])
const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const showDeleteDialog = ref(false)
const editingEpisode = ref<Episode | null>(null)
const deletingEpisode = ref<Episode | null>(null)

const form = ref({
  name: '',
  episode_number: 1,
  description: '',
  status: 'planning' as const
})

// Computed
const sortedEpisodes = computed(() => {
  return [...episodes.value].sort((a, b) => a.episode_number - b.episode_number)
})

// Methods
const loadEpisodes = async () => {
  try {
    isLoading.value = true
    error.value = null
    await episodesStore.fetchEpisodes(props.projectId)
    // fetchEpisodes with projectId already filters by project, so we can use episodes directly
    episodes.value = episodesStore.episodes
  } catch (err) {
    error.value = err instanceof Error ? err.message : 'Failed to load episodes'
    console.error('Failed to load episodes:', err)
  } finally {
    isLoading.value = false
  }
}

const editEpisode = (episode: Episode) => {
  editingEpisode.value = episode
  form.value = {
    name: episode.name,
    episode_number: episode.episode_number,
    description: episode.description || '',
    status: episode.status
  }
  showEditDialog.value = true
}

const confirmDelete = (episode: Episode) => {
  if ((episode.shot_count || 0) > 0) {
    toast({
      title: 'Cannot delete episode',
      description: 'This episode contains shots. Please delete all shots first.',
      variant: 'destructive'
    })
    return
  }
  deletingEpisode.value = episode
  showDeleteDialog.value = true
}

const handleSubmit = async () => {
  try {
    isSubmitting.value = true

    const data = {
      name: form.value.name,
      episode_number: form.value.episode_number,
      description: form.value.description || undefined,
      status: form.value.status
    }

    if (editingEpisode.value) {
      // Update existing episode
      await episodesStore.updateEpisode(editingEpisode.value.id, data)
      toast({
        title: 'Episode updated',
        description: `Episode "${data.name}" has been updated successfully.`
      })
    } else {
      // Create new episode
      await episodesStore.createEpisode(props.projectId, data)
      toast({
        title: 'Episode created',
        description: `Episode "${data.name}" has been created successfully.`
      })
    }

    // Reload episodes
    await loadEpisodes()
    closeDialogs()
  } catch (err) {
    console.error('Failed to save episode:', err)
    toast({
      title: 'Error',
      description: err instanceof Error ? err.message : 'Failed to save episode',
      variant: 'destructive'
    })
  } finally {
    isSubmitting.value = false
  }
}

const handleDelete = async () => {
  if (!deletingEpisode.value) return

  try {
    await episodesStore.deleteEpisode(deletingEpisode.value.id)
    toast({
      title: 'Episode deleted',
      description: `Episode "${deletingEpisode.value.name}" has been deleted successfully.`
    })
    await loadEpisodes()
    showDeleteDialog.value = false
    deletingEpisode.value = null
  } catch (err) {
    console.error('Failed to delete episode:', err)
    toast({
      title: 'Error',
      description: err instanceof Error ? err.message : 'Failed to delete episode',
      variant: 'destructive'
    })
  }
}

const closeDialogs = () => {
  showCreateDialog.value = false
  showEditDialog.value = false
  editingEpisode.value = null
  form.value = {
    name: '',
    episode_number: 1,
    description: '',
    status: 'planning'
  }
}

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(' ')
}

// Lifecycle
onMounted(() => {
  loadEpisodes()
})

// Watch for project changes
watch(() => props.projectId, () => {
  loadEpisodes()
})
</script>
