import { Component, OnInit, afterNextRender } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { 
  faCat, 
  faBell, 
  faUser, 
  faTrashAlt, 
  faLightbulb, 
  faCheck, 
  faSpinner, 
  faHome, 
  faSearch, 
  faBookOpen, 
  faShoppingCart 
} from '@fortawesome/free-solid-svg-icons';
import { Chart } from 'chart.js';
import { CartItemComponent } from './components/cart-item/cart-item.component/cart-item.component';
import { NutritionChartComponent } from './components/nutrition-chart/nutrition-chart.component/nutrition-chart.component';
import { BudgetProgressComponent } from './components/budget-progress/budget-progress.component/budget-progress.component';
import { SuggestionItemComponent } from './components/suggestion-item/suggestion-item.component/suggestion-item.component';
import { HistoryItemComponent } from './components/history-item/history-item.component/history-item.component';

@Component({
  selector: 'app-page-order',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    FontAwesomeModule,
    CartItemComponent,
    NutritionChartComponent,
    BudgetProgressComponent,
    SuggestionItemComponent,
    HistoryItemComponent
  ],
  templateUrl: './page-order.html',
  styleUrls: ['./page-order.scss']
})
export class PageOrderComponent implements OnInit {
  // Icons
  icons = {
    faCat,
    faBell,
    faUser,
    faTrashAlt,
    faLightbulb,
    faCheck,
    faSpinner,
    faHome,
    faSearch,
    faBookOpen,
    faShoppingCart
  };

  // Cart items data
  cartItems = [
    { id: 1, name: '招牌酸菜鱼', price: 68, quantity: 1, initial: '酸' },
    { id: 2, name: '香辣小龙虾', price: 98, quantity: 1, initial: '虾' },
    { id: 3, name: '金汤肥牛锅', price: 58, quantity: 1, initial: '牛' }
  ];

  // Suggestions data
  suggestions = [
    { 
      id: 1, 
      name: '清蒸鲈鱼', 
      price: 62, 
      initial: '鱼', 
      reason: '更低热量 · 更高蛋白质' 
    },
    { 
      id: 2, 
      name: '蒜蓉蒸虾', 
      price: 88, 
      initial: '虾', 
      reason: '更低脂肪 · 更少辛辣' 
    },
    { 
      id: 3, 
      name: '番茄牛腩汤', 
      price: 48, 
      initial: '汤', 
      reason: '更多维生素 · 更低热量' 
    }
  ];

  // History items data
  historyItems = [
    { id: 1, name: '点菜喵主题餐厅', date: '06-25 消费¥236', initial: '喵' },
    { id: 2, name: '渔家小馆', date: '06-20 消费¥182', initial: '鱼' },
    { id: 3, name: '龙虾先生', date: '06-15 消费¥320', initial: '虾' },
    { id: 4, name: '火锅物语', date: '06-10 消费¥198', initial: '锅' }
  ];

  // Order summary data
  orderSummary = {
    subtotal: 224,
    delivery: 3.5,
    discount: 15,
    total: 212.5
  };

  // Budget data
  budget = {
    total: 800,
    spent: 520,
    remaining: 280,
    percentage: 65
  };

  // Nutrition data
  nutrition = {
    balance: 72,
    healthScore: 4.8,
    nutrients: '3/5'
  };

  constructor() {
    afterNextRender(() => {
      this.initializeChart();
    });
  }

  ngOnInit(): void {}

  initializeChart(): void {
    const ctx = document.getElementById('nutritionChart') as HTMLCanvasElement;
    if (!ctx) return;

    new Chart(ctx, {
      type: 'radar',
      data: {
        labels: ['蛋白质', '碳水', '脂肪', '纤维', '维生素'],
        datasets: [{
          label: '当前营养值',
          data: [85, 70, 45, 60, 75],
          fill: true,
          backgroundColor: 'rgba(255, 107, 107, 0.2)',
          borderColor: 'rgba(255, 107, 107, 1)',
          pointBackgroundColor: 'rgba(255, 107, 107, 1)',
          pointBorderColor: '#fff',
          pointHoverBackgroundColor: '#fff',
          pointHoverBorderColor: 'rgba(255, 107, 107, 1)'
        }]
      },
      options: {
        scales: {
          r: {
            angleLines: { display: true },
            suggestedMin: 0,
            suggestedMax: 100,
            ticks: {
              stepSize: 20,
              backdropColor: 'transparent'
            },
            grid: { color: 'rgba(0, 0, 0, 0.1)' },
            pointLabels: { font: { size: 11 } }
          }
        },
        plugins: { legend: { display: false } }
      }
    });
  }

  updateQuantity(item: any, change: number): void {
    const newQuantity = item.quantity + change;
    if (newQuantity >= 1) {
      item.quantity = newQuantity;
    }
  }

  removeItem(itemId: number): void {
    this.cartItems = this.cartItems.filter(item => item.id !== itemId);
  }

  replaceSuggestion(suggestionId: number): void {
    const suggestion = this.suggestions.find(s => s.id === suggestionId);
    if (suggestion) {
      // In a real app, you would implement the replacement logic here
      console.log(`Replacing with ${suggestion.name}`);
    }
  }

  checkout(): void {
    // In a real app, you would implement the checkout logic here
    console.log('Checking out...');
  }
}