import { getPayload } from 'payload'
import config from '@payload-config'
import { NextRequest, NextResponse } from 'next/server'
import { subDays } from 'date-fns'
import {
  calculateComparison,
  calculateTrends,
  calculateROI,
} from '@/lib/youtube/analytics-helpers'
import type { Metric, VideoWithPerformance } from '@/lib/youtube/analytics-helpers'

interface UserWithYouTubeRole {
  id: number
  isSuperAdmin?: boolean
  youtubeRole?: string
}

function getPeriodDates(period: string) {
  const now = new Date()
  switch (period) {
    case '7d':
      return { start: subDays(now, 7), prevStart: subDays(now, 14), prevEnd: subDays(now, 7) }
    case '90d':
      return { start: subDays(now, 90), prevStart: subDays(now, 180), prevEnd: subDays(now, 90) }
    default:
      return { start: subDays(now, 30), prevStart: subDays(now, 60), prevEnd: subDays(now, 30) }
  }
}

async function getPerformanceData(payload: any, channel: string, period: string) {
  const { start, prevStart, prevEnd } = getPeriodDates(period)

  const where: Record<string, unknown> = {
    status: { equals: 'published' },
    actualPublishDate: { greater_than_equal: start.toISOString() },
  }
  if (channel !== 'all') {
    where.channel = { equals: parseInt(channel) }
  }

  const prevWhere: Record<string, unknown> = {
    status: { equals: 'published' },
    actualPublishDate: {
      greater_than_equal: prevStart.toISOString(),
      less_than: prevEnd.toISOString(),
    },
  }
  if (channel !== 'all') {
    prevWhere.channel = { equals: parseInt(channel) }
  }

  const [current, previous] = await Promise.all([
    payload.find({
      collection: 'youtube-content',
      where,
      limit: 100,
      depth: 0,
      sort: '-performance.views',
    }),
    payload.find({
      collection: 'youtube-content',
      where: prevWhere,
      limit: 100,
      depth: 0,
    }),
  ])

  const docs = current.docs
  const prevDocs = previous.docs

  let totalViews = 0, totalWatchTime = 0, totalCtr = 0, totalSubscribers = 0
  let totalLikes = 0, totalComments = 0, totalShares = 0
  let ctrCount = 0

  for (const doc of docs) {
    const p = doc.performance || {}
    totalViews += p.views || 0
    totalWatchTime += p.watchTimeMinutes || 0
    if (p.ctr != null) { totalCtr += p.ctr; ctrCount++ }
    totalSubscribers += p.subscribersGained || 0
    totalLikes += p.likes || 0
    totalComments += p.comments || 0
    totalShares += p.shares || 0
  }

  let prevViews = 0, prevWatchTime = 0, prevSubscribers = 0
  for (const doc of prevDocs) {
    const p = doc.performance || {}
    prevViews += p.views || 0
    prevWatchTime += p.watchTimeMinutes || 0
    prevSubscribers += p.subscribersGained || 0
  }

  const sorted = [...docs].sort((a, b) => (b.performance?.views || 0) - (a.performance?.views || 0))
  const mapVideo = (d: any) => ({
    id: d.id,
    title: d.title,
    thumbnailText: d.thumbnailText || '',
    views: d.performance?.views || 0,
    ctr: d.performance?.ctr || 0,
    avgRetention: d.performance?.avgViewPercentage || 0,
    likes: d.performance?.likes || 0,
  })

  return {
    stats: {
      totalViews,
      totalWatchTimeHours: Math.round((totalWatchTime / 60) * 10) / 10,
      avgCtr: ctrCount > 0 ? Math.round((totalCtr / ctrCount) * 100) / 100 : 0,
      subscribersGained: totalSubscribers,
    },
    comparison: {
      views: prevViews > 0 ? Math.round(((totalViews - prevViews) / prevViews) * 100) : 0,
      watchTime: prevWatchTime > 0 ? Math.round(((totalWatchTime - prevWatchTime) / prevWatchTime) * 100) : 0,
      subscribers: prevSubscribers > 0 ? Math.round(((totalSubscribers - prevSubscribers) / prevSubscribers) * 100) : 0,
    },
    topVideos: sorted.slice(0, 5).map(mapVideo),
    bottomVideos: sorted.length > 5 ? sorted.slice(-5).reverse().map(mapVideo) : [],
    engagement: { likes: totalLikes, comments: totalComments, shares: totalShares },
  }
}

async function getPipelineData(payload: any, channel: string) {
  const channelFilter: Record<string, unknown> = channel !== 'all'
    ? { channel: { equals: parseInt(channel) } }
    : {}

  const statuses = ['idea', 'script_draft', 'script_review', 'script_approved',
    'shoot_scheduled', 'shot', 'rough_cut', 'fine_cut', 'final_review',
    'approved', 'upload_scheduled', 'published']

  const counts = await Promise.all(
    statuses.map((s) =>
      payload.count({
        collection: 'youtube-content',
        where: { status: { equals: s }, ...channelFilter },
      }),
    ),
  )

  const pipeline: Record<string, number> = {}
  statuses.forEach((s, i) => { pipeline[s] = counts[i].totalDocs })

  const inProduction = Object.entries(pipeline)
    .filter(([k]) => k !== 'published')
    .reduce((sum, [, v]) => sum + v, 0)

  const weekStart = new Date()
  weekStart.setHours(0, 0, 0, 0)
  const weekEnd = new Date(weekStart)
  weekEnd.setDate(weekEnd.getDate() + 7)

  const weekWhere: Record<string, unknown> = {
    scheduledPublishDate: {
      greater_than_equal: weekStart.toISOString(),
      less_than: weekEnd.toISOString(),
    },
    ...channelFilter,
  }

  const [thisWeek, overdueTasks, pendingApprovals] = await Promise.all([
    payload.find({
      collection: 'youtube-content',
      where: weekWhere,
      sort: 'scheduledPublishDate',
      depth: 1,
      limit: 20,
    }),
    payload.find({
      collection: 'yt-tasks',
      where: {
        and: [
          { status: { not_in: ['done', 'cancelled'] } },
          { dueDate: { less_than: new Date().toISOString() } },
          ...(channel !== 'all' ? [{ channel: { equals: parseInt(channel) } }] : []),
        ],
      },
      depth: 1,
      limit: 20,
      sort: 'dueDate',
    }),
    payload.count({
      collection: 'youtube-content',
      where: {
        status: { in: ['script_review', 'final_review'] },
        ...channelFilter,
      },
    }),
  ])

  return {
    stats: {
      inProduction,
      thisWeekCount: thisWeek.totalDocs,
      overdueTasksCount: overdueTasks.totalDocs,
      pendingApprovals: pendingApprovals.totalDocs,
    },
    pipeline,
    thisWeekVideos: thisWeek.docs.map((d: any) => ({
      id: d.id,
      title: d.title,
      status: d.status,
      scheduledPublishDate: d.scheduledPublishDate,
      channel: typeof d.channel === 'object' ? d.channel?.name : d.channel,
    })),
    overdueTasks: overdueTasks.docs.map((d: any) => ({
      id: d.id,
      title: d.title,
      dueDate: d.dueDate,
      assignedTo: typeof d.assignedTo === 'object' ? d.assignedTo?.email : d.assignedTo,
      video: typeof d.video === 'object' ? d.video?.title : null,
    })),
  }
}

async function getGoalsData(payload: any, channel: string) {
  const now = new Date()
  const monthStart = new Date(now.getFullYear(), now.getMonth(), 1)
  const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0)

  const where: Record<string, unknown> = {
    month: {
      greater_than_equal: monthStart.toISOString(),
      less_than_equal: monthEnd.toISOString(),
    },
  }
  if (channel !== 'all') {
    where.channel = { equals: parseInt(channel) }
  }

  const goals = await payload.find({
    collection: 'yt-monthly-goals',
    where,
    depth: 1,
    limit: 10,
  })

  if (goals.docs.length === 0) {
    return { stats: { contentProgress: 0, contentLabel: '0/0', subscriberProgress: 0, subscriberLabel: '0/0', viewsProgress: 0, viewsLabel: '0/0', overall: 0 }, goals: [], customGoals: [] }
  }

  let totalContentTarget = 0, totalContentCurrent = 0
  let totalSubsTarget = 0, totalSubsCurrent = 0
  let totalViewsTarget = 0, totalViewsCurrent = 0
  const allCustomGoals: { metric: string; target: string; current: string; status: string }[] = []

  for (const goal of goals.docs) {
    const c = (goal as any).contentGoals || {}
    totalContentTarget += (c.longformsTarget || 0) + (c.shortsTarget || 0)
    totalContentCurrent += (c.longformsCurrent || 0) + (c.shortsCurrent || 0)

    const a = (goal as any).audienceGoals || {}
    totalSubsTarget += a.subscribersTarget || 0
    totalSubsCurrent += a.subscribersCurrent || 0
    totalViewsTarget += a.viewsTarget || 0
    totalViewsCurrent += a.viewsCurrent || 0

    if ((goal as any).customGoals) {
      for (const cg of (goal as any).customGoals) {
        allCustomGoals.push({
          metric: cg.metric,
          target: cg.target,
          current: cg.current,
          status: cg.status,
        })
      }
    }
  }

  const pct = (current: number, target: number) => target > 0 ? Math.round((current / target) * 100) : 0
  const contentPct = pct(totalContentCurrent, totalContentTarget)
  const subsPct = pct(totalSubsCurrent, totalSubsTarget)
  const viewsPct = pct(totalViewsCurrent, totalViewsTarget)
  const overall = Math.round((contentPct + subsPct + viewsPct) / 3)

  return {
    stats: {
      contentProgress: contentPct,
      contentLabel: `${totalContentCurrent}/${totalContentTarget}`,
      subscriberProgress: subsPct,
      subscriberLabel: `${totalSubsCurrent}/${totalSubsTarget}`,
      viewsProgress: viewsPct,
      viewsLabel: `${totalViewsCurrent}/${totalViewsTarget}`,
      overall,
    },
    goals: goals.docs.map((g: any) => ({
      id: g.id,
      channel: typeof g.channel === 'object' ? g.channel?.name : g.channel,
      month: g.month,
      contentGoals: g.contentGoals,
      audienceGoals: g.audienceGoals,
      engagementGoals: g.engagementGoals,
      businessGoals: g.businessGoals,
      notes: g.notes,
    })),
    customGoals: allCustomGoals,
  }
}

async function getCommunityData(payload: any, channel: string, period: string) {
  const { start } = getPeriodDates(period)

  const where: Record<string, unknown> = {
    publishedAt: { greater_than_equal: start.toISOString() },
  }
  if (channel !== 'all') {
    where.socialAccount = { equals: parseInt(channel) }
  }

  const [interactions, unresolved, escalations] = await Promise.all([
    payload.find({
      collection: 'community-interactions',
      where,
      limit: 500,
      depth: 0,
    }),
    payload.count({
      collection: 'community-interactions',
      where: { ...where, status: { equals: 'new' } },
    }),
    payload.count({
      collection: 'community-interactions',
      where: { ...where, 'flags.requiresEscalation': { equals: true }, status: { not_equals: 'resolved' } },
    }),
  ])

  const docs = interactions.docs

  const sentiment: Record<string, number> = { positive: 0, neutral: 0, negative: 0, question: 0 }
  for (const d of docs) {
    const s = (d as any).analysis?.sentiment as string
    if (s && s in sentiment) sentiment[s]++
  }
  const total = docs.length
  const positivePct = total > 0 ? Math.round((sentiment.positive / total) * 100) : 0

  let totalResponseTime = 0, responseCount = 0
  for (const d of docs) {
    if ((d as any).response?.sentAt && d.publishedAt) {
      const diff = new Date((d as any).response.sentAt as string).getTime() - new Date(d.publishedAt as string).getTime()
      totalResponseTime += diff / (1000 * 60 * 60)
      responseCount++
    }
  }
  const avgResponseHours = responseCount > 0 ? Math.round(totalResponseTime / responseCount * 10) / 10 : 0

  const topicMap = new Map<string, number>()
  for (const d of docs) {
    const topics = (d as any).analysis?.topics as string[] | undefined
    if (topics) {
      for (const t of topics) { topicMap.set(t, (topicMap.get(t) || 0) + 1) }
    }
  }
  const topTopics = [...topicMap.entries()]
    .sort((a, b) => b[1] - a[1])
    .slice(0, 10)
    .map(([topic, count]) => ({ topic, count }))

  const recent = await payload.find({
    collection: 'community-interactions',
    where: { ...where, status: { equals: 'new' } },
    sort: '-publishedAt',
    limit: 5,
    depth: 0,
  })

  return {
    stats: {
      unresolvedCount: unresolved.totalDocs,
      positivePct,
      avgResponseHours,
      escalationsCount: escalations.totalDocs,
    },
    sentiment,
    topTopics,
    recentUnresolved: recent.docs.map((d: any) => ({
      id: d.id,
      message: (d.message as string || '').slice(0, 120),
      authorName: d.author?.name || 'Unknown',
      authorHandle: d.author?.handle || '',
      publishedAt: d.publishedAt,
      platform: d.platform,
      sentiment: d.analysis?.sentiment,
    })),
  }
}

const VALID_METRICS: Metric[] = [
  'views', 'likes', 'comments', 'ctr', 'watchTimeMinutes', 'impressions', 'subscribersGained',
]

function isValidMetric(value: string): value is Metric {
  return VALID_METRICS.includes(value as Metric)
}

function mapDocToVideoWithPerformance(doc: any): VideoWithPerformance {
  return {
    id: doc.id,
    title: doc.title || '',
    performance: doc.performance || {},
    costs: doc.costs || undefined,
  }
}

async function getComparisonData(payload: any, videoIds: number[], metric: Metric) {
  if (videoIds.length === 0) {
    return { comparison: [], metric }
  }

  const results = await payload.find({
    collection: 'youtube-content',
    where: { id: { in: videoIds } },
    limit: videoIds.length,
    depth: 0,
  })

  const videos = results.docs.map(mapDocToVideoWithPerformance)
  return { comparison: calculateComparison(videos, metric), metric }
}

async function getTrendsData(payload: any, channel: string, metric: Metric) {
  const where: Record<string, unknown> = {
    status: { equals: 'published' },
  }
  if (channel !== 'all') {
    where.channel = { equals: parseInt(channel) }
  }

  const results = await payload.find({
    collection: 'youtube-content',
    where,
    limit: 100,
    depth: 0,
    sort: '-actualPublishDate',
  })

  const videos = results.docs.map(mapDocToVideoWithPerformance)
  return { trends: calculateTrends(videos, metric), metric, videoCount: videos.length }
}

async function getROIData(payload: any, channel: string) {
  const where: Record<string, unknown> = {
    status: { equals: 'published' },
    'costs.estimatedProductionCost': { greater_than: 0 },
  }
  if (channel !== 'all') {
    where.channel = { equals: parseInt(channel) }
  }

  const results = await payload.find({
    collection: 'youtube-content',
    where,
    limit: 100,
    depth: 0,
    sort: '-actualPublishDate',
  })

  const videos = results.docs.map(mapDocToVideoWithPerformance)
  return { roi: calculateROI(videos), videoCount: videos.length }
}

export async function GET(req: NextRequest) {
  try {
    const payload = await getPayload({ config })
    const { user } = await payload.auth({ headers: req.headers })
    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const typedUser = user as UserWithYouTubeRole
    if (!typedUser.isSuperAdmin && (!typedUser.youtubeRole || typedUser.youtubeRole === 'none')) {
      return NextResponse.json({ error: 'No YouTube access' }, { status: 403 })
    }

    const { searchParams } = new URL(req.url)
    const tab = searchParams.get('tab') || 'performance'
    const channel = searchParams.get('channel') || 'all'
    const period = searchParams.get('period') || '30d'

    const channels = await payload.find({
      collection: 'youtube-channels',
      where: { status: { equals: 'active' } },
      depth: 0,
      limit: 50,
    })

    let tabData: unknown = {}

    switch (tab) {
      case 'performance':
        tabData = await getPerformanceData(payload, channel, period)
        break
      case 'pipeline':
        tabData = await getPipelineData(payload, channel)
        break
      case 'goals':
        tabData = await getGoalsData(payload, channel)
        break
      case 'community':
        tabData = await getCommunityData(payload, channel, period)
        break
      case 'comparison': {
        const videoIdsParam = searchParams.get('videoIds') || ''
        const videoIds = videoIdsParam
          .split(',')
          .map((id) => parseInt(id.trim()))
          .filter((id) => !isNaN(id))
        const compMetric = searchParams.get('metric') || 'views'
        tabData = await getComparisonData(
          payload,
          videoIds,
          isValidMetric(compMetric) ? compMetric : 'views',
        )
        break
      }
      case 'trends': {
        const trendMetric = searchParams.get('metric') || 'views'
        tabData = await getTrendsData(
          payload,
          channel,
          isValidMetric(trendMetric) ? trendMetric : 'views',
        )
        break
      }
      case 'roi':
        tabData = await getROIData(payload, channel)
        break
      default:
        tabData = await getPerformanceData(payload, channel, period)
    }

    return NextResponse.json({
      tab,
      channel,
      period,
      channels: channels.docs.map((c: any) => ({ id: c.id, name: c.name, slug: c.slug })),
      data: tabData,
    })
  } catch (error) {
    console.error('[YouTube Analytics] Error:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Unknown error' },
      { status: 500 },
    )
  }
}

export const dynamic = 'force-dynamic'
