'use server';

import type {
  ProgressBilling,
  ProgressBillingStats,
  ProgressBillingStatus,
  ProgressBillingDetail,
  ProgressBillingDetailFormData,
} from './types';
import { MOCK_PROGRESS_BILLING_DETAIL } from './types';
import { format, subMonths } from 'date-fns';

/**
 * 목업 기성청구 데이터 생성
 */
function generateMockProgressBillings(): ProgressBilling[] {
  const partners = [
    { id: '1', name: '(주)대한건설' },
    { id: '2', name: '삼성물산' },
    { id: '3', name: '현대건설' },
    { id: '4', name: 'GS건설' },
    { id: '5', name: '대림산업' },
  ];

  const sites = [
    { id: '1', name: '강남 오피스빌딩 신축' },
    { id: '2', name: '판교 데이터센터' },
    { id: '3', name: '송도 물류센터' },
    { id: '4', name: '인천공항 터미널' },
    { id: '5', name: '부산항 창고' },
  ];

  const statuses: ProgressBillingStatus[] = ['billing_waiting', 'approval_waiting', 'constructor_sent', 'billing_complete'];

  const billings: ProgressBilling[] = [];
  const baseDate = new Date(2026, 0, 1);

  for (let i = 0; i < 50; i++) {
    const partner = partners[i % partners.length];
    const site = sites[i % sites.length];
    const status = statuses[i % statuses.length];
    const round = (i % 12) + 1;
    const monthOffset = i % 6;
    const billingDate = subMonths(baseDate, monthOffset);

    // 기성 금액 계산 (회차에 따라 누적)
    const baseAmount = 10000000 + (i * 500000);
    const previousBilling = round > 1 ? baseAmount * (round - 1) : 0;
    const currentBilling = baseAmount;
    const cumulativeBilling = previousBilling + currentBilling;

    billings.push({
      id: `billing-${i + 1}`,
      billingNumber: `PB-${2026}-${String(i + 1).padStart(4, '0')}`,
      partnerId: partner.id,
      partnerName: partner.name,
      siteId: site.id,
      siteName: site.name,
      round,
      billingYearMonth: format(billingDate, 'yyyy-MM'),
      previousBilling,
      currentBilling,
      cumulativeBilling,
      status,
      createdAt: format(billingDate, "yyyy-MM-dd'T'HH:mm:ss"),
      updatedAt: format(baseDate, "yyyy-MM-dd'T'HH:mm:ss"),
    });
  }

  return billings;
}

// 캐시된 목업 데이터
let cachedBillings: ProgressBilling[] | null = null;

function getMockBillings(): ProgressBilling[] {
  if (!cachedBillings) {
    cachedBillings = generateMockProgressBillings();
  }
  return cachedBillings;
}

/**
 * 기성청구 목록 조회
 */
export async function getProgressBillingList(params?: {
  size?: number;
  page?: number;
  startDate?: string;
  endDate?: string;
  status?: string;
  partnerIds?: string[];
  siteIds?: string[];
  search?: string;
}): Promise<{
  success: boolean;
  data?: { items: ProgressBilling[]; total: number };
  error?: string;
}> {
  try {
    let billings = getMockBillings();

    // 날짜 필터
    if (params?.startDate && params?.endDate) {
      billings = billings.filter((billing) => {
        const billingDate = billing.billingYearMonth;
        return billingDate >= params.startDate!.slice(0, 7) && billingDate <= params.endDate!.slice(0, 7);
      });
    }

    // 상태 필터
    if (params?.status && params.status !== 'all') {
      billings = billings.filter((billing) => billing.status === params.status);
    }

    // 거래처 필터 (다중선택)
    if (params?.partnerIds && params.partnerIds.length > 0) {
      billings = billings.filter((billing) => params.partnerIds!.includes(billing.partnerId));
    }

    // 현장 필터 (다중선택)
    if (params?.siteIds && params.siteIds.length > 0) {
      billings = billings.filter((billing) => params.siteIds!.includes(billing.siteId));
    }

    // 검색
    if (params?.search) {
      const search = params.search.toLowerCase();
      billings = billings.filter(
        (billing) =>
          billing.billingNumber.toLowerCase().includes(search) ||
          billing.partnerName.toLowerCase().includes(search) ||
          billing.siteName.toLowerCase().includes(search)
      );
    }

    // 페이지네이션
    const page = params?.page || 1;
    const size = params?.size || 1000;
    const start = (page - 1) * size;
    const paginatedBillings = billings.slice(start, start + size);

    return {
      success: true,
      data: {
        items: paginatedBillings,
        total: billings.length,
      },
    };
  } catch {
    return {
      success: false,
      error: '기성청구 목록 조회에 실패했습니다.',
    };
  }
}

/**
 * 기성청구 통계 조회
 */
export async function getProgressBillingStats(): Promise<{
  success: boolean;
  data?: ProgressBillingStats;
  error?: string;
}> {
  try {
    const billings = getMockBillings();

    const stats: ProgressBillingStats = {
      total: billings.length,
      contractWaiting: billings.filter((b) => b.status === 'billing_waiting' || b.status === 'approval_waiting').length,
      contractComplete: billings.filter((b) => b.status === 'billing_complete').length,
    };

    return {
      success: true,
      data: stats,
    };
  } catch {
    return {
      success: false,
      error: '기성청구 통계 조회에 실패했습니다.',
    };
  }
}

/**
 * 기성청구 상세 조회
 */
export async function getProgressBillingDetail(id: string): Promise<{
  success: boolean;
  data?: ProgressBillingDetail;
  error?: string;
}> {
  try {
    // TODO: 실제 API 호출로 대체
    // const response = await apiClient.get(`/progress-billing/${id}`);
    
    // 목업 데이터 반환
    await new Promise((resolve) => setTimeout(resolve, 300));
    
    return {
      success: true,
      data: {
        ...MOCK_PROGRESS_BILLING_DETAIL,
        id,
      },
    };
  } catch (error) {
    console.error('Failed to fetch progress billing detail:', error);
    return {
      success: false,
      error: '기성청구 정보를 불러오는데 실패했습니다.',
    };
  }
}

/**
 * 기성청구 저장 (생성/수정)
 */
export async function saveProgressBilling(
  id: string | null,
  data: ProgressBillingDetailFormData
): Promise<{
  success: boolean;
  data?: ProgressBillingDetail;
  error?: string;
}> {
  try {
    // TODO: 실제 API 호출로 대체
    // const response = id 
    //   ? await apiClient.put(`/progress-billing/${id}`, data)
    //   : await apiClient.post('/progress-billing', data);
    
    await new Promise((resolve) => setTimeout(resolve, 500));
    
    
    return {
      success: true,
      data: {
        ...MOCK_PROGRESS_BILLING_DETAIL,
        id: id || String(Date.now()),
        ...data,
      },
    };
  } catch (error) {
    console.error('Failed to save progress billing:', error);
    return {
      success: false,
      error: '기성청구 저장에 실패했습니다.',
    };
  }
}

/**
 * 기성청구 삭제
 */
export async function deleteProgressBilling(_id: string): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    // TODO: 실제 API 호출로 대체
    // await apiClient.delete(`/progress-billing/${id}`);
    
    await new Promise((resolve) => setTimeout(resolve, 500));
    
    
    return {
      success: true,
    };
  } catch (error) {
    console.error('Failed to delete progress billing:', error);
    return {
      success: false,
      error: '기성청구 삭제에 실패했습니다.',
    };
  }
}

/**
 * 기성청구 상태 변경
 */
export async function updateProgressBillingStatus(
  id: string,
  status: string
): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    // TODO: 실제 API 호출로 대체
    // await apiClient.patch(`/progress-billing/${id}/status`, { status });
    
    await new Promise((resolve) => setTimeout(resolve, 300));
    
    
    // 기성청구완료 시 매출 자동 등록 로직
    if (status === 'completed') {
      // TODO: 매출 자동 등록 API 호출
    }
    
    return {
      success: true,
    };
  } catch (error) {
    console.error('Failed to update progress billing status:', error);
    return {
      success: false,
      error: '상태 변경에 실패했습니다.',
    };
  }
}
