import { CommonModule } from '@angular/common';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { HeaderComponent } from '../header/header.component';
import { AuthService } from '../auth.service';
import { slugify as translitSlug } from 'transliteration';
import { LanguageService } from '../language.service';
import { TranslationService } from '../translation.service';

@Component({
  selector: 'app-search-result',
  standalone: true,
  imports: [CommonModule, HeaderComponent],
  templateUrl: './search-result.component.html',
  styleUrl: './search-result.component.css'
})
export class SearchResultComponent {
  isLoggedIn: boolean = false;
  stories: any[] = [];
  categoryId: string | null = null;
  filteredSuggestions: any[] = [];
  isLoading = true;
  errorMessage = '';
  searchText: string = '';
  relatedStories: any[] = [];
  userProgress: any[] = [];
  categoryName: string = '';
  selectedLanguage: string = 'en';
  userId: number | null = null;
  displayCount: number = 1;
  visibleHistoryCount: number = 5;
  storyImgPath = 'https://infoways.in/funtelapi';

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

  ngOnInit(): void {
    this.selectedLanguage = this.languageService.getCurrentLanguage();
    
    // ✅ Language changes subscribe karein
    this.languageService.currentLanguage$.subscribe(lang => {
      this.selectedLanguage = lang;
      this.refreshData(); // Language change pe data refresh karein
    });

    const userId = this.authService.getCurrentUserId();
    if (userId) {
      this.userId = +userId;
    }

    this.route.paramMap.subscribe(params => {
      this.resetComponentState();
      this.categoryId = params.get('id');
      const searchText = this.route.snapshot.queryParamMap.get('q');
      
      if (searchText) {
        this.fetchSearchResults(searchText);
        this.loadUserStoryProgress();
      } else if (this.categoryId) {
        this.fetchCategoryStories(this.categoryId);
        this.loadUserStoryProgress();
        this.loadCategoryName(this.categoryId);
      }
    });
  }

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

  private getHeaders(): HttpHeaders {
    return new HttpHeaders({
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    });
  }

  resetComponentState() {
    this.stories = [];
    this.relatedStories = [];
    this.categoryName = '';
    this.errorMessage = '';
    this.isLoading = true;
  }

 
  filterStoriesByLanguage(stories: any[]): any[] {
    if (!stories) return [];
    
    return stories.filter(story => {
      
      if (!story.language) return true;
      
     
      const storyLangCode = this.languageService.getCodeFromDBValue(story.language);
      return storyLangCode === this.selectedLanguage;
    });
  }


  refreshData() {
    const searchText = this.route.snapshot.queryParamMap.get('q');
    
    if (searchText) {
      this.fetchSearchResults(searchText);
    } else if (this.categoryId) {
      this.fetchCategoryStories(this.categoryId);
    }
  }

  loadCategoryName(categoryId: string) {
    this.http.get<any>(`https://infoways.in/funtelapi/category.php?id=${categoryId}`, {
      headers: this.getHeaders()
    }).subscribe({
      next: (res) => {
        if (res.status === 'success' && res.data?.length > 0) {
          const match = res.data.find((cat: any) => cat.id.toString() === categoryId);
          this.categoryName = match?.categoryName || 'Category';
        }
      },
      error: (err) => {
        console.error('Failed to load category name', err);
      }
    });
  }

  loadMoreHistory() {
    if (this.visibleHistoryCount < this.userProgress.length) {
      this.visibleHistoryCount += 5;
    }
  }

  fetchSearchResults(query: string) {
    this.searchText = query;
    this.isLoading = true;
    
    // Database ke liye language value use karein
    const dbLanguage = this.languageService.getCurrentLanguageForDB();
    const langParam = this.selectedLanguage !== 'en' ? `&language=${dbLanguage}` : '';
    
    this.http.get<any>(`https://infoways.in/funtelapi/allstory.php?q=${encodeURIComponent(query)}${langParam}`, {
      headers: this.getHeaders()
    }).subscribe({
      next: (res) => {
        if (res.status === 'success') {
          // Language ke hisaab se filter karein
          this.stories = this.filterStoriesByLanguage(res.data);
          this.relatedStories = this.getRandomRelatedStories(this.stories, 3);
        } else {
          this.errorMessage = res.message || 'No matching stories found.';
        }
        this.isLoading = false;
      },
      error: (err) => {
        this.errorMessage = 'Failed to load search results.';
        this.isLoading = false;
        console.error('Search error:', err);
      }
    });
  }

  onSearchSubmit(event: Event) {
    event.preventDefault();
    const query = this.searchText.trim();
    if (query) {
      this.filteredSuggestions = [];
      this.router.navigate(['/search'], { queryParams: { q: query } });
    }
  }

  fetchCategoryStories(categoryId: string) {
    this.isLoading = true;
    
    // Database ke liye language value use karein
    const dbLanguage = this.languageService.getCurrentLanguageForDB();
    const langParam = this.selectedLanguage !== 'en' ? `&language=${dbLanguage}` : '';
    
    this.http.get<any>(`https://infoways.in/funtelapi/allstory.php?category_id=${categoryId}${langParam}`, {
      headers: this.getHeaders()
    }).subscribe({
      next: (res) => {
        if (res.status === 'success') {
          // Language ke hisaab se filter karein
          this.stories = this.filterStoriesByLanguage(res.data);
          this.relatedStories = this.getRandomRelatedStories(this.stories, 3);
        } else {
          this.errorMessage = res.message || 'No stories found.';
        }
        this.isLoading = false;
      },
      error: (err) => {
        this.errorMessage = 'Failed to load category stories.';
        this.isLoading = false;
        console.error('Category error:', err);
      }
    });
  }

  formatDate(dateStr: string): string {
    const date = new Date(dateStr);
    return isNaN(date.getTime()) ? '' : date.toDateString();
  }

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

  slugify(text: string): string {
    let slug = translitSlug(text, { lowercase: true, separator: '-' });
    if (!slug || slug.trim() === '') {
      slug = text.toLowerCase().replace(/\s+/g, '-');
    }
    return slug;
  }

  getRandomRelatedStories(allStories: any[], count: number): any[] {
    const shuffled = [...allStories].sort(() => 0.5 - Math.random());
    return shuffled.slice(0, count);
  }

  resumeReading(storyId: number, title: string) {
    const slug = title.toLowerCase().replace(/\s+/g, '-');
    this.router.navigate(['/series', `${storyId}-${slug}`]);
  }

  loadUserStoryProgress() {
    const userId = sessionStorage.getItem('userId');
    const key = `story_progress_${userId}`;
    const data = localStorage.getItem(key);

    if (data) {
      const progress = JSON.parse(data);
      const entries = Object.entries(progress);

      this.userProgress = [];

      for (const [storyId, entry] of Object.entries(progress) as [string, {
        lastReadPartId: number;
        readParts: number[];
        totalParts: number;
        lastPartTitle: string;
        timestamp: number;
        author_name: string;
      }][]) {
        const percent = Math.round((entry.readParts.length / entry.totalParts) * 100);
        const headers = new HttpHeaders({
          'Content-Type': 'application/json'
        });
        
        this.http.get<any>(`https://infoways.in/funtelapi/allstory.php?id=${storyId}`, {
          headers: headers,
          withCredentials: true
        }).subscribe({
          next: (res) => {
            if (res.status === 'success' && res.data?.length) {
              const storyData = res.data.find((story: any) => story.id == +storyId);
              
              // ✅ Progress stories ko bhi language ke hisaab se filter karein
              if (this.shouldShowProgressStory(storyData)) {
                this.userProgress.push({
                  storyId,
                  title: entry.lastPartTitle,
                  lastReadPartId: entry.lastReadPartId,
                  percent,
                  part: entry.readParts.length,
                  total: entry.totalParts,
                  timestamp: entry.timestamp,
                  image: `${this.storyImgPath}/${storyData.story_image}`,
                  name: storyData.author_name,
                });

                this.userProgress.sort((a, b) => b.timestamp - a.timestamp);
              }
            }
          },
          error: (err) => {
            console.error('Error loading story progress:', err);
          }
        });
      }
    }
  }

  // ✅ Progress stories ko language ke hisaab se filter karein
  shouldShowProgressStory(storyData: any): boolean {
    if (!storyData.language) return true;
    
    const storyLangCode = this.languageService.getCodeFromDBValue(storyData.language);
    return storyLangCode === this.selectedLanguage;
  }

  clearHistory() {
    const userId = sessionStorage.getItem('userId');
    const key = `story_progress_${userId}`;
    localStorage.removeItem(key);
    location.reload();
  }

  formatCount(num: number): string {
    if (num >= 1_000_000) return (num / 1_000_000).toFixed(1) + 'M';
    if (num >= 1_000) return (num / 1_000).toFixed(1) + 'K';
    return num.toString();
  }
}