// filepath: src/views/Home.vue
<script setup lang="ts">
import { watch } from 'vue'
import { invoke } from '@tauri-apps/api/core'
import { Loader2 } from 'lucide-vue-next'
import { useQueueStore } from '../stores/queue'
import { useSettingsStore } from '../stores/settings'
import { useAnalysisStore } from '../stores/analysis'
import AppSelect from '../components/ui/AppSelect.vue'

const queueStore = useQueueStore()
const settingsStore = useSettingsStore()
const analysisStore = useAnalysisStore()

const qualityOptions = [
  { label: 'Best Quality', value: 'best' },
  { label: '1080p', value: '1080' },
  { label: '720p', value: '720' },
  { label: '480p', value: '480' },
]

// Sync default download path if not set
watch(() => settingsStore.settings.download_path, (newPath) => {
    if (newPath && !analysisStore.options.output_path) {
      analysisStore.options.output_path = newPath
    }
}, { immediate: true })

// Detect Mix URL
watch(() => analysisStore.url, (newUrl) => {
    if (newUrl && newUrl.includes('v=') && newUrl.includes('list=')) {
        analysisStore.isMix = true
    } else {
        analysisStore.isMix = false
        // Reset scanMix if URL changes to non-mix
        analysisStore.scanMix = false 
    }
})

async function analyze() {
  if (!analysisStore.url) return
  analysisStore.loading = true
  analysisStore.error = ''
  analysisStore.metadata = null
  
  try {
    let urlToScan = analysisStore.url;
    let parseMix = false;

    if (analysisStore.isMix) {
        if (analysisStore.scanMix) {
             // Keep URL as is, tell backend to limit scan
             parseMix = true;
        } else {
             // Strip list param
             try {
                 const u = new URL(urlToScan);
                 u.searchParams.delete('list');
                 u.searchParams.delete('index');
                 u.searchParams.delete('start_radio');
                 urlToScan = u.toString();
             } catch (e) {
                 // Fallback regex if URL parsing fails
                 urlToScan = urlToScan.replace(/&list=[^&]+/, '');
             }
        }
    }

    const res = await invoke('fetch_metadata', { url: urlToScan, parseMixPlaylist: parseMix })
    analysisStore.metadata = res
  } catch (e: any) {
    analysisStore.error = e.toString()
  } finally {
    analysisStore.loading = false
  }
}

async function startDownload() {
  if (!analysisStore.metadata) return
  
  // Ensure path is set
  if (!analysisStore.options.output_path) {
      analysisStore.options.output_path = settingsStore.settings.download_path
  }

  try {
      const metaToSend = analysisStore.metadata.entries ? 
         { title: analysisStore.metadata.title, thumbnail: "", id: analysisStore.metadata.id } : 
         analysisStore.metadata; 

    // Note: We might want to pass the *cleaned* URL if it was cleaned during analyze
    // But for now we pass the original URL or whatever was scanned.
    // Actually, if we scanned as a single video (unchecked), we should probably download as single video.
    // The user might expect the same result as analysis.
    // Let's reconstruct the URL logic or just use what `analyze` used?
    // Since `start_download` just takes a URL string, we should probably use the same logic.
    
    let urlToDownload = analysisStore.url;
     if (analysisStore.isMix && !analysisStore.scanMix) {
          try {
             const u = new URL(urlToDownload);
             u.searchParams.delete('list');
             u.searchParams.delete('index');
             u.searchParams.delete('start_radio');
             urlToDownload = u.toString();
         } catch (e) {
             urlToDownload = urlToDownload.replace(/&list=[^&]+/, '');
         }
     }

    const id = await invoke<string>('start_download', { 
        url: urlToDownload,
        options: analysisStore.options,
        metadata: metaToSend
    })

      queueStore.addTask({
          id,
          title: metaToSend.title,
          thumbnail: metaToSend.thumbnail,
          progress: 0,
          speed: 'Pending...',
          status: 'pending'
      })
      
      // Reset state after successful download start
      analysisStore.reset()
  } catch (e: any) {
      analysisStore.error = "Download failed to start: " + e.toString()
  }
}
</script>

<template>
  <div class="max-w-5xl mx-auto p-8">
    <header class="mb-8">
      <h1 class="text-3xl font-bold text-zinc-900 dark:text-white">New Download</h1>
      <p class="text-gray-500 dark:text-gray-400 mt-2">Paste a URL to start downloading media.</p>
    </header>

    <!-- Input Section -->
    <div class="bg-white dark:bg-zinc-900 p-6 rounded-2xl shadow-sm border border-gray-200 dark:border-zinc-800 mb-8">
      <div class="flex gap-4">
        <input 
          v-model="analysisStore.url" 
          type="text" 
          placeholder="https://youtube.com/watch?v=..." 
          class="flex-1 bg-gray-50 dark:bg-zinc-800 border-none rounded-xl px-4 py-3 text-zinc-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
          @keyup.enter="analyze"
        />
        <button 
          @click="analyze"
          :disabled="analysisStore.loading"
          class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-xl font-medium transition-colors disabled:opacity-50 flex items-center gap-2 shrink-0"
        >
          <Loader2 v-if="analysisStore.loading" class="animate-spin w-5 h-5" />
          <span v-else>Analyze</span>
        </button>
      </div>
      
      <!-- Mix Toggle -->
      <div v-if="analysisStore.isMix" class="mt-4 flex items-center gap-3">
          <button 
            @click="analysisStore.scanMix = !analysisStore.scanMix"
            class="w-12 h-6 rounded-full relative transition-colors duration-200 ease-in-out flex-shrink-0"
            :class="analysisStore.scanMix ? 'bg-blue-600' : 'bg-gray-300 dark:bg-zinc-600'"
          >
            <span 
              class="absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform duration-200"
              :class="analysisStore.scanMix ? 'translate-x-6' : 'translate-x-0'"
            />
          </button>
          <span class="text-sm font-medium text-zinc-700 dark:text-gray-300">Scan Playlist (Max 20)</span>
      </div>

      <p v-if="analysisStore.error" class="mt-3 text-red-500 text-sm">{{ analysisStore.error }}</p>
    </div>

    <!-- Analysis Result -->
    <div v-if="analysisStore.metadata" class="bg-white dark:bg-zinc-900 rounded-2xl shadow-sm border border-gray-200 dark:border-zinc-800 overflow-hidden mb-8">
      <div class="p-6 flex flex-col md:flex-row gap-6">
        <!-- Thumbnail -->
        <img :src="analysisStore.metadata.thumbnail || '/placeholder.png'" class="w-full md:w-64 aspect-video object-cover rounded-lg bg-gray-100 dark:bg-zinc-800" />
        
        <!-- Details -->
        <div class="flex-1">
          <h2 class="text-xl font-bold text-zinc-900 dark:text-white line-clamp-2">{{ analysisStore.metadata.title }}</h2>
          <p v-if="analysisStore.metadata.uploader" class="text-gray-500 dark:text-gray-400 mt-1">{{ analysisStore.metadata.uploader }}</p>
          <p v-if="analysisStore.metadata.entries" class="text-blue-500 mt-1 font-medium">{{ analysisStore.metadata.entries.length }} videos in playlist</p>
          
          <!-- Options -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-6">
             <!-- Audio Only Toggle -->
             <div class="flex items-center justify-between p-3 bg-gray-50 dark:bg-zinc-800 rounded-xl">
                <span class="font-medium text-sm">Audio Only</span>
                <button 
                  @click="analysisStore.options.is_audio_only = !analysisStore.options.is_audio_only"
                  class="w-12 h-6 rounded-full relative transition-colors duration-200 ease-in-out"
                  :class="analysisStore.options.is_audio_only ? 'bg-blue-600' : 'bg-gray-300 dark:bg-zinc-600'"
                >
                  <span 
                    class="absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform duration-200"
                    :class="analysisStore.options.is_audio_only ? 'translate-x-6' : 'translate-x-0'"
                  />
                </button>
             </div>

             <!-- Quality Dropdown -->
             <div class="relative">
                <AppSelect 
                  v-model="analysisStore.options.quality"
                  :options="qualityOptions"
                  :disabled="analysisStore.options.is_audio_only"
                />
             </div>
          </div>
        </div>
      </div>

      <div class="px-6 py-4 bg-gray-50 dark:bg-zinc-800/50 border-t border-gray-200 dark:border-zinc-800 flex justify-end">
         <button 
            @click="startDownload"
            class="bg-blue-600 hover:bg-blue-700 text-white px-8 py-3 rounded-xl font-bold transition-colors shadow-lg shadow-blue-600/20"
         >
            Download Now
         </button>
      </div>
    </div>

    <!-- Active Downloads -->
    <div v-if="queueStore.tasks.length > 0">
       <h3 class="text-lg font-bold mb-4">Active Downloads</h3>
       <div class="space-y-3">
          <!-- Reversed to show newest first -->
          <div v-for="task in queueStore.tasks.slice().reverse()" :key="task.id" class="bg-white dark:bg-zinc-900 p-4 rounded-xl border border-gray-200 dark:border-zinc-800 flex items-center gap-4">
             <img :src="task.thumbnail || '/placeholder.png'" class="w-16 h-16 object-cover rounded-lg bg-gray-100 dark:bg-zinc-800" />
             <div class="flex-1 min-w-0">
                <div class="flex justify-between mb-1">
                   <h4 class="font-medium truncate pr-4">{{ task.title }}</h4>
                   <span class="text-xs font-mono text-gray-500 whitespace-nowrap">
                      {{ task.status === 'finished' ? 'Completed' : (task.status === 'error' ? 'Failed' : task.speed) }}
                   </span>
                </div>
                <div class="h-2 bg-gray-100 dark:bg-zinc-800 rounded-full overflow-hidden">
                   <div 
                      class="h-full transition-all duration-300"
                      :style="{ width: `${task.progress}%` }"
                      :class="task.status === 'error' ? 'bg-red-500' : (task.status === 'finished' ? 'bg-green-500' : 'bg-blue-600')"
                   />
                </div>
             </div>
          </div>
       </div>
    </div>

  </div>
</template>
