/**
 * TypeScript Type Definitions
 * Central type definitions for the Media Downloader application
 */

import type { LucideIcon } from 'lucide-react'

// ============================================================================
// User & Authentication Types
// ============================================================================

export interface User {
  id: number
  username: string
  role: 'admin' | 'user' | 'viewer'
  email?: string
  created_at: string
  last_login?: string
  preferences: UserPreferences
}

export interface UserPreferences {
  theme: 'light' | 'dark'
  notifications_enabled?: boolean
  default_view?: string
}

export interface LoginRequest {
  username: string
  password: string
}

export interface LoginResponse {
  access_token: string
  token_type: string
  user: User
}

// ============================================================================
// Download Types
// ============================================================================

export interface Download {
  id: number
  platform: Platform
  source: string
  content_type: ContentType
  filename: string
  file_path: string
  file_size: number
  download_date: string
  status: DownloadStatus
  media_id?: string
  metadata?: DownloadMetadata
}

export type Platform =
  | 'instagram'
  | 'fastdl'
  | 'imginn'
  | 'toolzu'
  | 'snapchat'
  | 'tiktok'
  | 'forums'

export type ContentType =
  | 'posts'
  | 'stories'
  | 'reels'
  | 'tagged'
  | 'media'

export type DownloadStatus =
  | 'pending'
  | 'downloading'
  | 'completed'
  | 'failed'
  | 'duplicate'

export interface DownloadMetadata {
  resolution?: string
  duration?: number
  thumbnail_url?: string
  original_url?: string
  [key: string]: unknown
}

// ============================================================================
// Media Types
// ============================================================================

export interface MediaItem {
  id: string
  filename: string
  file_path: string
  file_size: number
  platform: Platform
  source: string
  content_type: ContentType
  media_type: 'image' | 'video'
  thumbnail_url?: string
  preview_url?: string
  download_date: string
  resolution?: string
  metadata?: MediaMetadata
}

export interface MediaMetadata {
  width?: number
  height?: number
  duration?: number
  format?: string
  codec?: string
  bitrate?: number
  [key: string]: unknown
}

export interface MediaGalleryResponse {
  media: MediaItem[]
  total: number
  offset: number
  limit: number
}

// ============================================================================
// Platform Configuration Types
// ============================================================================

export interface PlatformConfig {
  name: Platform
  enabled: boolean
  display_name: string
  check_interval_hours: number
  account_count: number
  config: PlatformSpecificConfig
}

export interface PlatformSpecificConfig {
  // Instagram/FastDL/ImgInn/Toolzu
  usernames?: string[]
  phrase_search?: PhraseSearchConfig
  run_at_start?: boolean

  // Instagram (Instaloader)
  username?: string
  password?: string
  totp_secret?: string
  session_file?: string
  accounts?: InstagramAccount[]
  max_downloads_per_user?: number

  // Toolzu
  email?: string

  // Content type settings
  posts?: ContentTypeConfig
  stories?: ContentTypeConfig
  reels?: ContentTypeConfig
  tagged?: ContentTypeConfig

  // TikTok
  full_profile?: boolean
  days_back?: number
  extensions?: string[]

  // Forums
  configs?: ForumConfig[]
  headless?: boolean
}

export interface PhraseSearchConfig {
  enabled: boolean
  usernames: string[]
  phrases: string[]
  case_sensitive: boolean
  match_all: boolean
  download_all?: boolean  // Skip phrase filtering, download all posts from these usernames
}

export interface InstagramAccount {
  username: string
  check_interval_hours: number
  run_at_start: boolean
}

export interface ContentTypeConfig {
  enabled: boolean
  days_back: number
  temp_dir: string
  destination_path: string
  extensions?: string[]
}

export interface ForumConfig {
  url: string
  username: string
  password?: string
  totp_secret?: string
  monitor_threads?: string[]
  auto_track?: boolean
  external_only?: boolean
  update_monitored?: boolean
}

// ============================================================================
// Scheduler Types
// ============================================================================

export interface SchedulerTask {
  id: string
  platform: Platform
  enabled: boolean
  interval_hours: number
  next_run: string
  last_run?: string
  status: TaskStatus
  accounts?: string[]
}

export type TaskStatus =
  | 'idle'
  | 'running'
  | 'scheduled'
  | 'failed'
  | 'disabled'

export interface CurrentActivity {
  platform: Platform
  source: string
  started_at: string
  status: string
  progress?: number
}

// ============================================================================
// Statistics Types
// ============================================================================

export interface Stats {
  total_downloads: number
  by_platform: Record<Platform, number>
  total_size: number
  last_24h: number
  last_7d: number
  last_30d: number
  duplicates_prevented: number
}

export interface HealthStatus {
  status: 'healthy' | 'degraded' | 'error'
  database: DatabaseHealth
  scheduler: SchedulerHealth
  disk_space: DiskSpaceInfo
  services: ServiceHealth[]
}

export interface DatabaseHealth {
  connected: boolean
  size: number
  wal_size?: number
  tables: number
}

export interface SchedulerHealth {
  running: boolean
  active_tasks: number
  total_tasks: number
}

export interface DiskSpaceInfo {
  total: number
  used: number
  free: number
  percent_used: number
}

export interface ServiceHealth {
  name: string
  status: 'running' | 'stopped' | 'error'
  uptime?: number
}

// ============================================================================
// Analytics Types
// ============================================================================

export interface AnalyticsData {
  downloads_over_time: TimeSeriesData[]
  downloads_by_platform: PieChartData[]
  downloads_by_content_type: PieChartData[]
  downloads_by_source: BarChartData[]
  storage_usage: StorageData
}

export interface TimeSeriesData {
  date: string
  count: number
  platform?: Platform
}

export interface PieChartData {
  name: string
  value: number
  color?: string
}

export interface BarChartData {
  name: string
  count: number
  platform?: Platform
}

export interface StorageData {
  total_size: number
  by_platform: Record<Platform, number>
  by_content_type: Record<ContentType, number>
}

// ============================================================================
// Notification Types
// ============================================================================

export interface Notification {
  id: number
  platform: Platform
  source: string
  content_type: ContentType
  message: string
  title: string
  priority: number
  download_count: number
  sent_at: string
  status: 'sent' | 'failed'
  response_data?: Record<string, unknown>
  metadata?: Record<string, unknown>
}

export interface NotificationStats {
  total: number
  by_platform: Record<Platform, number>
  by_status: Record<string, number>
  last_24h: number
}

// ============================================================================
// API Response Types
// ============================================================================

export interface APIResponse<T> {
  data: T
  message?: string
  timestamp: string
}

export interface APIError {
  error: string
  message: string
  details?: Record<string, unknown>
  timestamp: string
}

export interface PaginatedResponse<T> {
  items: T[]
  total: number
  offset: number
  limit: number
  has_more: boolean
}

// ============================================================================
// WebSocket Message Types
// ============================================================================

export interface WebSocketMessage {
  type: WebSocketMessageType
  data?: unknown
  timestamp?: string
}

export type WebSocketMessageType =
  | 'download_started'
  | 'download_completed'
  | 'download_error'
  | 'download_progress'
  | 'scheduler_update'
  | 'config_updated'
  | 'batch_delete_completed'
  | 'batch_move_completed'
  | 'batch_move_progress'
  | 'log'
  | 'health_update'
  | 'face_reference_added'
  | 'face_recognition_completed'
  | 'review_rescan_started'
  | 'review_rescan_progress'
  | 'review_rescan_complete'
  | 'review_rescan_error'

export interface DownloadStartedMessage extends WebSocketMessage {
  type: 'download_started'
  data: {
    platform: Platform
    username: string
    timestamp: string
  }
}

export interface DownloadCompletedMessage extends WebSocketMessage {
  type: 'download_completed'
  data: {
    platform: Platform
    filename: string
    username?: string
    timestamp: string
  }
}

export interface DownloadErrorMessage extends WebSocketMessage {
  type: 'download_error'
  data: {
    platform: Platform
    error: string
    timestamp: string
  }
}

export interface FaceReferenceAddedMessage extends WebSocketMessage {
  type: 'face_reference_added'
  data: {
    person_name: string
    reference_count: number
    timestamp: string
  }
}

export interface FaceRecognitionCompletedMessage extends WebSocketMessage {
  type: 'face_recognition_completed'
  data: {
    file_path: string
    faces_found: number
    timestamp: string
  }
}

export interface BatchMoveProgressMessage extends WebSocketMessage {
  type: 'batch_move_progress'
  data: {
    current: number
    total: number
    current_file: string
    timestamp: string
  }
}

export interface ReviewRescanMessage extends WebSocketMessage {
  type: 'review_rescan_started' | 'review_rescan_progress' | 'review_rescan_complete' | 'review_rescan_error'
  data: {
    status?: string
    progress?: number
    total?: number
    message?: string
    timestamp: string
  }
}

// ============================================================================
// Form & Input Types
// ============================================================================

export interface TriggerDownloadRequest {
  username: string
  options?: DownloadOptions
}

export interface DownloadOptions {
  days_back?: number
  content_types?: ContentType[]
  force?: boolean
}

export interface UpdateConfigRequest {
  platform: Platform
  config: Partial<PlatformSpecificConfig>
}

export interface BatchOperationRequest {
  file_paths: string[]
  destination?: string
}

export interface BatchOperationResponse {
  deleted_count?: number
  moved_count?: number
  failed: string[]
  success: string[]
}

// ============================================================================
// Filter & Search Types
// ============================================================================

export interface DownloadFilters {
  platform?: Platform
  source?: string
  content_type?: ContentType
  search?: string
  media_type?: 'image' | 'video' | 'all'
  date_from?: string
  date_to?: string
}

export interface PaginationOptions {
  limit: number
  offset: number
  order_by?: string
  order_direction?: 'asc' | 'desc'
}

// ============================================================================
// Changelog Types
// ============================================================================

export interface ChangelogEntry {
  version: string
  date: string
  title: string
  type: 'major' | 'minor' | 'patch'
  changes: string[]
  breaking_changes: string[]
  notes?: string
}

// ============================================================================
// Icon Types (for Lucide React)
// ============================================================================

export type IconComponent = LucideIcon

// ============================================================================
// Platform Configuration UI Types
// ============================================================================

export interface PlatformGroupConfig {
  platforms: string[]
  icon: IconComponent
  color: string
}

export interface ContentTypeUIConfig {
  label: string
  icon: IconComponent
  color: string
}

export interface StatusUIConfig {
  label: string
  color: string
  icon: IconComponent
}

// ============================================================================
// Lightbox Types
// ============================================================================

export interface LightboxItem {
  id: string | number
  src: string
  file_path?: string
  filename?: string
  thumbnail?: string
  media_type?: 'image' | 'video'
  width?: number
  height?: number
  title?: string
  description?: string
}

// ============================================================================
// Recycle Bin Types
// ============================================================================

export interface RecycledItem {
  id: string
  filename: string
  file_path: string
  original_path: string
  file_size: number
  deleted_at: string
  deleted_by: string
  reason?: string
  platform?: Platform
  source?: string
  metadata?: Record<string, unknown>
}

export interface RecycleStats {
  total_items: number
  total_size: number
  by_platform: Record<string, number>
  oldest_item?: string
  newest_item?: string
}

export interface RecycleListResponse {
  files: RecycledItem[]
  total: number
  offset: number
  limit: number
}

// ============================================================================
// YouTube Types
// ============================================================================

export interface YouTubeChannel {
  id: number
  channel_id: string
  channel_name: string
  enabled: boolean
  check_interval_hours: number
  last_check?: string
  next_run?: string
  video_count?: number
  created_at: string
}

export interface YouTubeChannelUpdate {
  channel_name?: string
  enabled?: boolean
  check_interval_hours?: number
}

// ============================================================================
// Scraper Types
// ============================================================================

export interface Scraper {
  id: string
  name: string
  type: string
  url?: string
  enabled: boolean
  status: 'idle' | 'running' | 'error'
  last_run?: string
  next_run?: string
  config: Record<string, unknown>
}

export interface ScraperUpdate {
  name?: string
  enabled?: boolean
  config?: Record<string, unknown>
}

// ============================================================================
// Video Queue Types
// ============================================================================

export interface VideoQueueItem {
  id: number
  url: string
  platform: string
  status: 'pending' | 'downloading' | 'completed' | 'failed'
  title?: string
  duration?: number
  file_path?: string
  error?: string
  created_at: string
  completed_at?: string
}

// ============================================================================
// Celebrity Discovery Types
// ============================================================================

export interface CelebritySearchJob {
  id: string
  celebrity_id: number
  celebrity_name: string
  status: 'pending' | 'searching' | 'completed' | 'failed'
  platforms: string[]
  results_count: number
  errors: CelebritySearchError[]
  created_at: string
  completed_at?: string
}

export interface CelebritySearchError {
  platform: string
  message: string
  timestamp: string
}

// ============================================================================
// Service Configuration Types
// ============================================================================

export interface ServiceConfig {
  name: string
  enabled: boolean
  service_name: string
  description?: string
}

// ============================================================================
// Health & Error Types
// ============================================================================

export interface ErrorLogEntry {
  id: number
  level: 'error' | 'warning' | 'critical'
  message: string
  module?: string
  timestamp: string
  details?: Record<string, unknown>
}
