import { Component, OnInit, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatTableModule } from '@angular/material/table';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatDialogModule, MatDialog } from '@angular/material/dialog';
import { MatSortModule } from '@angular/material/sort';
import { ProjectDialogComponent } from './project-dialog/project-dialog'; // @ts-ignore: Component used in code but not in template
import { ProjectService } from '../services/project.service';

interface Project {
  id: string;
  title: string;
  customer: string;
  customerId?: string;
  status: string;
  assignee: string;
  assigneeId?: string;
  createdAt?: Date;
  updatedAt?: Date;
  deadline?: Date;
  currentStage?: string;
}

@Component({
  selector: 'app-project-management',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    FormsModule,
    MatButtonModule,
    MatIconModule,
    MatTableModule,
    MatInputModule,
    MatSelectModule,
    MatPaginatorModule,
    MatDialogModule,
    MatSortModule
  ],
  templateUrl: './project-management.html',
  styleUrl: './project-management.scss'
})
export class ProjectManagement implements OnInit {
  projects = signal<Project[]>([]);
  filteredProjects = signal<Project[]>([]);
  searchTerm = '';
  statusFilter = '';
  sortColumn = 'updatedAt';
  sortDirection = 'desc';
  pageSize = 10;
  currentPage = 0;
  loading = signal(false);

  // 提供Math对象给模板使用
  readonly Math = Math;

  // 状态颜色映射
  statusColors: Record<string, string> = {
    '待分配': '#FFAA00',
    '进行中': '#165DFF',
    '已完成': '#00B42A',
    '已暂停': '#FF7D00',
    '已延期': '#F53F3F',
    '已取消': '#86909C'
  };

  // 状态文本映射
  statusTexts: Record<string, string> = {
    '待分配': '待分配',
    '进行中': '进行中',
    '已完成': '已完成',
    '已暂停': '已暂停',
    '已延期': '已延期',
    '已取消': '已取消'
  };

  constructor(
    private dialog: MatDialog,
    private projectService: ProjectService
  ) {}

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

  async loadProjects(): Promise<void> {
    this.loading.set(true);
    try {
      const projects = await this.projectService.findProjects({
        limit: 100
      });

      const projectList: Project[] = projects.map(p => {
        const json = this.projectService.toJSON(p);
        return {
          id: json.objectId,
          title: json.title || '未命名项目',
          customer: json.customerName || '未知客户',
          customerId: json.customerId,
          status: json.status || '待分配',
          assignee: json.assigneeName || '未分配',
          assigneeId: json.assigneeId,
          createdAt: json.createdAt?.iso || json.createdAt,
          updatedAt: json.updatedAt?.iso || json.updatedAt,
          deadline: json.deadline,
          currentStage: json.currentStage
        };
      });

      this.projects.set(projectList);
      this.applyFilters();
    } catch (error) {
      console.error('加载项目列表失败:', error);
      this.projects.set([]);
    } finally {
      this.loading.set(false);
    }
  }

  applyFilters(): void {
    let result = [...this.projects()];

    // 搜索过滤
    if (this.searchTerm) {
      const term = this.searchTerm.toLowerCase();
      result = result.filter(project =>
        project.title.toLowerCase().includes(term) ||
        project.customer.toLowerCase().includes(term) ||
        project.assignee.toLowerCase().includes(term)
      );
    }
    
    // 状态过滤
    if (this.statusFilter) {
      result = result.filter(project => project.status === this.statusFilter);
    }
    
    // 排序 - 按更新时间或创建时间
    result.sort((a, b) => {
      if (this.sortColumn === 'updatedAt' || this.sortColumn === 'createdAt') {
        const dateA = a[this.sortColumn] ? new Date(a[this.sortColumn] as Date).getTime() : 0;
        const dateB = b[this.sortColumn] ? new Date(b[this.sortColumn] as Date).getTime() : 0;
        return this.sortDirection === 'asc' ? dateA - dateB : dateB - dateA;
      } else {
        const valueA = String((a as any)[this.sortColumn] || '').toLowerCase();
        const valueB = String((b as any)[this.sortColumn] || '').toLowerCase();
        return this.sortDirection === 'asc' ? valueA.localeCompare(valueB) : valueB.localeCompare(valueA);
      }
    });
    
    this.filteredProjects.set(result);
  }

  onSearch(): void {
    this.applyFilters();
  }

  onStatusFilterChange(): void {
    this.applyFilters();
  }

  onSort(column: string): void {
    if (this.sortColumn === column) {
      this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
    } else {
      this.sortColumn = column;
      this.sortDirection = 'asc';
    }
    this.applyFilters();
  }

  // 简化的编辑对话框（只允许修改名字和分配组员）
  openEditDialog(project: Project): void {
    // TODO: 实现简单的编辑对话框，使用设计师分配组件
    // 暂时使用alert提示
    alert('编辑功能将在设计师分配组件对接完成后实现');
  }


  formatCurrency(amount: number): string {
    return new Intl.NumberFormat('zh-CN', {
      style: 'currency',
      currency: 'CNY',
      minimumFractionDigits: 0
    }).format(amount);
  }

  get paginatedProjects(): Project[] {
    const startIndex = this.currentPage * this.pageSize;
    return this.filteredProjects().slice(startIndex, startIndex + this.pageSize);
  }

  get totalPages(): number {
    return Math.ceil(this.filteredProjects().length / this.pageSize);
  }

  // 项目状态统计计算属性
  get inProgressProjectsCount(): number {
    return this.projects().filter(p => p.status === '进行中').length;
  }

  get completedProjectsCount(): number {
    return this.projects().filter(p => p.status === '已完成').length;
  }

  get pendingProjectsCount(): number {
    return this.projects().filter(p => p.status === '待分配').length;
  }

  // 项目总数
  get totalProjectsCount(): number {
    return this.projects().length;
  }

  onPageChange(page: number): void {
    this.currentPage = page;
  }

  // 生成页码数组
  getPageNumbers(): number[] {
    const totalPages = this.totalPages;
    const currentPage = this.currentPage;
    const pageNumbers: number[] = [];

    // 简单实现：显示所有页码
    for (let i = 0; i < totalPages; i++) {
      pageNumbers.push(i);
    }

    return pageNumbers;
  }
}