import { Component, inject, signal, computed, OnInit, DestroyRef } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { CommonModule } from '@angular/common';
import { RouterModule, Router } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { MatDividerModule } from '@angular/material/divider';
import { MatBadgeModule } from '@angular/material/badge';
import { MatTooltipModule } from '@angular/material/tooltip';
import { AuthService } from '../../core/services/auth.service';
import { DepartmentService } from '../../features/departments/services/department.service';

interface NavItem {
  label: string;
  icon: string;
  route: string;
  roles?: ('APPLICANT' | 'DEPARTMENT' | 'ADMIN')[];
  badge?: () => number;
}

@Component({
  selector: 'app-main-layout',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    MatButtonModule,
    MatIconModule,
    MatMenuModule,
    MatDividerModule,
    MatBadgeModule,
    MatTooltipModule,
  ],
  templateUrl: './main-layout.component.html',
  styleUrl: './main-layout.component.scss',
})
export class MainLayoutComponent implements OnInit {
  private readonly authService = inject(AuthService);
  private readonly departmentService = inject(DepartmentService);
  private readonly router = inject(Router);
  private readonly destroyRef = inject(DestroyRef);

  readonly sidenavOpened = signal(true);
  readonly currentUser = this.authService.currentUser$;
  readonly userType = this.authService.userType;

  // Enhanced department info fetched from API
  readonly departmentCode = signal<string | null>(null);
  readonly departmentName = signal<string | null>(null);
  readonly emblemLoaded = signal(true);
  readonly unreadNotifications = signal(3);
  readonly currentLanguage = signal<'en' | 'hi'>('en');
  readonly currentYear = new Date().getFullYear();
  readonly lastUpdated = new Date().toLocaleDateString('en-GB', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
  });

  // Pending approvals count for department badge
  private readonly pendingCount = signal(5);

  readonly navItems: NavItem[] = [
    { label: 'Dashboard', icon: 'dashboard', route: '/dashboard' },
    { label: 'My Requests', icon: 'description', route: '/requests', roles: ['APPLICANT'] },
    {
      label: 'Pending Approvals',
      icon: 'pending_actions',
      route: '/approvals',
      roles: ['DEPARTMENT'],
      badge: () => this.pendingCount(),
    },
    { label: 'All Requests', icon: 'list_alt', route: '/requests', roles: ['DEPARTMENT', 'ADMIN'] },
    { label: 'Departments', icon: 'business', route: '/departments', roles: ['ADMIN'] },
    { label: 'Workflows', icon: 'account_tree', route: '/workflows', roles: ['ADMIN'] },
    { label: 'Webhooks', icon: 'webhook', route: '/webhooks', roles: ['DEPARTMENT', 'ADMIN'] },
    { label: 'Audit Logs', icon: 'history', route: '/audit', roles: ['ADMIN'] },
  ];

  readonly visibleNavItems = computed(() => {
    const type = this.userType();
    return this.navItems.filter((item) => {
      if (!item.roles) return true;
      return type && item.roles.includes(type);
    });
  });

  ngOnInit(): void {
    this.loadDepartmentDetails();
  }

  /**
   * Fetch department details if user is a department and code is missing
   */
  private loadDepartmentDetails(): void {
    const user = this.authService.getCurrentUser();
    if (!user || user.type !== 'DEPARTMENT') return;

    // If we already have department code from login, use it
    if (user.departmentCode) {
      this.departmentCode.set(user.departmentCode);
      return;
    }

    // Fetch department details using the user's ID (which is the department ID)
    const deptId = user.departmentId || user.id;
    if (!deptId) return;

    this.departmentService.getDepartment(deptId)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe({
        next: (dept) => {
          this.departmentCode.set(dept.code);
          this.departmentName.set(dept.name);
        },
        error: () => {
          // Silently fail - we'll just not show the code
        },
      });
  }

  toggleSidenav(): void {
    this.sidenavOpened.update((v) => !v);
  }

  setLanguage(lang: 'en' | 'hi'): void {
    this.currentLanguage.set(lang);
    // In production, this would trigger i18n service to change language
    document.documentElement.lang = lang;
  }

  logout(): void {
    this.authService.logout();
  }

  getUserInitials(): string {
    const user = this.authService.getCurrentUser();
    if (!user?.name) return '?';
    const parts = user.name.split(' ');
    return parts
      .map((p) => p[0])
      .join('')
      .toUpperCase()
      .slice(0, 2);
  }

  getAvatarColor(): string {
    const type = this.userType();
    switch (type) {
      case 'ADMIN':
        return 'linear-gradient(135deg, #8B5CF6 0%, #6366F1 100%)';
      case 'DEPARTMENT':
        return 'linear-gradient(135deg, #1D0A69 0%, #2563EB 100%)';
      case 'APPLICANT':
        return 'linear-gradient(135deg, #10B981 0%, #06B6D4 100%)';
      default:
        return 'linear-gradient(135deg, #6B7280 0%, #9CA3AF 100%)';
    }
  }

  formatRole(role: string): string {
    switch (role) {
      case 'ADMIN':
        return 'Administrator';
      case 'DEPARTMENT':
        return 'Department Officer';
      case 'APPLICANT':
        return 'Citizen';
      default:
        return role;
    }
  }
}
