import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { HeaderComponent } from '../header/header.component';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ActivatedRoute, Router } from '@angular/router';
import { CommonModule } from '@angular/common';



@Component({
  selector: 'app-authorprofile',
  standalone: true,
  imports: [HeaderComponent, CommonModule],
  templateUrl: './authorprofile.component.html',
  styleUrl: './authorprofile.component.css'
})
export class AuthorprofileComponent {
activeTab: string = 'stories';
  stories: any[] = [];
  isLoading = true;
  errorMessage = '';
  deleteMessage = '';

  storyImgPath = 'https://infoways.in/funtelapi/'; // base API root (HTTPS)

  storyId: number | null = null;
  storyDetail: any = null;
  userDetail: any = null;

  followersList: any[] = [];
  followingList: any[] = [];
  followerCount = 0;
  followingCount = 0;

  uploadingProfile = false;
  uploadingCover = false;

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

  constructor(
    private http: HttpClient,
    private router: Router,
    private route: ActivatedRoute
  ) {}

  // ------------------------------------------------------------
  // Lifecycle
  // ------------------------------------------------------------
  ngOnInit(): void {
  this.route.paramMap.subscribe(params => {
    const id = params.get('id');
    if (id) {
      this.loadAuthorData(id);
    }
  });


    this.fetchStoryDetail();
    this.fetchUserDetail(); // follow data loaded after user fetched

    this.route.paramMap.subscribe(params => {
      const param = params.get('idAndTitle');
      if (param) {
        const id = param.split('-')[0];
        this.storyId = Number(id);
        this.fetchStoryDetail();
      }
      this.fetchStories(); // always call
    });
  }

  loadAuthorData(id: string): void {
  this.http.get<any>(`https://infoways.in/funtelapi/userinfo.php?id=${id}`).subscribe({
    next: (res) => {
      if (res.status === 'success') {
        this.userDetail = res.data;
      } else {
        console.error('Author not found');
      }
    },
    error: (err) => {
      console.error('API Error:', err);
    }
  });
}
  // ------------------------------------------------------------
  // 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();
  }

  // ------------------------------------------------------------
  // Delete story
  // ------------------------------------------------------------
  deleteStory(storyId: number): Promise<boolean> {
    return new Promise((resolve, reject) => {
      const userId = sessionStorage.getItem('userId');
      if (!userId) {
        this.router.navigate(['/login']);
        reject('User not authenticated');
        return;
      }

      const headers = new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${sessionStorage.getItem('userId')}`
      });

      this.http.post(
        `${this.storyImgPath}/allstory.php`,
        JSON.stringify({ story_id: storyId, user_id: userId }),
        { headers, withCredentials: true }
      ).subscribe({
        next: (response: any) => {
          if (response.status === 'success') {
            this.deleteMessage = 'Story deleted successfully';
            setTimeout(() => {
              this.deleteMessage = '';
              window.scrollTo(0, 0);
              location.reload();
            }, 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 = sessionStorage.getItem('userId');
    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',
      'Authorization': `Bearer ${sessionStorage.getItem('token') || ''}`
    });

    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;
      }
    });
  }

  // ------------------------------------------------------------
  // 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}`]);
  }

  // ------------------------------------------------------------
  // Story detail
  // ------------------------------------------------------------
  fetchStoryDetail() {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${sessionStorage.getItem('token') || ''}`
    });

    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.';
      }
    });
  }

  // ------------------------------------------------------------
  // User detail (current logged-in user)
  // ------------------------------------------------------------
  fetchUserDetail() {
    const userId = sessionStorage.getItem('userId');
    if (!userId) 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 = sessionStorage.getItem('userId');
    if (!loggedInUserId) 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 = sessionStorage.getItem('userId') || '';
    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);
    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);
  }
}
