import { Injectable, signal, computed } from '@angular/core';

export interface Article {
  id: number;
  title: string;
  category: string;
  body: string;
  author: string;
  date: string;
  status: 'pending' | 'approved' | 'rejected';
  approvalLevel: number; // 1 = Tech Review, 2 = HR Review, 3 = Approved
  likes: number;
  shares: number;
  commentsCount: number;
  shareTargets: string[];
  comments: string[];
}

@Injectable({
  providedIn: 'root'
})
export class ContentService {
  private currentId = 5;

  // Signal for published articles (visible in Info Hub)
  private _articles = signal<Article[]>([
    {
      id: 1,
      title: 'Anuncio de Nuevos Clientes Estratégicos',
      category: 'Company',
      body: 'Anuncio de Nuevos Clientes e...ncecentos estratégicos, aux ama ponientro del da...',
      author: 'App',
      date: 'Hace 2 horas',
      status: 'approved',
      approvalLevel: 3,
      likes: 230,
      shares: 18,
      commentsCount: 45,
      shareTargets: ['LinkedIn', 'X', 'Intranet'],
      comments: [
        'Excelente logro corporativo.',
        'Bienvenidos los nuevos socios estratégicos!'
      ]
    },
    {
      id: 2,
      title: 'Resultados del Trimestre',
      category: 'Company',
      body: 'Estalles de resultados de Trimestre et estratégicos lo denagua escomenate...',
      author: 'App',
      date: 'Hace 15m',
      status: 'approved',
      approvalLevel: 3,
      likes: 230,
      shares: 18,
      commentsCount: 45,
      shareTargets: ['LinkedIn', 'Intranet'],
      comments: []
    },
    {
      id: 3,
      title: 'Actualización de Tarifa Anual',
      category: 'Company',
      body: 'Resultados del Trimestre, estratégicos en Anuncio de nuevos Clientes.',
      author: 'App',
      date: 'Hace 2 horas',
      status: 'approved',
      approvalLevel: 3,
      likes: 230,
      shares: 18,
      commentsCount: 45,
      shareTargets: ['X', 'Intranet'],
      comments: []
    },
    {
      id: 5,
      title: 'Taller de Desarrollo de Habilidades',
      category: 'Team',
      body: 'Taller de Desarrollo de Habilidades en Anuncio de Nuevos Clientes.',
      author: 'App',
      date: 'Ayer',
      status: 'approved',
      approvalLevel: 3,
      likes: 230,
      shares: 18,
      commentsCount: 45,
      shareTargets: ['Intranet'],
      comments: []
    },
    {
      id: 6,
      title: 'Nuevo Miembro en el Equipo',
      category: 'Team',
      body: 'Nuevo Miembro en el Equipo, i nuevo Miembro en el Equipo.',
      author: 'App',
      date: 'Hace 3 días',
      status: 'approved',
      approvalLevel: 3,
      likes: 220,
      shares: 6,
      commentsCount: 45,
      shareTargets: ['Intranet'],
      comments: []
    }
  ]);

  // Signal for pending approvals (visible in Workflow Module)
  private _pending = signal<Article[]>([
    {
      id: 4,
      title: 'Manual de Seguridad de Datos para Desarrolladores',
      category: 'Seguridad',
      body: 'Documento técnico con las directrices de codificación segura, rotación de secretos en Azure y cumplimiento con OWASP Top 10 para APIs REST.',
      author: 'David Chen',
      date: 'Hace 1 hora',
      status: 'pending',
      approvalLevel: 1, // 1st level approval needed
      likes: 0,
      shares: 0,
      commentsCount: 0,
      shareTargets: ['Intranet'],
      comments: []
    }
  ]);

  articles = computed(() => this._articles());
  pending = computed(() => this._pending());

  addPending(title: string, category: string, body: string, author: string, shareTargets: string[]): void {
    const newArticle: Article = {
      id: this.currentId++,
      title,
      category,
      body,
      author,
      date: 'Hace un momento',
      status: 'pending',
      approvalLevel: 1,
      likes: 0,
      shares: 0,
      commentsCount: 0,
      shareTargets,
      comments: []
    };
    this._pending.update(prev => [newArticle, ...prev]);
  }

  advanceApproval(id: number): void {
    let articleToMove: Article | undefined;

    this._pending.update(prev => {
      const items = prev.map(art => {
        if (art.id === id) {
          const nextLevel = art.approvalLevel + 1;
          if (nextLevel > 2) {
            // Reaches level 3 -> Approved & Published
            articleToMove = { ...art, status: 'approved', approvalLevel: 3, date: 'Publicado hace un momento' };
            return null;
          }
          return { ...art, approvalLevel: nextLevel };
        }
        return art;
      });
      return items.filter(art => art !== null) as Article[];
    });

    if (articleToMove) {
      this._articles.update(prev => [articleToMove!, ...prev]);
    }
  }

  rejectArticle(id: number): void {
    this._pending.update(prev => prev.filter(art => art.id !== id));
  }

  likeArticle(id: number): void {
    this._articles.update(prev => {
      return prev.map(art => art.id === id ? { ...art, likes: art.likes + 1 } : art);
    });
  }

  shareArticle(id: number): void {
    this._articles.update(prev => {
      return prev.map(art => art.id === id ? { ...art, shares: art.shares + 1 } : art);
    });
  }

  addComment(id: number, comment: string): void {
    this._articles.update(prev => {
      return prev.map(art => {
        if (art.id === id) {
          return {
            ...art,
            comments: [...art.comments, comment],
            commentsCount: art.commentsCount + 1
          };
        }
        return art;
      });
    });
  }
}
