import { Component, Input, OnInit, OnChanges, SimpleChanges } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DashboardKPI, DashboardChart, DashboardTabConfig } from '../base-domain/base-domain.component';

@Component({
  selector: 'app-domain-dashboard',
  standalone: true,
  imports: [CommonModule],
  template: `
    <div class="domain-dashboard">
      <!-- Header -->
      <div class="dashboard-header">
        <h2 class="dashboard-title">
          <i class="fas fa-chart-bar"></i>
          {{ title }}
        </h2>
        <p class="dashboard-subtitle">Visão geral e métricas principais</p>
      </div>

      <!-- KPIs Grid -->
      <div class="kpis-grid" *ngIf="showKPIs && kpis.length > 0">
        <div 
          class="kpi-card" 
          *ngFor="let kpi of kpis"
          [ngClass]="'kpi-' + kpi.color">
          
          <div class="kpi-header">
            <div class="kpi-icon">
              <i [class]="kpi.icon"></i>
            </div>
            <div class="kpi-trend" *ngIf="kpi.trend">
              <i [class]="getTrendIcon(kpi.trend)" [ngClass]="'trend-' + kpi.trend"></i>
            </div>
          </div>
          
          <div class="kpi-content">
            <div class="kpi-value">{{ formatKPIValue(kpi.value) }}</div>
            <div class="kpi-label">{{ kpi.label }}</div>
            <div class="kpi-change" *ngIf="kpi.change">{{ kpi.change }}</div>
          </div>
        </div>
      </div>

      <!-- Charts Section -->
      <div class="charts-section" *ngIf="showCharts && charts.length > 0">
        <h3 class="section-title">
          <i class="fas fa-chart-line"></i>
          Gráficos
        </h3>
        <div class="charts-grid">
          <div class="chart-card" *ngFor="let chart of charts">
            <h4 class="chart-title">{{ chart.title }}</h4>
            <div class="chart-placeholder">
              <i class="fas fa-chart-{{ chart.type }}"></i>
              <p>Gráfico {{ chart.type }} - {{ chart.title }}</p>
              <small>{{ chart.data.length }} registros</small>
            </div>
          </div>
        </div>
      </div>

      <!-- Recent Items -->
      <div class="recent-items-section" *ngIf="showRecentItems && recentItems.length > 0">
        <h3 class="section-title">
          <i class="fas fa-clock"></i>
          Itens Recentes
        </h3>
        <div class="recent-items-list">
          <div class="recent-item" *ngFor="let item of recentItems">
            <div class="item-info">
              <div class="item-name">{{ getItemName(item) }}</div>
              <div class="item-details">{{ getItemDetails(item) }}</div>
            </div>
            <div class="item-date">{{ formatDate(item.created_at || item.updated_at) }}</div>
          </div>
        </div>
      </div>

      <!-- Empty State -->
      <div class="empty-state" *ngIf="!hasContent()">
        <i class="fas fa-chart-bar empty-icon"></i>
        <h3>Dashboard em Construção</h3>
        <p>Configure KPIs e gráficos para visualizar métricas importantes.</p>
      </div>
    </div>
  `,
  styles: [`
    .domain-dashboard {
      padding: 24px;
      background: var(--background);
      min-height: 100%;
    }

    .dashboard-header {
      margin-bottom: 32px;
      text-align: center;
    }

    .dashboard-title {
      margin: 0 0 8px 0;
      font-size: 28px;
      font-weight: 600;
      color: var(--text-primary);
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 12px;

      i {
        color: var(--idt-primary-color);
      }
    }

    .dashboard-subtitle {
      margin: 0;
      color: var(--text-secondary);
      font-size: 16px;
    }

    /* KPIs Grid */
    .kpis-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
      gap: 24px;
      margin-bottom: 40px;
    }

    .kpi-card {
      background: var(--surface);
      border: 1px solid var(--divider);
      border-radius: 12px;
      padding: 24px;
      transition: all 0.3s ease;
      position: relative;
      overflow: hidden;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
      }

      &.kpi-primary { border-left: 4px solid var(--idt-primary-color); }
      &.kpi-success { border-left: 4px solid var(--idt-success); }
      &.kpi-warning { border-left: 4px solid var(--idt-warning); }
      &.kpi-danger { border-left: 4px solid var(--idt-danger); }
      &.kpi-info { border-left: 4px solid var(--idt-info); }
    }

    .kpi-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
    }

    .kpi-icon {
      width: 48px;
      height: 48px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(var(--idt-primary-rgb), 0.1);

      i {
        font-size: 20px;
        color: var(--idt-primary-color);
      }
    }

    .kpi-trend {
      i {
        font-size: 16px;
        
        &.trend-up { color: var(--idt-success); }
        &.trend-down { color: var(--idt-danger); }
        &.trend-stable { color: var(--idt-warning); }
      }
    }

    .kpi-content {
      .kpi-value {
        font-size: 32px;
        font-weight: 700;
        color: var(--text-primary);
        margin-bottom: 4px;
      }

      .kpi-label {
        font-size: 14px;
        color: var(--text-secondary);
        margin-bottom: 8px;
      }

      .kpi-change {
        font-size: 12px;
        color: var(--idt-success);
        font-weight: 600;
      }
    }

    /* Charts Section */
    .charts-section {
      margin-bottom: 40px;
    }

    .section-title {
      display: flex;
      align-items: center;
      gap: 12px;
      font-size: 20px;
      font-weight: 600;
      color: var(--text-primary);
      margin-bottom: 24px;
      padding-bottom: 8px;
      border-bottom: 2px solid var(--divider);

      i {
        color: var(--idt-primary-color);
      }
    }

    .charts-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
      gap: 24px;
    }

    .chart-card {
      background: var(--surface);
      border: 1px solid var(--divider);
      border-radius: 12px;
      padding: 24px;
      min-height: 300px;
    }

    .chart-title {
      margin: 0 0 16px 0;
      font-size: 16px;
      font-weight: 600;
      color: var(--text-primary);
    }

    .chart-placeholder {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 200px;
      color: var(--text-secondary);
      text-align: center;

      i {
        font-size: 48px;
        margin-bottom: 16px;
        opacity: 0.5;
      }

      p {
        margin: 0 0 8px 0;
        font-weight: 500;
      }

      small {
        opacity: 0.7;
      }
    }

    /* Recent Items */
    .recent-items-section {
      margin-bottom: 40px;
    }

    .recent-items-list {
      background: var(--surface);
      border: 1px solid var(--divider);
      border-radius: 12px;
      overflow: hidden;
    }

    .recent-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 24px;
      border-bottom: 1px solid var(--divider);
      transition: background-color 0.2s ease;

      &:last-child {
        border-bottom: none;
      }

      &:hover {
        background: var(--hover-bg);
      }
    }

    .item-info {
      flex: 1;

      .item-name {
        font-weight: 600;
        color: var(--text-primary);
        margin-bottom: 4px;
      }

      .item-details {
        font-size: 14px;
        color: var(--text-secondary);
      }
    }

    .item-date {
      font-size: 12px;
      color: var(--text-muted);
      white-space: nowrap;
    }

    /* Empty State */
    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 80px 40px;
      text-align: center;
      color: var(--text-secondary);

      .empty-icon {
        font-size: 64px;
        margin-bottom: 24px;
        opacity: 0.3;
      }

      h3 {
        margin: 0 0 12px 0;
        font-size: 20px;
        color: var(--text-primary);
      }

      p {
        margin: 0;
        max-width: 400px;
      }
    }

    /* Responsive */
    @media (max-width: 768px) {
      .domain-dashboard {
        padding: 16px;
      }

      .kpis-grid {
        grid-template-columns: 1fr;
        gap: 16px;
      }

      .charts-grid {
        grid-template-columns: 1fr;
      }

      .dashboard-title {
        font-size: 24px;
      }
    }
  `]
})
export class DomainDashboardComponent implements OnInit, OnChanges {
  @Input() title: string = 'Dashboard';
  @Input() kpis: DashboardKPI[] = [];
  @Input() charts: DashboardChart[] = [];
  @Input() recentItems: any[] = [];
  @Input() config?: DashboardTabConfig;

  showKPIs = true;
  showCharts = true;
  showRecentItems = true;

  ngOnInit() {
    this.updateVisibilitySettings();
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes['config']) {
      this.updateVisibilitySettings();
    }
  }

  private updateVisibilitySettings() {
    if (this.config) {
      this.showKPIs = this.config.showKPIs !== false;
      this.showCharts = this.config.showCharts !== false;
      this.showRecentItems = this.config.showRecentItems !== false;
    }
  }

  formatKPIValue(value: string | number): string {
    if (typeof value === 'number') {
      if (value >= 1000000) {
        return `${(value / 1000000).toFixed(1)}M`;
      } else if (value >= 1000) {
        return `${(value / 1000).toFixed(1)}K`;
      }
      return value.toLocaleString('pt-BR');
    }
    return value.toString();
  }

  getTrendIcon(trend: string): string {
    const icons = {
      'up': 'fas fa-arrow-up',
      'down': 'fas fa-arrow-down',
      'stable': 'fas fa-minus'
    };
    return icons[trend as keyof typeof icons] || 'fas fa-minus';
  }

  getItemName(item: any): string {
    return item.name || item.title || item.description || `Item #${item.id}`;
  }

  getItemDetails(item: any): string {
    const details = [];
    if (item.status) details.push(`Status: ${item.status}`);
    if (item.type) details.push(`Tipo: ${item.type}`);
    if (item.category) details.push(`Categoria: ${item.category}`);
    return details.join(' • ') || 'Sem detalhes adicionais';
  }

  formatDate(dateString?: string): string {
    if (!dateString) return '-';
    
    const date = new Date(dateString);
    const now = new Date();
    const diffTime = Math.abs(now.getTime() - date.getTime());
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    
    if (diffDays === 1) return 'Hoje';
    if (diffDays === 2) return 'Ontem';
    if (diffDays <= 7) return `${diffDays} dias atrás`;
    
    return date.toLocaleDateString('pt-BR');
  }

  hasContent(): boolean {
    return (this.showKPIs && this.kpis.length > 0) ||
           (this.showCharts && this.charts.length > 0) ||
           (this.showRecentItems && this.recentItems.length > 0);
  }
}
