import { CommonModule } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component, Input } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AuthService } from '../auth.service';
import { Subject, takeUntil } from 'rxjs';
import { LanguageService } from '../language.service';
import { TranslationService } from '../translation.service';

@Component({
  selector: 'app-comment-section',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './comment-section.component.html',
  styleUrls: ['./comment-section.component.css']
})
export class CommentSectionComponent {
  @Input() storyId!: number;

  comments: any[] = [];
  visibleComments: any[] = [];
  displayCount = 2;
  showLoginTooltip = false;

  commentText = '';
  parentId: number | null = null;
isLoggedIn: boolean = false;
  userId: number | null = null;
  currentUserName:string = '';
  selectedLanguage: string = 'en';

  replyMode = false;
  replyParentId: number | null = null;

  error = '';
  message = '';

  currentUserProfile: string | null = null;
  userImgPath = 'https://infoways.in/funtelapi/'; 
  hideUserImage = false;
    private destroy$ = new Subject<void>();
  
    profileImagePath = 'https://infoways.in/funtelapi/';
    
    currentUser: any = null;
    profileImageUrl: string | null = null;
    userName: string = '';
  constructor(private http: HttpClient, private authService: AuthService, public translationService: TranslationService, 
          private languageService: LanguageService ) {}

  ngOnInit(): void {
    this.selectedLanguage = this.languageService.getCurrentLanguage();
    this.languageService.currentLanguage$.subscribe(lang => {
      this.selectedLanguage = lang;
    });
this.authService.currentUser$.pipe(takeUntil(this.destroy$)).subscribe(user => {
      this.currentUser = user;
      this.isLoggedIn = !!user;

      if (user) {
        this.userName = user.name || user.email || 'User';
        
        this.profileImageUrl = user.profileimg 
         console.log('Current User path:', this.profileImageUrl);
      } else {
        this.userName = '';
        this.profileImageUrl = null;
      }
    });
    this.http.get<any>('https://infoways.in/funtelapi/userinfo.php', {
      withCredentials: true
    }).subscribe({
      next: (res) => {
        console.log('User info:', res);
        if (res.status === 'success') {
          this.userId = res.user.id;
          this.currentUserName = res.user.name;
          this.currentUserProfile = res.user.profile_image; // assuming the API returns profile_image
          console.log('✅ User info loaded:', res.user);
        } else {
          console.warn('⚠️ User info not available (unauthenticated)');
        }
      },
      error: (err) => {
        console.error('❌ Failed to fetch user info:', err);
      }
    });

    this.loadComments();
    document.addEventListener('click', this.handleClickOutside.bind(this));
  }
  ngOnDestroy(): void {
  document.removeEventListener('click', this.handleClickOutside.bind(this));
}

handleClickOutside(event: MouseEvent): void {
  const target = event.target as HTMLElement;
  if (!target.closest('#comment-text') && !target.closest('.tooltip-box')) {
    this.showLoginTooltip = false;
  }
}
  checkLoginStatus(): void {
  this.authService.getUserDetails().subscribe({
    next: (res) => {
      if (res.status === 'success') {
        this.userName = res.user?.name || res.user?.email || 'User';
        this.isLoggedIn = true;
      } else {
        this.isLoggedIn = false; // Just update status, don't redirect
        this.userName = '';
      }
    },
    error: () => {
      this.isLoggedIn = false; // Just update status, don't redirect
      this.userName = '';
    }
  });
}

  onImageError(): void {
    this.hideUserImage = true;
  }

t(key: string): string {
    return this.translationService.translate(key);
  }

  loadComments(): void {
    this.http.get<any>(`https://infoways.in/funtelapi/get_comments.php?story_id=${this.storyId}`)
      .subscribe({
        next: (res: any) => {
          if (res.status === 'success') {
            this.comments = this.buildCommentTree(res.data);
            this.visibleComments = this.comments.slice(0, this.displayCount);
          } else {
            this.error = res.message || 'Failed to load comments.';
          }
        },
        error: err => {
          this.error = err.error?.message || 'Failed to load comments.';
        }
      });
  }

  showMoreComments(): void {
    this.displayCount += 2;
    this.visibleComments = this.comments.slice(0, this.displayCount);
  }

  buildCommentTree(flat: any[]): any[] {
    const map: Record<number, any> = {};
    const roots: any[] = [];

    flat.forEach(item => {
      item.replies = [];
      map[item.id] = item;
    });

    flat.forEach(item => {
      if (item.parent_id && map[item.parent_id]) {
        map[item.parent_id].replies.push(item);
      } else {
        roots.push(item);
      }
    });

    return roots;
  }

  setReply(id: number): void {
    this.replyMode = true;
    this.replyParentId = id;
    this.parentId = id;
    this.commentText = '';
  }

  cancelReply(): void {
    this.replyMode = false;
    this.replyParentId = null;
    this.parentId = null;
    this.commentText = '';
  }

  postComment(): void {
    this.userId = this.authService.getCurrentUserId();
    console.log('Posting comment:', this.commentText, 'for storyId:', this.storyId, 'by userId:', this.userId);
    if (!this.commentText.trim() || !this.userId) {
      this.error = 'Please log in to comment.';
      return;
    }

    const body = {
      story_id: this.storyId,
      comment: this.commentText,
      parent_id: this.parentId,
      user_id: this.userId
    };

    this.http.post<any>('https://infoways.in/funtelapi/add_comment.php', body, {
      withCredentials: true
    }).subscribe({
      next: (res: any) => {
        if (res.status === 'success') {
          this.commentText = '';
          this.cancelReply();
          this.loadComments();
        } else {
          this.error = res.message || 'Failed to post comment.';
        }
      },
      error: err => {
        this.error = err.error?.message || 'Failed to post comment.';
      }
    });
  }

  react(commentId: number, type: 'like' | 'dislike'): void {
    this.userId = this.authService.getCurrentUserId();
    if (!this.userId) return;

    const body = {
      action: 'react',
      comment_id: commentId,
      user_id: this.userId,
      type
    };

    this.http.post<any>('https://infoways.in/funtelapi/add_comment.php', body, {
      withCredentials: true
    }).subscribe({
      next: () => this.loadComments(),
      error: () => this.loadComments()
    });
  }

  getRelativeTime(dateString: string): string {
    const now = new Date().getTime();
    const then = new Date(dateString).getTime();
    if (isNaN(then)) return '';
    const diffSec = Math.floor((now - then) / 1000);
    if (diffSec < 60) return 'just now';
    const mins = Math.floor(diffSec / 60);
    if (mins < 60) return `${mins} min${mins > 1 ? 's' : ''} ago`;
    const hrs = Math.floor(mins / 60);
    if (hrs < 24) return `${hrs} hour${hrs > 1 ? 's' : ''} ago`;
    const days = Math.floor(hrs / 24);
    if (days < 30) return `${days} day${days > 1 ? 's' : ''} ago`;
    const months = Math.floor(days / 30);
    if (months < 12) return `${months} month${months > 1 ? 's' : ''} ago`;
    const years = Math.floor(months / 12);
    return `${years} year${years > 1 ? 's' : ''} ago`;
  }
  handleTextareaClick(event: Event): void {
  if (!this.isLoggedIn) {
    event.preventDefault();
    this.showLoginTooltip = true;
  }
}

redirectToLogin(): void {
  
  window.location.href = '/login'; 
}
}
