import { Component, inject, computed, OnInit, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router, RouterModule } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Store } from '@ngrx/store';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { ButtonModule } from 'primeng/button';
import { ProgressSpinnerModule } from 'primeng/progressspinner';
import { ChartModule } from 'primeng/chart';
import { forkJoin } from 'rxjs';
import {
  DashboardActions,
  selectDashboardStats,
  selectDashboardCompany,
  selectDashboardLoading,
  selectDashboardError,
} from '../../core/store';
import { PermissionService } from '../../core/services/permission.service';
import { selectUser } from '../../core/store/auth/auth.reducer';
import { environment } from '../../../environments/environment';

@Component({
  selector: 'app-dashboard',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    TranslateModule,
    ButtonModule,
    ProgressSpinnerModule,
    ChartModule,
  ],
  templateUrl: './dashboard.component.html',
  styleUrl: './dashboard.component.scss',
})
export class DashboardComponent implements OnInit {
  private store = inject(Store);
  private http = inject(HttpClient);
  private router = inject(Router);
  private translate = inject(TranslateService);
  permissionService = inject(PermissionService);
  showSetupBanner = signal(false);

  stats$ = this.store.select(selectDashboardStats);
  company$ = this.store.select(selectDashboardCompany);
  loading$ = this.store.select(selectDashboardLoading);
  error$ = this.store.select(selectDashboardError);
  user = this.store.selectSignal(selectUser);

  private allQuickActions = [
    { icon: 'pi pi-book', label: 'DASHBOARD.NEW_ENTRY', route: '/accounting/journal-entries', permissions: ['accounting.journal-entries'], color: '#6366f1' },
    { icon: 'pi pi-sitemap', label: 'DASHBOARD.VIEW_ACCOUNTS', route: '/accounting/accounts', permissions: ['accounting.accounts'], color: '#10b981' },
    { icon: 'pi pi-users', label: 'DASHBOARD.VIEW_PARTNERS', route: '/core/partners', permissions: ['sales.', 'purchasing.', 'inventory.products'], color: '#f59e0b' },
    { icon: 'pi pi-wallet', label: 'DASHBOARD.BANK_ACCOUNTS', route: '/accounting/bank-accounts', permissions: ['accounting.'], color: '#3b82f6' },
    { icon: 'pi pi-calendar', label: 'DASHBOARD.FISCAL_YEARS', route: '/accounting/fiscal-years', permissions: ['accounting.fiscal-years'], color: '#ef4444' },
    { icon: 'pi pi-chart-bar', label: 'DASHBOARD.REPORTS', route: '/accounting/reports', permissions: ['reports', 'accounting.'], color: '#8b5cf6' },
  ];

  quickActions = computed(() =>
    this.allQuickActions.filter(a => this.permissionService.hasAnyPermission(a.permissions))
  );

  showCompanyLink = computed(() => this.permissionService.hasPermission('core.company'));
  showCharts = computed(() => this.permissionService.hasAnyPermission(['accounting.']));
  showSalesSection = computed(() => this.permissionService.hasAnyPermission(['sales.']));
  showPosSection = computed(() => this.permissionService.hasAnyPermission(['pos.']));
  showSupportSection = computed(() => this.permissionService.hasAnyPermission(['support.']));

  // Chart data
  accountChartData = signal<any>(null);
  accountChartOptions: any = {
    plugins: {
      legend: { position: 'bottom', labels: { padding: 16, usePointStyle: true, pointStyle: 'circle', font: { size: 12 } } },
    },
    responsive: true,
    maintainAspectRatio: false,
    cutout: '65%',
  };

  entryChartData = signal<any>(null);
  entryChartOptions: any = {
    plugins: {
      legend: { display: false },
    },
    responsive: true,
    maintainAspectRatio: false,
    scales: {
      x: { grid: { display: false }, ticks: { font: { size: 11 } } },
      y: { beginAtZero: true, grid: { color: 'rgba(0,0,0,0.04)' }, ticks: { font: { size: 11 } } },
    },
  };

  recentEntries = signal<any[]>([]);
  today = new Date();

  ngOnInit(): void {
    this.store.dispatch(DashboardActions.loadDashboard());
    if (this.permissionService.hasAnyPermission(['accounting.'])) {
      this.loadChartData();
    }
    this.checkSetupNeeded();
  }

  private checkSetupNeeded(): void {
    this.stats$.subscribe((stats) => {
      if (stats && stats.accounts_count === 0) {
        // Auto-redirect to setup wizard if no accounts exist
        this.router.navigate(['/setup']);
      } else if (stats && stats.accounts_count > 0 && stats.accounts_count <= 5) {
        // Show banner if only root headers exist
        this.showSetupBanner.set(true);
      }
    });
  }

  goToSetup(): void {
    this.router.navigate(['/setup']);
  }

  retry(): void {
    this.store.dispatch(DashboardActions.loadDashboard());
    this.loadChartData();
  }

  private loadChartData(): void {
    const apiUrl = environment.apiUrl;

    // Fetch accounts for classification chart + recent journal entries
    forkJoin({
      accounts1: this.http.get<any>(`${apiUrl}/accounting/accounts?page=1`),
      accounts2: this.http.get<any>(`${apiUrl}/accounting/accounts?page=2`),
      accounts3: this.http.get<any>(`${apiUrl}/accounting/accounts?page=3`),
      entries: this.http.get<any>(`${apiUrl}/accounting/journal-entries?page=1`),
    }).subscribe({
      next: ({ accounts1, accounts2, accounts3, entries }) => {
        const allAccounts = [
          ...(accounts1.data || []),
          ...(accounts2.data || []),
          ...(accounts3.data || []),
        ];

        // Build account classification chart
        const classifications: Record<string, number> = {};
        for (const acc of allAccounts) {
          const cls = acc.classification || 'other';
          classifications[cls] = (classifications[cls] || 0) + 1;
        }

        const classLabels: Record<string, string> = {
          assets: this.translate.instant('DASHBOARD.CHART_ASSETS'),
          liabilities: this.translate.instant('DASHBOARD.CHART_LIABILITIES'),
          equity: this.translate.instant('DASHBOARD.CHART_EQUITY'),
          revenue: this.translate.instant('DASHBOARD.CHART_REVENUE'),
          expenses: this.translate.instant('DASHBOARD.CHART_EXPENSES'),
        };

        const classColors: Record<string, string> = {
          assets: '#3b82f6',
          liabilities: '#ef4444',
          equity: '#8b5cf6',
          revenue: '#10b981',
          expenses: '#f59e0b',
        };

        const labels = Object.keys(classifications).map(k => classLabels[k] || k);
        const data = Object.values(classifications);
        const colors = Object.keys(classifications).map(k => classColors[k] || '#64748b');

        this.accountChartData.set({
          labels,
          datasets: [{
            data,
            backgroundColor: colors,
            hoverBackgroundColor: colors.map(c => c + 'dd'),
            borderWidth: 0,
          }],
        });

        // Build monthly entries bar chart
        const monthlyData = this.buildMonthlyData(entries.data || []);
        this.entryChartData.set(monthlyData);

        // Recent entries
        this.recentEntries.set((entries.data || []).slice(0, 5));
      },
      error: () => {},
    });
  }

  private buildMonthlyData(entries: any[]): any {
    const months: Record<string, { debit: number; credit: number }> = {};
    const now = new Date();

    // Initialize last 6 months
    for (let i = 5; i >= 0; i--) {
      const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
      const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
      months[key] = { debit: 0, credit: 0 };
    }

    for (const entry of entries) {
      if (!entry.date) continue;
      const key = entry.date.substring(0, 7); // YYYY-MM
      if (months[key]) {
        months[key].debit += parseFloat(entry.total_debit || 0);
        months[key].credit += parseFloat(entry.total_credit || 0);
      }
    }

    const monthNames = Object.keys(months).map(k => {
      const [y, m] = k.split('-');
      const d = new Date(parseInt(y), parseInt(m) - 1);
      return d.toLocaleDateString(this.translate.currentLang === 'ar' ? 'ar-EG' : 'en-US', { month: 'short' });
    });

    return {
      labels: monthNames,
      datasets: [
        {
          label: this.translate.instant('DASHBOARD.CHART_DEBIT'),
          data: Object.values(months).map(m => m.debit),
          backgroundColor: 'rgba(59,130,246,0.8)',
          borderRadius: 6,
          barPercentage: 0.6,
        },
        {
          label: this.translate.instant('DASHBOARD.CHART_CREDIT'),
          data: Object.values(months).map(m => m.credit),
          backgroundColor: 'rgba(16,185,129,0.8)',
          borderRadius: 6,
          barPercentage: 0.6,
        },
      ],
    };
  }

  getStatusColor(status: string): string {
    switch (status) {
      case 'posted': return '#10b981';
      case 'draft': return '#f59e0b';
      case 'cancelled': return '#ef4444';
      default: return '#64748b';
    }
  }

  getStatusBg(status: string): string {
    switch (status) {
      case 'posted': return 'rgba(16,185,129,0.1)';
      case 'draft': return 'rgba(245,158,11,0.1)';
      case 'cancelled': return 'rgba(239,68,68,0.1)';
      default: return 'rgba(100,116,139,0.1)';
    }
  }
}
