import { CommonModule } from '@angular/common';
import { Component, HostListener, OnInit, Renderer2 } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router, RouterModule } from '@angular/router';
import { AllapiService } from '../allapi.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { filter, Subject, takeUntil } from 'rxjs';
import { AuthService } from '../auth.service';
import { map, take } from 'rxjs/operators';
import { TranslationService } from '../translation.service';
import { LanguageService } from '../language.service';

@Component({
  selector: 'app-header',
  standalone: true,
  imports: [CommonModule, FormsModule, RouterModule],
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
  isLoggedIn: boolean = false;
  mobileMenuOpen = false;
  activeDropdown: string | null = null;
  isBrowseMenuOpen = false;
  isBrowseWriteMenuOpen = false;
  isDarkMode = true;
  mobileMenuActive = false;
  searchOverlayActive = false;
  categoryColumns: any[][] = [];
  selectedLanguage: string = 'en';
  userName: string = '';
  searchText = '';
  allStories: any[] = [];
  filteredSuggestions: any[] = [];
  private destroy$ = new Subject<void>();
  mobileActiveDropdown: string | null = null;

  profileImagePath = 'https://infoways.in/funtelapi/';
  currentUser: any = null;
  profileImageUrl: string | null = null;
  showLoginRedirectMessage: boolean = false;

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

  ngOnInit(): void {
    // Current language set karein
    this.selectedLanguage = this.languageService.getCurrentLanguage();
    
    // Language changes subscribe karein
    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;
      } else {
        this.userName = '';
        this.profileImageUrl = null;
      }
    });

    this.getCategory();
    this.checkLoginStatus();
    this.loadAllStories();
    this.setInitialTheme();

    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd)
    ).subscribe(() => {
      const currentRoute = this.router.url.split('?')[0];
      if (this.isLoggedIn && currentRoute === '/login') {
        this.showLoginRedirectMessage = true;
      }
    });
  }

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

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }

  // Language change handler
  changeLanguage(event: Event): void {
    const target = event.target as HTMLSelectElement;
    const newLanguage = target.value;
    
    console.log('Changing language to:', newLanguage);
    
    // Language service ko update karein
    this.languageService.setLanguage(newLanguage);
    
    // Local state update karein
    this.selectedLanguage = newLanguage;
    
    // Dropdown close karein (optional)
    this.activeDropdown = null;
    this.mobileActiveDropdown = null;
    
    // Page refresh karein taaki nayi language load ho
    setTimeout(() => {
      window.location.reload();
    }, 100);
  }

  // Baaki methods same rahenge...
  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' && Array.isArray(res.data)) {
          const grouped = this.groupCategories(res.data, 5);
          this.categoryColumns = grouped;
        }
      },
      error: (err) => {
        console.error('Failed to fetch categories:', err);
      }
    });
  }

  toggleBrowseMenu() {
    this.isBrowseMenuOpen = !this.isBrowseMenuOpen;
  }

  toggleBrowseWriteMenu() {
    this.isBrowseWriteMenuOpen = !this.isBrowseWriteMenuOpen;
  }

  @HostListener('document:click', ['$event'])
  onDocumentClick(event: MouseEvent) {
    const target = event.target as HTMLElement;
    const clickedInsideDropdown = target.closest('.browse-dropdown') ||
      target.closest('.write-dropdown') ||
      target.closest('.user-dropdown') ||
      target.closest('.language-selector');
    if (!clickedInsideDropdown) {
      this.activeDropdown = null;
    }
  }

  private setInitialTheme(): void {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme === 'light') {
      this.isDarkMode = false;
      this.renderer.removeClass(document.documentElement, 'dark');
    } else {
      this.isDarkMode = true;
      this.renderer.addClass(document.documentElement, 'dark');
      localStorage.setItem('theme', 'dark');
    }
  }

  toggleDropdown(name: string): void {
    this.activeDropdown = this.activeDropdown === name ? null : name;
  }

  closeDropdowns() {
    this.activeDropdown = null;
  }

  homePage() {
    this.router.navigate(['']);
  }

  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;
          this.userName = '';
        }
      },
      error: () => {
        this.isLoggedIn = false;
        this.userName = '';
      }
    });
  }

  loadAllStories() {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });
    this.http.get<any>('https://infoways.in/funtelapi/allstory.php', { headers, withCredentials: true }).subscribe({
      next: (res) => {
        this.allStories = res.data || [];
      },
      error: () => {
        this.allStories = [];
      }
    });
  }

  logout() {
    this.authService.logout().subscribe({
      next: () => {
        this.isLoggedIn = false;
        this.userName = '';
        this.currentUser = null;
        this.router.navigate(['/login']);
      },
      error: (err) => {
        console.error('Logout Error:', err);
        this.isLoggedIn = false;
        this.userName = '';
        this.currentUser = null;
        this.router.navigate(['/login']);
      }
    });
  }

  toggleMobileMenu(): void {
    this.mobileMenuActive = !this.mobileMenuActive;
    if (!this.mobileMenuActive) {
      this.mobileActiveDropdown = null;
    }
  }

  toggleSearchOverlay(): void {
    this.searchOverlayActive = !this.searchOverlayActive;
  }

  toggleTheme(): void {
    this.isDarkMode = !this.isDarkMode;
    if (this.isDarkMode) {
      this.renderer.addClass(document.documentElement, 'dark');
      localStorage.setItem('theme', 'dark');
    } else {
      this.renderer.removeClass(document.documentElement, 'dark');
      localStorage.setItem('theme', 'light');
    }
  }

  navigateToMyWorks() {
    this.authService.currentUser$.pipe(take(1)).subscribe(user => {
      if (user?.id) {
        this.router.navigate(['/myworks']);
        console.log('myworks');
      } else {
        this.router.navigate(['/login']);
        console.log('login');
      }
    });
  }

  createNewStory() {
    this.router.navigate(['new']);
  }

  onSearchInput() {
    const text = this.searchText.toLowerCase().trim();
    this.filteredSuggestions = this.allStories.filter(story =>
      story.story_title.toLowerCase().includes(text)
    ).slice(0, 5);
  }

  selectSuggestion(suggestion: any) {
    this.searchText = suggestion.story_title;
    this.filteredSuggestions = [];
    const slug = this.slugify(suggestion.story_title);
    this.router.navigate(['/story', `${suggestion.id}-${slug}`]);
  }

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

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

  toggleMobileDropdown(name: string): void {
    this.mobileActiveDropdown = this.mobileActiveDropdown === name ? null : name;
  }
}