import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { HeaderComponent } from '../header/header.component';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { AuthService } from '../auth.service';
import { take } from 'rxjs';
import { TranslationService } from '../translation.service';
import { LanguageService } from '../language.service';

interface DeleteResponse {
  status: string;
  message: string;
}

@Component({
  selector: 'app-myworks',
  standalone: true,
  imports: [HeaderComponent, CommonModule, RouterModule],
  templateUrl: './myworks.component.html',
  styleUrl: './myworks.component.css'
})
export class MyworksComponent implements OnInit {
  // ---------------- State ----------------
  activeTab: string = 'stories';
  stories: any[] = [];
  isLoading = true;
  errorMessage = '';
  deleteMessage = '';
  categoryColumns: any[][] = [];
categories:any[] = [];
  storyImgPath = 'https://infoways.in/funtelapi/'; // base API root (HTTPS)

    isFollowingMap: { [authorId: string]: boolean } = {};
  storyId: number | null = null;
  storyDetail: any = null;
  userDetail: any = null;
selectedLanguage: string = 'en';
  followersList: any[] = [];
  followingList: any[] = [];
  followerCount = 0;
  followingCount = 0;

  uploadingProfile = false;
  uploadingCover = false;
  viewingUserId: string = '';
isOwnProfile: boolean = false;





  @ViewChild('profileInput') profileInput!: ElementRef<HTMLInputElement>;
  @ViewChild('coverInput') coverInput!: ElementRef<HTMLInputElement>;

  constructor(
    private http: HttpClient,
    private router: Router,
    private route: ActivatedRoute,
    private authService: AuthService,
    public translationService: TranslationService,
              private languageService: LanguageService 
  ) {}

  // ------------------------------------------------------------
  // Lifecycle
  // ------------------------------------------------------------
ngOnInit(): void {
  this.selectedLanguage = this.languageService.getCurrentLanguage();
    
    // ✅ Language changes subscribe karein
    this.languageService.currentLanguage$.subscribe(lang => {
      this.selectedLanguage = lang;
    });
  const paramId = this.route.snapshot.paramMap.get('storyId');
  this.storyId = paramId ? Number(paramId) : 0;
  this.route.paramMap.pipe(take(1)).subscribe(params => {
    this.initProfile(params.get('id'));
  });

  // Runs when navigating to another profile (e.g., /profile/21 → /profile/22)
  this.route.params.subscribe(params => {
    this.initProfile(params['id']);
  });
  this.getCategory()
 
}
t(key: string): string {
    return this.translationService.translate(key);
  }
initProfile(idFromRoute: string | null): void {
  const currentUserId = this.authService.getCurrentUserId();
  if (idFromRoute) {
    // Viewing someone else's profile - no login required
    
   this.isOwnProfile = (idFromRoute === currentUserId?.toString());
    this.viewingUserId = idFromRoute;
    
    console.log('Profile View Mode:', 
      this.isOwnProfile ? 'OWN PROFILE' : 'OTHER USER PROFILE',
      'User ID:', this.viewingUserId,
      'Logged in ID:', currentUserId
    );

    this.loadAuthorData(idFromRoute);
    this.loadProfileData(idFromRoute);
    this.loadStories(idFromRoute);
    this.loadAuthorStories(idFromRoute);
    this.loadFollowStatus(); // This will be safe-checked inside
  } else {
    // No ID in route - check if user is logged in and show their profile
    this.authService.verifyTokenAndFetchUser().pipe(take(1)).subscribe({
      next: (res) => {
        const userId = res?.user?.id ?? this.authService.getCurrentUserId();
        
        if (userId) {

          this.isOwnProfile = true;
          this.viewingUserId = userId.toString();
          console.log('Viewing own profile (no ID in route)', this.viewingUserId);

          this.loadAuthorData(this.viewingUserId);
          this.loadProfileData(this.viewingUserId);
          this.loadStories(this.viewingUserId);
          // this.loadAuthorStories(this.viewingUserId);
          this.loadFollowStatus();
        } else {
          // Still no user, redirect
          this.router.navigate(['/login']);
        }
      },
      error: () => this.router.navigate(['/login'])
    });
  }
}

  // ------------------------------------------------------------
  // Helpers
  // ------------------------------------------------------------
  private applyUserImageUrls(user: any): any {
    // builds profileimg_url & coverimage_url from filename if missing
    if (!user) { return user; }
    const userId = user.id;
    const base = `${this.storyImgPath}/`;

    if (user.profileimg_url === undefined) {
      user.profileimg_url = user.profileimg ? base + user.profileimg : '';
    }
    if (user.coverimage_url === undefined) {
      user.coverimage_url = user.coverimage ? base + user.coverimage : '';
    }
    return user;
  }

  triggerProfileUpload() {
    this.profileInput?.nativeElement.click();
  }

  triggerCoverUpload() {
    this.coverInput?.nativeElement.click();
  }

  // ------------------------------------------------------------
  // Author data
  // ------------------------------------------------------------
loadAuthorData(id: string): void {
  const headers = new HttpHeaders({
   
    'Content-Type': 'application/json'
  });
  this.http.get<any>(`https://infoways.in/funtelapi/userinfo.php?id=${id}`,{
    headers: headers,

  }).subscribe({
    next: (res) => {
      if (res.status === 'success') {
        this.userDetail = res.data;
      }
    }
  });
}

loadProfileData(userId: string): void {
  
  this.http.get<any>(`https://infoways.in/funtelapi/follow/profile_data.php?user_id=${userId}`,{
   
    withCredentials: true
  }).subscribe({
    next: (res) => {
      if (res.status === 'success') {
        this.stories = res.stories || [];
        this.followersList = res.followers || [];
        this.followingList = res.following || [];

        this.followerCount = res.followerCount || 0;
        this.followingCount = res.followingCount || 0;

        // Enhance each followed user with default counts
        this.followingList = this.followingList.map(user => ({
          ...user,
          followers_count: 0,
          stories_count: 0,
          profileimg_url: user.profileimg ? `${this.storyImgPath}/${user.profileimg}` : ''
        }));

        // Load follow status for all users after data is loaded
        this.loadFollowStatus();
      }
    },
    error: (err) => {
      console.error('Error loading profile data:', err);
    }
  });
}

async loadUserCountsForFollowingList() {
  for (const user of this.followingList) {
    try {
      const res = await this.http.get<any>(
        `https://infoways.in/funtelapi/user_counts.php?id=${user.id}`
      ).toPromise();
      
      user.followers_count = res.followers || 0;
      user.stories_count = res.stories || 0;
    } catch (err) {
      console.error(`Error loading counts for user ${user.id}:`, err);
      user.followers_count = 0;
      user.stories_count = 0;
    }
  }
}

viewProfile(authorId: string) {
  this.router.navigate(['/profile', authorId]);
}
  loadAuthorInfo(authorId: string) {
    this.http.get<any>(`https://infoways.in/funtelapi/userinfo.php?author_id=${authorId}`)
      .subscribe({
        next: (res) => {
          if (res.status === 'success') {
            this.stories = res.data || [];
          } else {
            console.error('Failed to load author stories:', res.message);
          }
        },
        error: (err) => {
          console.error('Error fetching author stories:', err);
        }
      });
  }

  loadAuthorStories(id: string): void {
  const apiUrl = `https://infoways.in/funtelapi/allstory.php?action=user&user_id=${id}`;

  this.http.get<any>(apiUrl).subscribe({
    next: (res) => {
      if (res.status === 'success') {
        // Only keep stories belonging to the specified user_id
        this.stories = res.data.filter((story: any) => story.user_id == id);
      } else {
        this.stories = [];
        console.error('Failed to load stories:', res.message);
      }
    },
    error: (err) => {
      this.stories = [];
      console.error('Error loading stories:', err);
    }
  });
}


  // ------------------------------------------------------------
  // Delete story
  // ------------------------------------------------------------
  deleteStory(storyId: number): Promise<boolean> {
  return new Promise((resolve, reject) => {
    if (!confirm('Are you sure you want to delete this Story?')) {
      resolve(false); 
      return;
    }

    this.http.post<DeleteResponse>(
      `https://infoways.in/funtelapi/allstory.php`,
      { story_id: storyId },
      { withCredentials: true }
    ).subscribe({
      next: (response) => {
        if (response.status === 'success') {
          this.deleteMessage = 'Story deleted successfully';
          this.stories = this.stories.filter(story => story.id !== storyId);
          setTimeout(() => this.deleteMessage = '', 3000);
          resolve(true);
        } else {
          alert(response.message || 'Delete failed');
          resolve(false);
        }
      },
      error: (err) => {
        console.error('Delete error:', err);
        alert(err.error?.message || 'Connection error');
        reject(err);
      }
    });
  });
}

  // ------------------------------------------------------------
  // Stories list
  // ------------------------------------------------------------
  fetchStories() {
    const userId = this.authService.getCurrentUserId();
    
  if (!userId) {
    this.errorMessage = 'Please login to view your stories';
    this.isLoading = false;
    this.router.navigate(['/login']);
    return;
  }

    this.isLoading = true;

    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      
    });

    this.http.post<{status: string, data: any[]}>(
    `${this.storyImgPath}/my_works_story_name.php`,
    { user_id: userId },
    { headers, withCredentials: true }
  ).subscribe({
      next: (response) => {
        if (response.status === 'success' && response.data) {
          this.stories = response.data;
        } else {
          this.errorMessage = 'No stories found';
        }
        this.isLoading = false;
      },
      error: (error) => {
        console.error('Error fetching stories:', error);
        this.errorMessage = 'Failed to load stories. Please try again later.';
        this.isLoading = false;
      }
    });
  }


 toggleFollow(authorId: string) {
  const userId = this.authService.getCurrentUserId();
  
  if (!userId) { this.router.navigate(['login']); return; }

  // Immediately update UI state for better responsiveness
  const wasFollowing = this.isFollowingMap[authorId];
  this.isFollowingMap[authorId] = !wasFollowing;

  const apiUrl = wasFollowing
    ? 'https://infoways.in/funtelapi/follow/unfollow.php'
    : 'https://infoways.in/funtelapi/follow/follow.php';
  const body = { follower_id: userId, following_id: +authorId };
  const headers = new HttpHeaders({ 'Content-Type': 'application/json' });

  this.http.post(apiUrl, body, { headers, withCredentials: true }).subscribe({
    error: (err) => {
      console.error('Follow/Unfollow failed:', err);
      // Revert UI state if API call fails
      this.isFollowingMap[authorId] = wasFollowing;
    }
  });
}


 loadFollowStatus() {
  const userId = this.authService.getCurrentUserId();
  const profileUserId = this.viewingUserId;

  if (!userId || !profileUserId) return;

  this.http.post<any>(
    'https://infoways.in/funtelapi/follow/check_follow.php',
    { follower_id: +userId, following_id: +profileUserId },
    { headers: new HttpHeaders({ 'Content-Type': 'application/json' }), withCredentials: true }
  ).subscribe({
    next: (res) => {
      // Update for the current profile user
      this.isFollowingMap[profileUserId] = !!res.isFollowing;
      
      // Also update for all followers/following users
      if (res.followersList) {
        res.followersList.forEach((follower: any) => {
          this.isFollowingMap[follower.id] = true;
        });
      }
      
      if (res.followingList) {
        res.followingList.forEach((following: any) => {
          this.isFollowingMap[following.id] = true;
        });
      }
    },
    error: (err) => console.error(`Error checking follow status:`, err)
  });
}

checkFollowStatus(otherUserId: string) {
  const userId = this.authService.getCurrentUserId();
  
  if (!userId) { this.router.navigate(['login']); return; }

  this.http.post<any>(
    'https://infoways.in/funtelapi/follow/check_follow.php',
    { follower_id: +userId, following_id: +otherUserId },
    { headers: new HttpHeaders({ 'Content-Type': 'application/json' }), withCredentials: true }
  ).subscribe({
    next: (res) => this.isFollowingMap[otherUserId] = !!res.isFollowing,
    error: (err) => console.error('Follow status error for', otherUserId, err)
  });
}
  // ------------------------------------------------------------
  // Tab helpers
  // ------------------------------------------------------------
  setActiveTab(tab: string) {
    this.activeTab = tab;
  }
  get totalStories(): number {
    return this.stories.length;
  }
  isActiveTab(tab: string): boolean {
    return this.activeTab === tab;
  }
  getTabClass(tab: string): string {
    const baseClasses = 'px-4 py-2 font-medium transition-colors';
    return this.isActiveTab(tab)
      ? `${baseClasses} text-wattpad-primary border-b-2 border-wattpad-primary`
      : `${baseClasses} text-wattpad-light hover:text-wattpad-primary`;
  }

  // ------------------------------------------------------------
  // Continue writing navigation
  // ------------------------------------------------------------
  continueWriting(storyId: string, title: string) {
    const slug = this.slugify(title);
    this.router.navigate(['/episode', `${storyId}-${slug}`]);
  }

  continueIsNotOwner(storyId: string, title: string) {
    const slug = this.slugify(title);
    this.router.navigate(['/story', `${storyId}-${slug}`]);
  }

 

  // ------------------------------------------------------------
  // Story detail
  // ------------------------------------------------------------
  fetchStoryDetail() {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      
    });

    this.http.post<{ status: string, data: any }>(
      `${this.storyImgPath}/getstorydetails.php?id=${this.storyId}`,
      {},
      { headers }
    ).subscribe({
      next: (response) => {
        if (response.status === 'success' && response.data) {
          this.storyDetail = response.data;
        } else {
          this.errorMessage = 'Story detail not found.';
        }
      },
      error: (error) => {
        console.error('Error fetching story detail:', error);
        this.errorMessage = 'Failed to load story detail.';
      }
    });
  }
getTypeOf(value: any): string {
  return typeof value;
}
getStoryStatus(story: any): string {
  // Handle both string and number status values
  return String(story?.story_status || '0').trim();
}
  // Update the loadStories method:
loadStories(id: string): void {
  this.isLoading = true;
  this.errorMessage = '';
  const apiUrl = `https://infoways.in/funtelapi/allstory.php?action=myworks`;

  this.http.get<any>(apiUrl, { withCredentials: true }).subscribe({
    next: (res) => {
      console.log('RAW API RESPONSE:', res);
      this.isLoading = false;
      if (res.status === 'success' && res.data && res.data.length > 0) {
        // Filter stories to only show those belonging to the viewing user
        this.stories = res.data
          .filter((story: any) => story.user_id == this.viewingUserId)
          .map((story: any) => ({
            ...story,
            story_status: story.story_status, 
            statusText: story.story_status === 1 ? 'Published' : 'Draft', 
            story_image: story.story_image 
              ? `${story.story_image.replace(/\\/g, '/')}`
              : null,
            views: parseInt(story.views) || 0
          }));
        console.log('Processed stories with status:', this.stories);
      } else {
        this.stories = [];
        this.errorMessage = 'No stories found';
      }
    },
    error: (err) => {
      this.isLoading = false;
      this.stories = [];
      this.errorMessage = 'Failed to load stories. Please try again.';
      console.error('Error loading stories:', err);
    }
  });
}



  // ------------------------------------------------------------
  // User detail (current logged-in user)
  // ------------------------------------------------------------
  fetchUserDetail() {
    const userId = this.authService.getCurrentUserId();
  
  if (!userId) { this.router.navigate(['login']); return; }
    this.http.get<{ status: string, data: any[] }>(
      `${this.storyImgPath}/getuserdetail.php`,
      { withCredentials: true }
    ).subscribe({
      next: (res) => {
        if (res.status === 'success') {
          const matchedUser = res.data.find(u => u.id == userId);
          if (matchedUser) {
            this.userDetail = this.applyUserImageUrls(matchedUser);
            this.fetchFollowData(this.userDetail.id);
          } else {
            this.errorMessage = 'User not found';
          }
        } else {
          this.errorMessage = 'Failed to load user';
        }
      },
      error: () => {
        this.errorMessage = 'Error fetching user info';
      }
    });
  }

  // ------------------------------------------------------------
  // Follow data (followers + following)
  // ------------------------------------------------------------
  fetchFollowData(profileUserId?: string | number) {
   

    const loggedInUserId = this.authService.getCurrentUserId();
  
  if (!loggedInUserId) { this.router.navigate(['login']); return; }


    const pid = profileUserId ?? loggedInUserId;

    this.http.post<any>(
      `${this.storyImgPath}/follow/check_follow.php`,
      { follower_id: loggedInUserId, following_id: pid },
      { withCredentials: true }
    ).subscribe({
      next: (res) => {
        if (res.status === 'success') {
          this.followingList = res.followingList || [];
          this.followersList = res.followersList || [];
          this.followingCount = res.followingCount ?? this.followingList.length;
          this.followerCount = res.followerCount ?? this.followersList.length;
        } else {
          console.warn('Follow API error:', res.message);
        }
      },
      error: (err) => {
        console.error('Error loading follow data', err);
      }
    });
  }

  // ------------------------------------------------------------
  // Upload handlers
  // ------------------------------------------------------------
  onProfileSelected(e: Event) {
    const input = e.target as HTMLInputElement;
    const file = input.files?.[0];
    if (!file) return;
    this.uploadImage(file, 'profileimg');
    input.value = ''; // reset so same file can be reselected
  }

  onCoverSelected(e: Event) {
    const input = e.target as HTMLInputElement;
    const file = input.files?.[0];
    if (!file) return;
    this.uploadImage(file, 'coverimage');
    input.value = '';
  }

  private uploadImage(file: File, type: 'profileimg' | 'coverimage') {
  const userId = this.authService.getCurrentUserId();
  if (!userId) return;

  if (type === 'profileimg') this.uploadingProfile = true;
  if (type === 'coverimage') this.uploadingCover = true;

  const fd = new FormData();
  // endpoints handled in signup.php (upload_profileimg / upload_coverimage flags)
  if (type === 'profileimg') {
    fd.append('upload_profileimg', '1');
  } else {
    fd.append('upload_coverimage', '1');
  }

  fd.append('user_id', userId.toString()); // ✅ FIXED LINE
  fd.append('file', file);

  this.http.post<any>(`${this.storyImgPath}/signup.php`, fd, { withCredentials: true })
    .subscribe({
      next: (res) => {
        if (type === 'profileimg') this.uploadingProfile = false;
        if (type === 'coverimage') this.uploadingCover = false;

        if (res.status === 'success') {
          // update UI without full reload
          if (!this.userDetail) this.userDetail = {};
          if (type === 'profileimg') {
            this.userDetail.profileimg = res.path ?? res.filename ?? '';
            this.userDetail.profileimg_url = res.url ?? res.file_url ?? '';
          } else {
            this.userDetail.coverimage = res.path ?? res.filename ?? '';
            this.userDetail.coverimage_url = res.url ?? res.file_url ?? '';
          }
        } else {
          alert(res.message || 'Image upload failed');
        }
      },
      error: (err) => {
        if (type === 'profileimg') this.uploadingProfile = false;
        if (type === 'coverimage') this.uploadingCover = false;
        console.error(`${type} upload error`, err);
        alert('Image upload error');
      }
    });
}

  // ------------------------------------------------------------
  // Misc utils
  // ------------------------------------------------------------
  slugify(text: string): string {
    return text
      .toLowerCase()
      .trim()
      .replace(/[\s\W-]+/g, '-')
      .replace(/^-+|-+$/g, '');
  }

  getJoinedMonthYear(dateString: string): string {
    if (!dateString) return '';
    const date = new Date(dateString.replace(' ', 'T'));
    const options: Intl.DateTimeFormatOptions = { month: 'long', year: 'numeric' };
    return isNaN(date.getTime()) ? 'Invalid Date' : date.toLocaleDateString('en-US', options);
  }
editStory(storyId: number) {
  this.router.navigate(['/update', storyId]);
}
NewEp(storyId: number) {
  this.router.navigate(['/creat', storyId]);
}
getTimeAgo(dateString: string): string {
  if (!dateString) return '';

  // Convert to ISO format
  const parsedDate = new Date(dateString.replace(' ', 'T'));

  if (isNaN(parsedDate.getTime())) return 'Invalid date';

  const now = new Date();
  const diffInSeconds = Math.floor((now.getTime() - parsedDate.getTime()) / 1000);

  if (diffInSeconds < 0) return 'Just now';

  const intervals = [
    { label: 'year', seconds: 31536000 },
    { label: 'month', seconds: 2592000 },
    { label: 'week', seconds: 604800 },
    { label: 'day', seconds: 86400 },
    { label: 'hour', seconds: 3600 },
    { label: 'minute', seconds: 60 },
    { label: 'second', seconds: 1 }
  ];

  for (const interval of intervals) {
    const count = Math.floor(diffInSeconds / interval.seconds);
    if (count >= 1) {
      return `${count} ${interval.label}${count > 1 ? 's' : ''} ago`;
    }
  }

  return 'Just now';
}
getValidDate(story: any): string {
  return story.updated_at || story.updated || story.story_created_at || story.author_created_at || '';
}
groupCategories(list: any[], chunkSize: number): any[][] {
    const result: any[][] = [];
    for (let i = 0; i < list.length; i += chunkSize) {
      result.push(list.slice(i, i + chunkSize));
    }
    return result;
  }
 getCategory() {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      
    });
    this.http.get<any>('https://infoways.in/funtelapi/category.php', { headers: headers, withCredentials: true }).subscribe({
      next: (res) => {
        if (res.status === 'success') {
          this.categories = res.data;
          
        }
      },
      error: (err) => {
        console.error('Failed to fetch categories:', err);
      }
    });
  }

}
