import db from '@/services/db'

export interface BlockerRecord {
  id?: number
  projectId: number
  huId?: number
  huTitle?: string
  date: string
  category: string
  description: string
  spAffected: number
  resolvedAt?: string
  resolution?: string
  timeLostHours: number
  createdBy?: string
  createdAt: string
}

export type BlockerCategory = 'client' | 'pm' | 'tech' | 'external' | 'other'

const CATEGORY_LABELS: Record<BlockerCategory, string> = {
  client: 'Cliente',
  pm: 'Lambda',
  tech: 'Técnico',
  external: 'Terceros',
  other: 'Otro',
}

const CATEGORY_COLORS: Record<BlockerCategory, string> = {
  client: 'text-orange-600 bg-orange-100 dark:bg-orange-900/30 dark:text-orange-400',
  pm: 'text-blue-600 bg-blue-100 dark:bg-blue-900/30 dark:text-blue-400',
  tech: 'text-red-600 bg-red-100 dark:bg-red-900/30 dark:text-red-400',
  external: 'text-purple-600 bg-purple-100 dark:bg-purple-900/30 dark:text-purple-400',
  other: 'text-gray-600 bg-gray-100 dark:bg-gray-900/30 dark:text-gray-400',
}

export function getBlockerCategoryLabel(cat: BlockerCategory): string {
  return CATEGORY_LABELS[cat] || cat
}

export function getBlockerCategoryColor(cat: BlockerCategory): string {
  return CATEGORY_COLORS[cat] || ''
}

export const BLOCKER_CATEGORIES: BlockerCategory[] = ['client', 'pm', 'tech', 'external', 'other']

export async function saveBlocker(blocker: BlockerRecord): Promise<number> {
  if (blocker.id) {
    await (db as any).table('blockers').put(blocker)
    return blocker.id
  }
  return (db as any).table('blockers').add(blocker)
}

export async function getBlockers(projectId: number): Promise<BlockerRecord[]> {
  return (db as any).table('blockers').where('projectId').equals(projectId).toArray()
}

export async function getActiveBlockers(projectId: number): Promise<BlockerRecord[]> {
  const all = await getBlockers(projectId)
  return all.filter(b => !b.resolvedAt)
}

export async function getBlockersByCategory(projectId: number): Promise<Record<BlockerCategory, BlockerRecord[]>> {
  const all = await getBlockers(projectId)
  const grouped: Record<string, BlockerRecord[]> = {}
  for (const b of all) {
    const cat = b.category || 'other'
    if (!grouped[cat]) grouped[cat] = []
    grouped[cat].push(b)
  }
  return grouped as Record<BlockerCategory, BlockerRecord[]>
}

export async function resolveBlocker(id: number, resolution: string, resolvedAt: string): Promise<void> {
  const blocker = await (db as any).table('blockers').get(id)
  if (blocker) {
    blocker.resolvedAt = resolvedAt
    blocker.resolution = resolution
    await (db as any).table('blockers').put(blocker)
  }
}

export async function getBlockerStats(projectId: number): Promise<{
  totalBlocks: number
  activeBlocks: number
  totalHoursLost: number
  byCategory: Record<string, { count: number; hours: number }>
}> {
  const all = await getBlockers(projectId)
  const active = all.filter(b => !b.resolvedAt)
  const byCategory: Record<string, { count: number; hours: number }> = {}

  for (const b of all) {
    const cat = b.category || 'other'
    if (!byCategory[cat]) byCategory[cat] = { count: 0, hours: 0 }
    byCategory[cat].count++
    byCategory[cat].hours += b.timeLostHours || 0
  }

  return {
    totalBlocks: all.length,
    activeBlocks: active.length,
    totalHoursLost: all.reduce((s, b) => s + (b.timeLostHours || 0), 0),
    byCategory,
  }
}
