'use server';

import type {
  Project,
  ProjectStats,
  ProjectFilter,
  ProjectListResponse,
  SelectOption,
  ProjectDetail,
  Stage,
  StageDetail,
  ProjectEndFormData,
  DetailCategory,
} from './types';

/**
 * 프로젝트 관리 Server Actions
 * TODO: 실제 API 연동 시 구현
 */

// 목업 데이터
const mockProjects: Project[] = [
  {
    id: '1',
    contractNumber: '121123',
    partnerName: '대한건설',
    siteName: '서울 강남 현장',
    contractManager: '홍길동',
    constructionPM: '김철수',
    totalLocations: 5,
    contractAmount: 150000000,
    progressRate: 100,
    accumulatedPayment: 150000000,
    startDate: '2024-11-01',
    endDate: '2025-03-31',
    status: 'completed',
    hasUrgentIssue: false,
    createdAt: '2024-11-01',
    updatedAt: '2025-03-31',
  },
  {
    id: '2',
    contractNumber: '121124',
    partnerName: '삼성시공',
    siteName: '부산 해운대 현장',
    contractManager: '이영희',
    constructionPM: '박민수',
    totalLocations: 8,
    contractAmount: 200000000,
    progressRate: 85.2,
    accumulatedPayment: 170400000,
    startDate: '2024-12-15',
    endDate: '2025-06-30',
    status: 'in_progress',
    hasUrgentIssue: false,
    createdAt: '2024-12-15',
    updatedAt: '2025-01-10',
  },
  {
    id: '3',
    contractNumber: '121125',
    partnerName: 'LG건설',
    siteName: '대전 유성 현장',
    contractManager: '최민수',
    constructionPM: '정대리',
    totalLocations: 3,
    contractAmount: 80000000,
    progressRate: 15.3,
    accumulatedPayment: 12240000,
    startDate: '2025-01-01',
    endDate: '2025-08-31',
    status: 'in_progress',
    hasUrgentIssue: false,
    createdAt: '2025-01-01',
    updatedAt: '2025-01-10',
  },
  {
    id: '4',
    contractNumber: '121126',
    partnerName: '현대건설',
    siteName: '인천 송도 현장',
    contractManager: '강과장',
    constructionPM: '윤대리',
    totalLocations: 12,
    contractAmount: 350000000,
    progressRate: 86.5,
    accumulatedPayment: 302750000,
    startDate: '2024-10-01',
    endDate: '2025-05-31',
    status: 'in_progress',
    hasUrgentIssue: false,
    createdAt: '2024-10-01',
    updatedAt: '2025-01-10',
  },
  {
    id: '5',
    contractNumber: '121127',
    partnerName: 'SK건설',
    siteName: '광주 북구 현장',
    contractManager: '임부장',
    constructionPM: '오차장',
    totalLocations: 6,
    contractAmount: 120000000,
    progressRate: 86.5,
    accumulatedPayment: 103800000,
    startDate: '2024-09-15',
    endDate: '2025-04-30',
    status: 'in_progress',
    hasUrgentIssue: false,
    createdAt: '2024-09-15',
    updatedAt: '2025-01-10',
  },
  {
    id: '6',
    contractNumber: '121128',
    partnerName: '포스코건설',
    siteName: '울산 남구 현장',
    contractManager: '서이사',
    constructionPM: '한부장',
    totalLocations: 4,
    contractAmount: 95000000,
    progressRate: 85.3,
    accumulatedPayment: 81035000,
    startDate: '2024-11-20',
    endDate: '2025-07-31',
    status: 'urgent',
    hasUrgentIssue: true,
    createdAt: '2024-11-20',
    updatedAt: '2025-01-10',
  },
  // 스크롤 테스트용 추가 데이터
  {
    id: '7',
    contractNumber: '121129',
    partnerName: '롯데건설',
    siteName: '제주 서귀포 현장',
    contractManager: '김사장',
    constructionPM: '이과장',
    totalLocations: 7,
    contractAmount: 180000000,
    progressRate: 45.0,
    accumulatedPayment: 81000000,
    startDate: '2024-12-01',
    endDate: '2025-09-30',
    status: 'in_progress',
    hasUrgentIssue: false,
    createdAt: '2024-12-01',
    updatedAt: '2025-01-10',
  },
  {
    id: '8',
    contractNumber: '121130',
    partnerName: 'GS건설',
    siteName: '수원 영통 현장',
    contractManager: '박대리',
    constructionPM: '최부장',
    totalLocations: 10,
    contractAmount: 280000000,
    progressRate: 62.8,
    accumulatedPayment: 175840000,
    startDate: '2024-11-15',
    endDate: '2025-06-15',
    status: 'in_progress',
    hasUrgentIssue: false,
    createdAt: '2024-11-15',
    updatedAt: '2025-01-10',
  },
  {
    id: '9',
    contractNumber: '121131',
    partnerName: '한화건설',
    siteName: '대구 동구 현장',
    contractManager: '정이사',
    constructionPM: '송대리',
    totalLocations: 5,
    contractAmount: 140000000,
    progressRate: 78.5,
    accumulatedPayment: 109900000,
    startDate: '2024-10-20',
    endDate: '2025-04-20',
    status: 'in_progress',
    hasUrgentIssue: false,
    createdAt: '2024-10-20',
    updatedAt: '2025-01-10',
  },
  {
    id: '10',
    contractNumber: '121132',
    partnerName: '대우건설',
    siteName: '성남 분당 현장',
    contractManager: '윤차장',
    constructionPM: '장과장',
    totalLocations: 15,
    contractAmount: 420000000,
    progressRate: 35.0,
    accumulatedPayment: 147000000,
    startDate: '2025-01-05',
    endDate: '2025-12-31',
    status: 'in_progress',
    hasUrgentIssue: false,
    createdAt: '2025-01-05',
    updatedAt: '2025-01-10',
  },
  {
    id: '11',
    contractNumber: '121133',
    partnerName: '두산건설',
    siteName: '청주 흥덕 현장',
    contractManager: '안부장',
    constructionPM: '허대리',
    totalLocations: 6,
    contractAmount: 160000000,
    progressRate: 92.0,
    accumulatedPayment: 147200000,
    startDate: '2024-08-01',
    endDate: '2025-02-28',
    status: 'in_progress',
    hasUrgentIssue: false,
    createdAt: '2024-08-01',
    updatedAt: '2025-01-10',
  },
  {
    id: '12',
    contractNumber: '121134',
    partnerName: '태영건설',
    siteName: '천안 서북 현장',
    contractManager: '문과장',
    constructionPM: '남차장',
    totalLocations: 8,
    contractAmount: 220000000,
    progressRate: 55.5,
    accumulatedPayment: 122100000,
    startDate: '2024-12-20',
    endDate: '2025-08-20',
    status: 'urgent',
    hasUrgentIssue: true,
    createdAt: '2024-12-20',
    updatedAt: '2025-01-10',
  },
];

// 프로젝트 목록 조회
export async function getProjectList(
  filter?: ProjectFilter
): Promise<{ success: boolean; data?: ProjectListResponse; error?: string }> {
  try {
    let filtered = [...mockProjects];

    // 거래처 필터 (다중선택)
    if (filter?.partners && filter.partners.length > 0 && !filter.partners.includes('all')) {
      filtered = filtered.filter((p) => filter.partners!.includes(p.partnerName));
    }

    // 현장 필터 (다중선택)
    if (filter?.sites && filter.sites.length > 0 && !filter.sites.includes('all')) {
      filtered = filtered.filter((p) => filter.sites!.includes(p.siteName));
    }

    // 계약담당자 필터 (다중선택)
    if (filter?.contractManagers && filter.contractManagers.length > 0 && !filter.contractManagers.includes('all')) {
      filtered = filtered.filter((p) => filter.contractManagers!.includes(p.contractManager));
    }

    // 공사PM 필터 (다중선택)
    if (filter?.constructionPMs && filter.constructionPMs.length > 0 && !filter.constructionPMs.includes('all')) {
      filtered = filtered.filter((p) => filter.constructionPMs!.includes(p.constructionPM));
    }

    // 상태 필터 (단일선택)
    if (filter?.status && filter.status !== 'all') {
      filtered = filtered.filter((p) => p.status === filter.status);
    }

    // 정렬
    if (filter?.sortBy) {
      switch (filter.sortBy) {
        case 'latest':
          filtered.sort((a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime());
          break;
        case 'progress':
          filtered.sort((a, b) => b.progressRate - a.progressRate);
          break;
        case 'register':
          filtered.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
          break;
        case 'completion':
          filtered.sort((a, b) => new Date(a.endDate).getTime() - new Date(b.endDate).getTime());
          break;
      }
    }

    const page = filter?.page ?? 1;
    const size = filter?.size ?? 20;
    const start = (page - 1) * size;
    const paginatedItems = filtered.slice(start, start + size);

    return {
      success: true,
      data: {
        items: paginatedItems,
        total: filtered.length,
        page,
        size,
        totalPages: Math.ceil(filtered.length / size),
      },
    };
  } catch (error) {
    console.error('getProjectList error:', error);
    return { success: false, error: '프로젝트 목록 조회에 실패했습니다.' };
  }
}

// 프로젝트 상세 조회
export async function getProject(
  id: string
): Promise<{ success: boolean; data?: Project; error?: string }> {
  try {
    const project = mockProjects.find((p) => p.id === id);

    if (!project) {
      return { success: false, error: '프로젝트를 찾을 수 없습니다.' };
    }

    return { success: true, data: project };
  } catch (error) {
    console.error('getProject error:', error);
    return { success: false, error: '프로젝트 조회에 실패했습니다.' };
  }
}

// 프로젝트 통계 조회
export async function getProjectStats(): Promise<{ success: boolean; data?: ProjectStats; error?: string }> {
  try {
    const total = mockProjects.length;
    const completed = mockProjects.filter((p) => p.status === 'completed').length;
    const inProgress = mockProjects.filter((p) => p.status === 'in_progress' || p.status === 'urgent').length;

    return {
      success: true,
      data: {
        total,
        inProgress,
        completed,
      },
    };
  } catch (error) {
    console.error('getProjectStats error:', error);
    return { success: false, error: '통계 조회에 실패했습니다.' };
  }
}

// 거래처 목록 조회 (필터용)
export async function getPartnerOptions(): Promise<{ success: boolean; data?: SelectOption[]; error?: string }> {
  try {
    const partners = [...new Set(mockProjects.map((p) => p.partnerName))];
    const options: SelectOption[] = partners.map((name) => ({
      value: name,
      label: name,
    }));

    return { success: true, data: options };
  } catch (error) {
    console.error('getPartnerOptions error:', error);
    return { success: false, error: '거래처 목록 조회에 실패했습니다.' };
  }
}

// 현장 목록 조회 (필터용)
export async function getSiteOptions(): Promise<{ success: boolean; data?: SelectOption[]; error?: string }> {
  try {
    const sites = [...new Set(mockProjects.map((p) => p.siteName))];
    const options: SelectOption[] = sites.map((name) => ({
      value: name,
      label: name,
    }));

    return { success: true, data: options };
  } catch (error) {
    console.error('getSiteOptions error:', error);
    return { success: false, error: '현장 목록 조회에 실패했습니다.' };
  }
}

// 계약담당자 목록 조회 (필터용)
export async function getContractManagerOptions(): Promise<{ success: boolean; data?: SelectOption[]; error?: string }> {
  try {
    const managers = [...new Set(mockProjects.map((p) => p.contractManager))];
    const options: SelectOption[] = managers.map((name) => ({
      value: name,
      label: name,
    }));

    return { success: true, data: options };
  } catch (error) {
    console.error('getContractManagerOptions error:', error);
    return { success: false, error: '계약담당자 목록 조회에 실패했습니다.' };
  }
}

// 공사PM 목록 조회 (필터용)
export async function getConstructionPMOptions(): Promise<{ success: boolean; data?: SelectOption[]; error?: string }> {
  try {
    const pms = [...new Set(mockProjects.map((p) => p.constructionPM))];
    const options: SelectOption[] = pms.map((name) => ({
      value: name,
      label: name,
    }));

    return { success: true, data: options };
  } catch (error) {
    console.error('getConstructionPMOptions error:', error);
    return { success: false, error: '공사PM 목록 조회에 실패했습니다.' };
  }
}

// 프로젝트 수정
export async function updateProject(
  id: string,
  data: Partial<Project>
): Promise<{ success: boolean; data?: Project; error?: string }> {
  try {

    const existingProject = mockProjects.find((p) => p.id === id);
    if (!existingProject) {
      return { success: false, error: '프로젝트를 찾을 수 없습니다.' };
    }

    const updatedProject: Project = {
      ...existingProject,
      ...data,
      updatedAt: new Date().toISOString(),
    };

    return { success: true, data: updatedProject };
  } catch (error) {
    console.error('updateProject error:', error);
    return { success: false, error: '프로젝트 수정에 실패했습니다.' };
  }
}

// ============================================
// 프로젝트 실행관리 상세 페이지 Server Actions
// ============================================

// 프로젝트별 단계 목업 데이터
const mockStages: Record<string, Stage[]> = {
  '1': [
    { id: 's1-1', type: 'bid', siteName: '서울 강남 현장', status: 'completed', date: '2024-11-05', amount: 150000000 },
    { id: 's1-2', type: 'contract', siteName: '서울 강남 현장', status: 'completed', date: '2024-11-10', amount: 150000000 },
    { id: 's1-3', type: 'construction', siteName: '서울 강남 현장', status: 'completed', pm: '김철수', count: 5 },
  ],
  '2': [
    { id: 's2-1', type: 'bid', siteName: '부산 해운대 현장', status: 'completed', date: '2024-12-18', amount: 200000000 },
    { id: 's2-2', type: 'contract', siteName: '부산 해운대 현장', status: 'completed', date: '2024-12-20', amount: 200000000 },
    { id: 's2-3', type: 'construction', siteName: '부산 해운대 현장', status: 'in_progress', pm: '박민수', count: 8 },
  ],
  '3': [
    { id: 's3-1', type: 'bid', siteName: '대전 유성 현장', status: 'in_progress', date: '2025-01-05', amount: 80000000 },
  ],
  '4': [
    { id: 's4-1', type: 'bid', siteName: '인천 송도 현장', status: 'completed', date: '2024-10-05', amount: 350000000 },
    { id: 's4-2', type: 'contract', siteName: '인천 송도 현장', status: 'completed', date: '2024-10-10', amount: 350000000 },
    { id: 's4-3', type: 'order', siteName: '인천 송도 현장', status: 'completed', date: '2024-10-15' },
    { id: 's4-4', type: 'construction', siteName: '인천 송도 현장', status: 'in_progress', pm: '윤대리', count: 12 },
  ],
};

// 단계별 상세 항목 목업 데이터
const mockStageDetails: Record<string, StageDetail[]> = {
  's2-1': [
    { id: 'd2-1-1', type: 'site_briefing', title: '부산 해운대 현장', date: '2024-12-16', status: 'completed' },
    { id: 'd2-1-2', type: 'estimation', title: '부산 해운대 현장', date: '2024-12-17', status: 'completed' },
    { id: 'd2-1-3', type: 'bid_result', title: '부산 해운대 현장', date: '2024-12-18', status: 'completed' },
  ],
  's2-3': [
    { id: 'd2-3-1', type: 'handover_report', title: '부산 해운대 현장', pm: '박민수', status: 'completed' },
    { id: 'd2-3-2', type: 'structure_review', title: '부산 해운대 현장', date: '2024-12-22', status: 'completed' },
  ],
  's3-1': [
    { id: 'd3-1-1', type: 'site_briefing', title: '대전 유성 현장', date: '2025-01-03', status: 'completed' },
    { id: 'd3-1-2', type: 'estimation', title: '대전 유성 현장', date: '2025-01-04', status: 'in_progress' },
  ],
  's4-1': [
    { id: 'd4-1-1', type: 'site_briefing', title: '인천 송도 현장', date: '2024-10-03', status: 'completed' },
    { id: 'd4-1-2', type: 'estimation', title: '인천 송도 현장', date: '2024-10-04', status: 'completed' },
    { id: 'd4-1-3', type: 'bid_result', title: '인천 송도 현장', date: '2024-10-05', status: 'completed' },
  ],
  's4-4': [
    { id: 'd4-4-1', type: 'handover_report', title: '인천 송도 현장', pm: '윤대리', status: 'completed' },
    { id: 'd4-4-2', type: 'structure_review', title: '인천 송도 현장', date: '2024-10-18', status: 'completed' },
  ],
};

// 프로젝트 상세 조회 (칸반 보드용)
export async function getProjectDetail(
  id: string
): Promise<{ success: boolean; data?: ProjectDetail; error?: string }> {
  try {
    const project = mockProjects.find((p) => p.id === id);

    if (!project) {
      return { success: false, error: '프로젝트를 찾을 수 없습니다.' };
    }

    const stages = mockStages[id] || [];
    const details: StageDetail[] = [];

    // 각 단계의 상세 항목 수집
    stages.forEach((stage) => {
      const stageDetails = mockStageDetails[stage.id] || [];
      details.push(...stageDetails);
    });

    const projectDetail: ProjectDetail = {
      ...project,
      stages,
      details,
    };

    return { success: true, data: projectDetail };
  } catch (error) {
    console.error('getProjectDetail error:', error);
    return { success: false, error: '프로젝트 상세 조회에 실패했습니다.' };
  }
}

// 단계별 상세 항목 조회
export async function getStageDetails(
  stageId: string
): Promise<{ success: boolean; data?: StageDetail[]; error?: string }> {
  try {
    const details = mockStageDetails[stageId] || [];
    return { success: true, data: details };
  } catch (error) {
    console.error('getStageDetails error:', error);
    return { success: false, error: '단계 상세 조회에 실패했습니다.' };
  }
}

// 프로젝트 종료 처리
export async function updateProjectEnd(
  data: ProjectEndFormData
): Promise<{ success: boolean; error?: string }> {
  try {

    const project = mockProjects.find((p) => p.id === data.projectId);
    if (!project) {
      return { success: false, error: '프로젝트를 찾을 수 없습니다.' };
    }

    // 실제 구현에서는 DB 업데이트
    // project.status = data.status === 'completed' ? 'completed' : 'in_progress';
    // project.endDate = data.completionDate;

    return { success: true };
  } catch (error) {
    console.error('updateProjectEnd error:', error);
    return { success: false, error: '프로젝트 종료 처리에 실패했습니다.' };
  }
}

// 단계별 상세 카테고리 목업 데이터 (시공, 이슈 아코디언)
const mockDetailCategories: Record<string, DetailCategory[]> = {
  // 시공 단계 선택 시 표시할 상세 카테고리
  's1-3': [
    {
      type: 'construction',
      count: 3,
      constructionItems: [
        { id: 'c1-1', number: '123123', inputDate: '2024-11-15', status: 'completed' },
        { id: 'c1-2', number: '123124', inputDate: '2024-11-20', status: 'completed' },
        { id: 'c1-3', number: '123125', inputDate: '2024-11-25', status: 'completed' },
      ],
    },
    {
      type: 'issue',
      count: 2,
      issueItems: [
        { id: 'i1-1', number: 'ISS-001', title: '자재 지연', status: 'resolved', createdAt: '2024-11-18' },
        { id: 'i1-2', number: 'ISS-002', title: '인력 부족', status: 'resolved', createdAt: '2024-11-22' },
      ],
    },
  ],
  's2-3': [
    {
      type: 'construction',
      count: 5,
      constructionItems: [
        { id: 'c2-1', number: '123126', inputDate: '2024-12-25', status: 'in_progress' },
        { id: 'c2-2', number: '123127', inputDate: '2024-12-28', status: 'completed' },
        { id: 'c2-3', number: '123128', inputDate: '2025-01-02', status: 'completed' },
        { id: 'c2-4', number: '123129', inputDate: '2025-01-05', status: 'in_progress' },
        { id: 'c2-5', number: '123130', inputDate: '2025-01-08', status: 'in_progress' },
      ],
    },
    {
      type: 'issue',
      count: 3,
      issueItems: [
        { id: 'i2-1', number: 'ISS-003', title: '설계 변경', status: 'open', createdAt: '2024-12-27' },
        { id: 'i2-2', number: 'ISS-004', title: '민원 발생', status: 'resolved', createdAt: '2025-01-03' },
        { id: 'i2-3', number: 'ISS-005', title: '안전 점검', status: 'open', createdAt: '2025-01-10' },
      ],
    },
  ],
  's4-4': [
    {
      type: 'construction',
      count: 128,
      constructionItems: [
        { id: 'c4-1', number: '123123', inputDate: '2025-12-15', status: 'in_progress' },
        { id: 'c4-2', number: '123123', inputDate: '2025-12-15', status: 'completed' },
        { id: 'c4-3', number: '123123', inputDate: '2025-12-15', status: 'completed' },
      ],
    },
    {
      type: 'issue',
      count: 128,
      issueItems: [
        { id: 'i4-1', number: 'ISS-010', title: '품질 검사', status: 'open', createdAt: '2024-10-20' },
        { id: 'i4-2', number: 'ISS-011', title: '공정 지연', status: 'resolved', createdAt: '2024-10-25' },
      ],
    },
  ],
};

// 단계별 상세 카테고리 조회
export async function getDetailCategories(
  stageId: string
): Promise<{ success: boolean; data?: DetailCategory[]; error?: string }> {
  try {
    const categories = mockDetailCategories[stageId] || [];
    return { success: true, data: categories };
  } catch (error) {
    console.error('getDetailCategories error:', error);
    return { success: false, error: '상세 카테고리 조회에 실패했습니다.' };
  }
}

// 프로젝트 목록 조회 (상세 페이지용 - 전체 프로젝트 목록)
export async function getProjectsForKanban(): Promise<{
  success: boolean;
  data?: ProjectDetail[];
  error?: string;
}> {
  try {
    const projectDetails: ProjectDetail[] = mockProjects.map((project) => {
      const stages = mockStages[project.id] || [];
      const details: StageDetail[] = [];

      stages.forEach((stage) => {
        const stageDetails = mockStageDetails[stage.id] || [];
        details.push(...stageDetails);
      });

      return {
        ...project,
        stages,
        details,
      };
    });

    return { success: true, data: projectDetails };
  } catch (error) {
    console.error('getProjectsForKanban error:', error);
    return { success: false, error: '프로젝트 목록 조회에 실패했습니다.' };
  }
}

// ============================================
// 시공관리 리스트 Server Actions
// ============================================

import type {
  ConstructionManagement,
  ConstructionManagementStats,
  ConstructionManagementFilter,
  ConstructionManagementListResponse,
} from './types';

// 시공관리 목업 데이터
const mockConstructionManagements: ConstructionManagement[] = [
  {
    id: 'cm1',
    constructionNumber: '121212',
    partnerName: '대한건설',
    siteName: '서울 강남 현장',
    constructionPM: '김철수',
    workTeamLeader: '이반장',
    worker: '홍길동',
    workerCount: 3,
    constructionStartDate: '2025-12-15',
    constructionEndDate: null,
    status: 'in_progress',
    periodStart: '2025-12-15',
    periodEnd: '2025-12-20',
    createdAt: '2025-12-10',
    updatedAt: '2025-12-15',
  },
  {
    id: 'cm2',
    constructionNumber: '121213',
    partnerName: '삼성시공',
    siteName: '부산 해운대 현장',
    constructionPM: '박민수',
    workTeamLeader: '김반장',
    worker: '이순신',
    workerCount: 2,
    constructionStartDate: '2025-12-14',
    constructionEndDate: '2025-12-16',
    status: 'completed',
    periodStart: '2025-12-14',
    periodEnd: '2025-12-16',
    createdAt: '2025-12-08',
    updatedAt: '2025-12-16',
  },
  {
    id: 'cm3',
    constructionNumber: '121214',
    partnerName: 'LG건설',
    siteName: '대전 유성 현장',
    constructionPM: '정대리',
    workTeamLeader: '박반장',
    worker: '강감찬',
    workerCount: 4,
    constructionStartDate: '2025-12-13',
    constructionEndDate: null,
    status: 'in_progress',
    periodStart: '2025-12-13',
    periodEnd: '2025-12-18',
    createdAt: '2025-12-05',
    updatedAt: '2025-12-13',
  },
  {
    id: 'cm4',
    constructionNumber: '121215',
    partnerName: '현대건설',
    siteName: '인천 송도 현장',
    constructionPM: '윤대리',
    workTeamLeader: '최반장',
    worker: '을지문덕',
    workerCount: 5,
    constructionStartDate: '2025-12-12',
    constructionEndDate: '2025-12-15',
    status: 'completed',
    periodStart: '2025-12-12',
    periodEnd: '2025-12-15',
    createdAt: '2025-12-01',
    updatedAt: '2025-12-15',
  },
  {
    id: 'cm5',
    constructionNumber: '121216',
    partnerName: 'SK건설',
    siteName: '광주 북구 현장',
    constructionPM: '오차장',
    workTeamLeader: '정반장',
    worker: '계백',
    workerCount: 2,
    constructionStartDate: '2025-12-11',
    constructionEndDate: null,
    status: 'in_progress',
    periodStart: '2025-12-11',
    periodEnd: '2025-12-19',
    createdAt: '2025-12-02',
    updatedAt: '2025-12-11',
  },
  {
    id: 'cm6',
    constructionNumber: '121217',
    partnerName: '대한건설',
    siteName: '서울 강남 현장',
    constructionPM: '김철수',
    workTeamLeader: '이반장',
    worker: '김유신',
    workerCount: 3,
    constructionStartDate: '2025-12-10',
    constructionEndDate: '2025-12-14',
    status: 'completed',
    periodStart: '2025-12-10',
    periodEnd: '2025-12-14',
    createdAt: '2025-12-03',
    updatedAt: '2025-12-14',
  },
  {
    id: 'cm7',
    constructionNumber: '121218',
    partnerName: '삼성시공',
    siteName: '부산 해운대 현장',
    constructionPM: '박민수',
    workTeamLeader: '김반장',
    worker: '권율',
    workerCount: 4,
    constructionStartDate: '2025-12-09',
    constructionEndDate: null,
    status: 'in_progress',
    periodStart: '2025-12-09',
    periodEnd: '2025-12-17',
    createdAt: '2025-12-04',
    updatedAt: '2025-12-09',
  },
  {
    id: 'cm8',
    constructionNumber: '121219',
    partnerName: 'LG건설',
    siteName: '대전 유성 현장',
    constructionPM: '정대리',
    workTeamLeader: '박반장',
    worker: '이성계',
    workerCount: 3,
    constructionStartDate: '2025-12-08',
    constructionEndDate: '2025-12-12',
    status: 'completed',
    periodStart: '2025-12-08',
    periodEnd: '2025-12-12',
    createdAt: '2025-12-01',
    updatedAt: '2025-12-12',
  },
  {
    id: 'cm9',
    constructionNumber: '121220',
    partnerName: '현대건설',
    siteName: '인천 송도 현장',
    constructionPM: '윤대리',
    workTeamLeader: '최반장',
    worker: '정도전',
    workerCount: 6,
    constructionStartDate: '2025-12-07',
    constructionEndDate: null,
    status: 'in_progress',
    periodStart: '2025-12-07',
    periodEnd: '2025-12-16',
    createdAt: '2025-12-02',
    updatedAt: '2025-12-07',
  },
  {
    id: 'cm10',
    constructionNumber: '121221',
    partnerName: 'SK건설',
    siteName: '광주 북구 현장',
    constructionPM: '오차장',
    workTeamLeader: '정반장',
    worker: '세종대왕',
    workerCount: 2,
    constructionStartDate: '2025-12-06',
    constructionEndDate: null,
    status: 'in_progress',
    periodStart: '2025-12-06',
    periodEnd: '2025-12-15',
    createdAt: '2025-11-28',
    updatedAt: '2025-12-06',
  },
  {
    id: 'cm11',
    constructionNumber: '121222',
    partnerName: '대한건설',
    siteName: '서울 강남 현장',
    constructionPM: '김철수',
    workTeamLeader: '이반장',
    worker: '장영실',
    workerCount: 5,
    constructionStartDate: '2025-12-05',
    constructionEndDate: null,
    status: 'in_progress',
    periodStart: '2025-12-05',
    periodEnd: '2025-12-14',
    createdAt: '2025-11-27',
    updatedAt: '2025-12-05',
  },
];

// 시공관리 목록 조회
export async function getConstructionManagementList(
  filter?: ConstructionManagementFilter
): Promise<{ success: boolean; data?: ConstructionManagementListResponse; error?: string }> {
  try {
    let filtered = [...mockConstructionManagements];

    // 거래처 필터 (다중선택)
    if (filter?.partners && filter.partners.length > 0) {
      const partnerLabels = filter.partners.map((v) => {
        const found = [
          { value: 'partner1', label: '대한건설' },
          { value: 'partner2', label: '삼성시공' },
          { value: 'partner3', label: 'LG건설' },
          { value: 'partner4', label: '현대건설' },
          { value: 'partner5', label: 'SK건설' },
        ].find((p) => p.value === v);
        return found?.label;
      }).filter(Boolean);
      filtered = filtered.filter((c) => partnerLabels.includes(c.partnerName));
    }

    // 현장명 필터 (다중선택)
    if (filter?.sites && filter.sites.length > 0) {
      const siteLabels = filter.sites.map((v) => {
        const found = [
          { value: 'site1', label: '서울 강남 현장' },
          { value: 'site2', label: '부산 해운대 현장' },
          { value: 'site3', label: '대전 유성 현장' },
          { value: 'site4', label: '인천 송도 현장' },
          { value: 'site5', label: '광주 북구 현장' },
        ].find((s) => s.value === v);
        return found?.label;
      }).filter(Boolean);
      filtered = filtered.filter((c) => siteLabels.includes(c.siteName));
    }

    // 공사PM 필터 (다중선택)
    if (filter?.constructionPMs && filter.constructionPMs.length > 0) {
      const pmLabels = filter.constructionPMs.map((v) => {
        const found = [
          { value: 'pm1', label: '김철수' },
          { value: 'pm2', label: '박민수' },
          { value: 'pm3', label: '정대리' },
          { value: 'pm4', label: '윤대리' },
          { value: 'pm5', label: '오차장' },
        ].find((p) => p.value === v);
        return found?.label;
      }).filter(Boolean);
      filtered = filtered.filter((c) => pmLabels.includes(c.constructionPM));
    }

    // 작업반장 필터 (다중선택)
    if (filter?.workTeamLeaders && filter.workTeamLeaders.length > 0) {
      const leaderLabels = filter.workTeamLeaders.map((v) => {
        const found = [
          { value: 'leader1', label: '이반장' },
          { value: 'leader2', label: '김반장' },
          { value: 'leader3', label: '박반장' },
          { value: 'leader4', label: '최반장' },
          { value: 'leader5', label: '정반장' },
        ].find((l) => l.value === v);
        return found?.label;
      }).filter(Boolean);
      filtered = filtered.filter((c) => leaderLabels.includes(c.workTeamLeader));
    }

    // 상태 필터 (단일선택)
    if (filter?.status && filter.status !== 'all') {
      filtered = filtered.filter((c) => c.status === filter.status);
    }

    // 정렬
    if (filter?.sortBy) {
      switch (filter.sortBy) {
        case 'latest':
          filtered.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
          break;
        case 'register':
          filtered.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
          break;
        case 'completionDateDesc':
          filtered.sort((a, b) => {
            if (!a.constructionEndDate) return 1;
            if (!b.constructionEndDate) return -1;
            return new Date(b.constructionEndDate).getTime() - new Date(a.constructionEndDate).getTime();
          });
          break;
        case 'partnerNameAsc':
          filtered.sort((a, b) => a.partnerName.localeCompare(b.partnerName, 'ko'));
          break;
        case 'partnerNameDesc':
          filtered.sort((a, b) => b.partnerName.localeCompare(a.partnerName, 'ko'));
          break;
      }
    }

    const page = filter?.page ?? 1;
    const size = filter?.size ?? 1000;
    const start = (page - 1) * size;
    const paginatedItems = filtered.slice(start, start + size);

    return {
      success: true,
      data: {
        items: paginatedItems,
        total: filtered.length,
        page,
        size,
        totalPages: Math.ceil(filtered.length / size),
      },
    };
  } catch (error) {
    console.error('getConstructionManagementList error:', error);
    return { success: false, error: '시공관리 목록 조회에 실패했습니다.' };
  }
}

// 시공관리 통계 조회
export async function getConstructionManagementStats(): Promise<{
  success: boolean;
  data?: ConstructionManagementStats;
  error?: string;
}> {
  try {
    const total = mockConstructionManagements.length;
    const inProgress = mockConstructionManagements.filter((c) => c.status === 'in_progress').length;
    const completed = mockConstructionManagements.filter((c) => c.status === 'completed').length;

    return {
      success: true,
      data: {
        total,
        inProgress,
        completed,
      },
    };
  } catch (error) {
    console.error('getConstructionManagementStats error:', error);
    return { success: false, error: '시공관리 통계 조회에 실패했습니다.' };
  }
}

// 시공관리 상세 조회
export async function getConstructionManagement(
  id: string
): Promise<{ success: boolean; data?: ConstructionManagement; error?: string }> {
  try {
    const item = mockConstructionManagements.find((c) => c.id === id);

    if (!item) {
      return { success: false, error: '시공 정보를 찾을 수 없습니다.' };
    }

    return { success: true, data: item };
  } catch (error) {
    console.error('getConstructionManagement error:', error);
    return { success: false, error: '시공 정보 조회에 실패했습니다.' };
  }
}

// 시공관리 삭제
export async function deleteConstructionManagement(
  _id: string
): Promise<{ success: boolean; error?: string }> {
  return { success: true };
}

// 시공관리 일괄 삭제
export async function deleteConstructionManagements(
  ids: string[]
): Promise<{ success: boolean; deletedCount?: number; error?: string }> {
  try {
    return { success: true, deletedCount: ids.length };
  } catch (error) {
    console.error('deleteConstructionManagements error:', error);
    return { success: false, error: '시공 정보 일괄 삭제에 실패했습니다.' };
  }
}

// ============================================
// 시공 상세 페이지 Server Actions
// ============================================

import type {
  ConstructionManagementDetail,
  ConstructionDetailFormData,
} from './types';

// 시공 상세 목업 데이터
const mockConstructionDetails: Record<string, ConstructionManagementDetail> = {
  cm1: {
    id: 'cm1',
    constructionNumber: '123123',
    siteName: '서울 강남 현장',
    constructionStartDate: '2025-12-15',
    constructionEndDate: null,
    workTeamLeader: '홍길동',
    status: 'in_progress',
    workerInfoList: [
      { id: 'w1', workDate: '2026-01-05', workers: ['홍길동', '김영희'] },
      { id: 'w2', workDate: '2026-01-06', workers: ['홍길동', '이철수'] },
    ],
    workProgressList: [
      { id: 'wp1', scheduleDate: '2026-01-05 12:12', workName: '공과명' },
    ],
    orderNumber: '123123',
    orderId: 'order1',
    issueCount: 0,
    workLogContent: '',
    photos: [],
    isIssueReported: false,
    createdAt: '2025-12-10',
    updatedAt: '2025-12-15',
  },
  cm2: {
    id: 'cm2',
    constructionNumber: '123124',
    siteName: '부산 해운대 현장',
    constructionStartDate: '2025-12-14',
    constructionEndDate: '2025-12-16',
    workTeamLeader: '김반장',
    status: 'completed',
    workerInfoList: [
      { id: 'w3', workDate: '2025-12-14', workers: ['이순신', '강감찬'] },
      { id: 'w4', workDate: '2025-12-15', workers: ['이순신'] },
      { id: 'w5', workDate: '2025-12-16', workers: ['이순신', '강감찬', '을지문덕'] },
    ],
    workProgressList: [
      { id: 'wp2', scheduleDate: '2025-12-14 09:00', workName: '기초 공사' },
      { id: 'wp3', scheduleDate: '2025-12-15 14:00', workName: '배선 작업' },
    ],
    orderNumber: '123124',
    orderId: 'order2',
    issueCount: 2,
    workLogContent: '금일 기초 공사 및 배선 작업 완료. 특이사항 없음.',
    photos: [
      { id: 'p1', url: '/images/sample1.jpg', name: '현장사진1.jpg', uploadedAt: '2025-12-16' },
    ],
    isIssueReported: false,
    createdAt: '2025-12-08',
    updatedAt: '2025-12-16',
  },
  cm3: {
    id: 'cm3',
    constructionNumber: '123125',
    siteName: '대전 유성 현장',
    constructionStartDate: '2025-12-13',
    constructionEndDate: null,
    workTeamLeader: '박반장',
    status: 'in_progress',
    workerInfoList: [
      { id: 'w6', workDate: '2025-12-13', workers: ['강감찬'] },
    ],
    workProgressList: [],
    orderNumber: '123125',
    orderId: 'order3',
    issueCount: 1,
    workLogContent: '',
    photos: [],
    isIssueReported: true,
    createdAt: '2025-12-05',
    updatedAt: '2025-12-13',
  },
};

// 시공 상세 조회
export async function getConstructionManagementDetail(
  id: string
): Promise<{ success: boolean; data?: ConstructionManagementDetail; error?: string }> {
  try {
    // 목업 데이터에서 찾기
    let detail = mockConstructionDetails[id];

    // 없으면 리스트에서 찾아서 기본 상세 데이터 생성
    if (!detail) {
      const listItem = mockConstructionManagements.find((c) => c.id === id);
      if (!listItem) {
        return { success: false, error: '시공 정보를 찾을 수 없습니다.' };
      }

      // 기본 상세 데이터 생성
      detail = {
        id: listItem.id,
        constructionNumber: listItem.constructionNumber,
        siteName: listItem.siteName,
        constructionStartDate: listItem.constructionStartDate,
        constructionEndDate: listItem.constructionEndDate,
        workTeamLeader: listItem.workTeamLeader,
        status: listItem.status,
        workerInfoList: [],
        workProgressList: [],
        orderNumber: listItem.constructionNumber,
        orderId: `order-${listItem.id}`,
        issueCount: 0,
        workLogContent: '',
        photos: [],
        isIssueReported: false,
        createdAt: listItem.createdAt,
        updatedAt: listItem.updatedAt,
      };
    }

    return { success: true, data: detail };
  } catch (error) {
    console.error('getConstructionManagementDetail error:', error);
    return { success: false, error: '시공 상세 조회에 실패했습니다.' };
  }
}

// 시공 상세 수정
export async function updateConstructionManagementDetail(
  _id: string,
  _data: Partial<ConstructionDetailFormData>
): Promise<{ success: boolean; error?: string }> {
  // 실제 구현에서는 DB 업데이트
  return { success: true };
}

// 시공 완료 처리
export async function completeConstruction(
  _id: string
): Promise<{ success: boolean; error?: string }> {
  // 실제 구현에서는 상태를 completed로 변경
  return { success: true };
}