<script setup lang="ts">
import { watch } from 'vue'
import { invoke } from '@tauri-apps/api/core'
import { Loader2, List, Link } 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: '最佳画质', value: 'best' },
  { label: '1080p', value: '1080' },
  { label: '720p', value: '720' },
  { label: '480p', value: '480' },
]

const videoFormatOptions = [
  { label: '原格式', value: 'original' },
  { label: 'MP4', value: 'mp4' },
  { label: 'WebM', value: 'webm' },
  { label: 'Matroska (MKV)', value: 'mkv' },
  { label: 'FLV', value: 'flv' },
  { label: 'AVI', value: 'avi' },
]

const audioFormatOptions = [
  { label: '原格式', value: 'original' },
  { label: 'MP3', value: 'mp3' },
  { label: 'M4A', value: 'm4a' },
  { label: 'AAC', value: 'aac' },
  { label: 'Opus', value: 'opus' },
  { label: 'Vorbis', value: 'vorbis' },
  { label: 'WAV', value: 'wav' },
  { label: 'FLAC', value: 'flac' },
]

// 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 
    }
})

// Reset format to original when toggling audio-only mode
watch(() => analysisStore.options.is_audio_only, () => {
    analysisStore.options.output_format = 'original'
})

async function processThumbnail(url: string | undefined): Promise<string | undefined> {
    if (!url) return undefined;
    // Check if it's an Instagram URL or similar that needs proxying
    if (url.includes('instagram.com') || url.includes('fbcdn.net') || url.includes('cdninstagram.com')) {
        try {
            return await invoke<string>('fetch_image', { url });
        } catch (e) {
            console.warn('Thumbnail fetch failed, falling back to URL', e);
            return url;
        }
    }
    return url;
}

async function processMetadataThumbnails(metadata: any) {
    if (!metadata) return;
    
    // Process single video thumbnail
    if (metadata.thumbnail) {
        metadata.thumbnail = await processThumbnail(metadata.thumbnail);
    }
    
    // Process playlist entries
    if (metadata.entries && Array.isArray(metadata.entries)) {
        await Promise.all(metadata.entries.map(async (entry: any) => {
            if (entry.thumbnail) {
                entry.thumbnail = await processThumbnail(entry.thumbnail);
            }
        }));
    }
}

async function analyze() {
  if (!analysisStore.url) return
  analysisStore.loading = true
  analysisStore.error = ''
  analysisStore.metadata = null
  
  try {
    if (analysisStore.isBatchMode) {
        // Batch Mode Logic
        const lines = analysisStore.url.split('\n').map(l => l.trim()).filter(l => l);
        const validLinks = lines.filter(l => {
            if (!(l.startsWith('http://') || l.startsWith('https://'))) return false;
            
            // Allow if it has NO list param
            if (!l.includes('list=')) return true;

            // Allow if it has list param BUT ALSO has v= (video in playlist/mix)
            if (l.includes('list=') && l.includes('v=')) return true;

            // Otherwise ignore (pure playlist)
            return false;
        });

        if (validLinks.length === 0) {
             throw new Error("未找到有效的单个视频链接（已忽略纯播放列表链接）。");
        }

        const results: any[] = [];
        
        // Process sequentially to be safe
        for (let link of validLinks) {
            try {
                // If it's a mix/playlist context (has v= and list=), strip the list param to treat as single video
                if (link.includes('list=') && link.includes('v=')) {
                     try {
                         const u = new URL(link);
                         u.searchParams.delete('list');
                         u.searchParams.delete('index');
                         u.searchParams.delete('start_radio');
                         link = u.toString();
                     } catch (e) {
                         link = link.replace(/&list=[^&]+/, '');
                     }
                }

                // Ensure we don't accidentally trigger mix parsing on single links if logic fails
                const res = await invoke<any>('fetch_metadata', { url: link, parseMixPlaylist: false });
                
                // Only add if it's a single video (no entries)
                if (!res.entries) {
                    results.push(res);
                }
            } catch (e) {
                console.warn(`Failed to parse ${link}`, e);
            }
        }

        if (results.length === 0) {
             throw new Error("所有链接解析失败或均为播放列表。");
        }

        // Process thumbnails for batch results
        await Promise.all(results.map(r => processMetadataThumbnails(r)));

        // Construct synthetic playlist
        analysisStore.metadata = {
            id: 'batch_download_' + Date.now(),
            title: `批量解析结果 (${results.length} 个视频)`,
            entries: results.map(e => ({ ...e, selected: true }))
        };

    } else {
        // Single Link Mode
        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<any>('fetch_metadata', { url: urlToScan, parseMixPlaylist: parseMix })
        
        await processMetadataThumbnails(res);
        
        // Initialize selected state for playlist entries
        if (res.entries) {
            res.entries = res.entries.map((e: any) => ({ ...e, selected: true }))
        }
        
        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
  }

  // Ensure cookies path is set from settings
  analysisStore.options.cookies_path = settingsStore.settings.cookies_path || ''

  try {
      if (analysisStore.metadata.entries) {
          // Playlist Download
          const selectedEntries = analysisStore.metadata.entries.filter((e: any) => e.selected)
          
          if (selectedEntries.length === 0) {
              analysisStore.error = "请至少选择一个要下载的视频。"
              return
          }

          for (const entry of selectedEntries) {
              const videoUrl = entry.url || `https://www.youtube.com/watch?v=${entry.id}`
              const id = await invoke<string>('start_download', { 
                  url: videoUrl,
                  options: analysisStore.options,
                  metadata: entry // Pass the individual video metadata
              })

              queueStore.addTask({
                  id,
                  title: entry.title,
                  thumbnail: entry.thumbnail,
                  progress: 0,
                  speed: '等待中...',
                  status: 'pending'
              })
          }
      } else {
        // Single Video Download
        let urlToDownload = analysisStore.url;
        // Clean URL if it was a mix but we didn't scan it as one
        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: analysisStore.metadata
        })

          queueStore.addTask({
              id,
              title: analysisStore.metadata.title,
              thumbnail: analysisStore.metadata.thumbnail,
              progress: 0,
              speed: '等待中...',
              status: 'pending'
          })
      }
      
      // Reset state after successful download start
      analysisStore.reset()
  } catch (e: any) {
      analysisStore.error = "下载启动失败： " + 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">新建下载</h1>
      <!-- <p class="text-gray-500 dark:text-gray-400 mt-2">粘贴 URL 开始下载媒体。</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">
      
      <!-- Input Area with Batch Toggle -->
      <div class="flex flex-col gap-3">
        <div class="flex justify-end mb-1">
             <button 
                @click="analysisStore.isBatchMode = !analysisStore.isBatchMode"
                class="text-xs font-medium flex items-center gap-1.5 px-3 py-1.5 rounded-lg transition-colors"
                :class="analysisStore.isBatchMode ? 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400' : 'bg-gray-100 text-gray-600 dark:bg-zinc-800 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-zinc-700'"
             >
                <List v-if="analysisStore.isBatchMode" class="w-3.5 h-3.5" />
                <Link v-else class="w-3.5 h-3.5" />
                {{ analysisStore.isBatchMode ? '单链接模式' : '批量输入模式' }}
             </button>
        </div>

        <div class="flex gap-4 items-start">
            <div class="flex-1 relative">
                <textarea 
                  v-if="analysisStore.isBatchMode"
                  v-model="analysisStore.url" 
                  placeholder="每行输入一个链接..." 
                  rows="5"
                  class="w-full 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 resize-none font-mono text-sm leading-relaxed"
                ></textarea>
                <input 
                  v-else
                  v-model="analysisStore.url"  
                  type="text" 
                  placeholder="https://..." 
                  class="w-full 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"
                />
            </div>
            
            <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 h-[48px]"
            >
              <Loader2 v-if="analysisStore.loading" class="animate-spin w-5 h-5" />
              <span v-else>解析</span>
            </button>
        </div>
      </div>
      
      <!-- Mix Toggle (Only in Single Mode) -->
      <div v-if="!analysisStore.isBatchMode && 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">解析播放列表 (前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">
      
      <!-- Playlist Header / Global Controls -->
      <div v-if="analysisStore.metadata.entries" class="p-6 border-b border-gray-200 dark:border-zinc-800">
          <div class="flex items-start justify-between mb-4">
              <div>
                  <h2 class="text-xl font-bold text-zinc-900 dark:text-white">{{ analysisStore.metadata.title }}</h2>
                  <p class="text-blue-500 mt-1 font-medium">{{ analysisStore.metadata.entries.length }} 个视频</p>
              </div>
          </div>
          
          <!-- Global Options Bar -->
          <div class="flex flex-col md:flex-row items-center justify-between gap-4 bg-gray-50 dark:bg-zinc-800/50 p-4 rounded-xl">
             
             <!-- Left: Selection Controls -->
             <div class="flex items-center gap-2 w-full md:w-auto">
                 <button @click="analysisStore.setAllEntries(true)" class="text-base font-medium px-3 py-1.5 rounded-lg bg-white dark:bg-zinc-700 hover:bg-gray-100 dark:hover:bg-zinc-600 text-zinc-700 dark:text-gray-200 border border-gray-200 dark:border-zinc-600 transition-colors shadow-sm">全选</button>
                 <button @click="analysisStore.setAllEntries(false)" class="text-base font-medium px-3 py-1.5 rounded-lg bg-white dark:bg-zinc-700 hover:bg-gray-100 dark:hover:bg-zinc-600 text-zinc-700 dark:text-gray-200 border border-gray-200 dark:border-zinc-600 transition-colors shadow-sm">取消全选</button>
                 <button @click="analysisStore.invertSelection()" class="text-base font-medium px-3 py-1.5 rounded-lg bg-white dark:bg-zinc-700 hover:bg-gray-100 dark:hover:bg-zinc-600 text-zinc-700 dark:text-gray-200 border border-gray-200 dark:border-zinc-600 transition-colors shadow-sm">反选</button>
             </div>

             <!-- Right: Settings -->
             <div class="flex items-center gap-6 w-full md:w-auto justify-end">
                <!-- Audio Only Toggle -->
                <div class="flex items-center gap-x-4 p-3 bg-gray-50 dark:bg-zinc-800 rounded-xl">
                    <span class="font-medium text-base text-zinc-700 dark:text-gray-300">仅音频</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="flex items-center gap-3">
                     <div class="w-44">
                        <AppSelect 
                          v-model="analysisStore.options.quality"
                          :options="qualityOptions"
                          :disabled="analysisStore.options.is_audio_only"
                        />
                     </div>
                </div>

                <!-- Format Dropdown -->
                <div class="flex items-center gap-3">
                     <div class="w-48">
                        <AppSelect 
                          v-model="analysisStore.options.output_format"
                          :options="analysisStore.options.is_audio_only ? audioFormatOptions : videoFormatOptions"
                        />
                     </div>
                </div>
             </div>
          </div>
      </div>

      <!-- Video List (Playlist Mode) -->
      <div v-if="analysisStore.metadata.entries" class="max-h-[500px] overflow-y-auto p-2 space-y-2 bg-gray-50/50 dark:bg-black/20">
          <div 
            v-for="entry in analysisStore.metadata.entries" 
            :key="entry.id" 
            class="flex items-center gap-4 p-3 rounded-xl hover:bg-white dark:hover:bg-zinc-800 transition-colors border border-transparent hover:border-gray-200 dark:hover:border-zinc-700 group"
            :class="entry.selected ? 'opacity-100' : 'opacity-60 grayscale'"
          >
              <!-- Checkbox -->
              <button 
                @click="entry.selected = !entry.selected"
                class="w-6 h-6 rounded-lg border-2 flex items-center justify-center transition-colors shrink-0"
                :class="entry.selected ? 'bg-blue-600 border-blue-600 text-white' : 'border-gray-300 dark:border-zinc-600 hover:border-blue-400'"
              >
                 <svg v-if="entry.selected" xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                 </svg>
              </button>

              <!-- Thumb -->
              <img :src="entry.thumbnail || '/placeholder.png'" class="w-24 h-14 object-cover rounded-lg bg-gray-200 dark:bg-zinc-700 shrink-0" />

              <!-- Info -->
              <div class="flex-1 min-w-0">
                  <h4 class="font-medium text-zinc-900 dark:text-white truncate text-sm" :title="entry.title">{{ entry.title }}</h4>
                  <p class="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
                      {{ entry.duration ? Math.floor(entry.duration / 60) + ':' + String(Math.floor(entry.duration % 60)).padStart(2, '0') : '' }}
                      <span v-if="entry.uploader" class="mx-1">•</span> {{ entry.uploader }}
                  </p>
              </div>
          </div>
      </div>

      <!-- Single Video Layout -->
      <div v-else 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 }} 个视频 (播放列表)</p>
          
          <!-- Options -->
          <div class="grid grid-cols-1 md:grid-cols-3 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-base">仅音频</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>

             <!-- Format Dropdown -->
             <div class="relative">
                <AppSelect 
                  v-model="analysisStore.options.output_format"
                  :options="analysisStore.options.is_audio_only ? audioFormatOptions : videoFormatOptions"
                />
             </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"
         >
            立即下载 {{ analysisStore.metadata.entries ? `(${analysisStore.metadata.entries.filter((e: any) => e.selected).length})` : '' }}
         </button>
      </div>
    </div>

    <!-- Active Downloads -->
    <div v-if="queueStore.tasks.length > 0">
       <h3 class="text-lg font-bold mb-4">进行中的任务</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' ? '已完成' : (task.status === 'error' ? '失败' : 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>