'use server';

import type {
  Estimate,
  EstimateDetail,
  EstimateStats,
  EstimateFilter,
  EstimateListResponse,
  EstimateDetailFormData,
  EstimateSummaryItem,
  ExpenseItem,
  PriceAdjustmentItem,
  PriceAdjustmentData,
  EstimateDetailItem,
  SiteBriefingInfo,
  BidInfo,
} from './types';
import { getEmptyPriceAdjustmentData } from './types';
import { apiClient } from '@/lib/api';
import { formatDate } from '@/lib/utils/date';

/**
 * 건설 프로젝트 - 견적관리 Server Actions
 * quotes API 사용 (quote_type=construction 필터)
 */

// ========================================
// API 응답 타입 (Quotes API)
// ========================================

interface ApiQuote {
  id: number;
  quote_type: string;
  quote_number: string;
  registration_date: string;
  client_id: number | null;
  client_name: string | null;
  site_id: number | null;
  site_name: string | null;
  site_briefing_id: number | null;
  product_category: string | null;
  product_name: string | null;
  total_amount: number | string;
  status: string;
  author: string | null;
  manager: string | null;
  remarks: string | null;
  created_at: string;
  updated_at: string;
  created_by: number | null;
  // 연관 데이터
  items?: ApiQuoteItem[];
  site_briefing?: ApiSiteBriefing;
  // 옵션 데이터 (JSON)
  options?: ApiQuoteOptions;
}

interface ApiQuoteOptions {
  summary_items?: ApiSummaryItem[];
  expense_items?: ApiExpenseItem[];
  price_adjustments?: ApiPriceAdjustment[];
  price_adjustment_data?: ApiPriceAdjustmentData;
  detail_items?: ApiDetailItem[];
}

// 견적 상세 항목 (API 응답용)
interface ApiDetailItem {
  id: string;
  no: number;
  name: string;
  material: string;
  width: number;
  height: number;
  quantity: number;
  box: number;
  assembly: number;
  coating: number;
  batting: number;
  mounting: number;
  fitting: number;
  controller: number;
  width_construction: number;
  height_construction: number;
  material_cost: number;
  labor_cost: number;
  quantity_price: number;
  expense_quantity: number;
  expense_total: number;
  total_cost: number;
  other_cost: number;
  margin_cost: number;
  total_price: number;
  unit_price: number;
  expense: number;
  margin_rate: number;
  unit_quantity: number;
  expense_result: number;
  margin_actual: number;
  // 계산 필드
  calc_weight?: number;
  calc_area?: number;
  calc_steel_screen?: number;
  calc_caulking?: number;
  calc_rail?: number;
  calc_bottom?: number;
  calc_box_reinforce?: number;
  calc_shaft?: number;
  calc_unit_price?: number;
  calc_expense?: number;
  // 조정단가 필드
  adjusted_caulking?: number;
  adjusted_rail?: number;
  adjusted_bottom?: number;
  adjusted_box_reinforce?: number;
  adjusted_shaft?: number;
  adjusted_painting?: number;
  adjusted_motor?: number;
  adjusted_controller?: number;
}

// 품목 단가 조정 (신규 구조) - API 응답용
interface ApiPriceAdjustmentData {
  caulking?: ApiPriceAdjustmentItemPrice;
  rail?: ApiPriceAdjustmentItemPrice;
  bottom?: ApiPriceAdjustmentItemPrice;
  boxReinforce?: ApiPriceAdjustmentItemPrice;
  shaft?: ApiPriceAdjustmentItemPrice;
  painting?: ApiPriceAdjustmentItemPrice;
  motor?: ApiPriceAdjustmentItemPrice;
  controller?: ApiPriceAdjustmentItemPrice;
}

interface ApiPriceAdjustmentItemPrice {
  purchasePrice: number;
  marginRate: number;
  sellingPrice: number;
  adjustedPrice: number;
}

interface ApiSummaryItem {
  id: string;
  name: string;
  quantity: number;
  unit: string;
  material_cost: number;
  labor_cost: number;
  total_cost: number;
  remarks?: string;
}

interface ApiExpenseItem {
  id: string;
  name: string;
  amount: number;
}

interface ApiPriceAdjustment {
  id: string;
  category: string;
  unit_price: number;
  coating: number;
  batting: number;
  box_reinforce: number;
  painting: number;
  total: number;
}

interface ApiQuoteItem {
  id: number;
  item_code: string;
  item_name: string;
  specification: string | null;
  unit: string;
  base_quantity: number;
  calculated_quantity: number;
  unit_price: number;
  total_price: number;
  formula: string | null;
  note: string | null;
  sort_order: number;
}

interface ApiSiteBriefing {
  id: number;
  briefing_code: string;
  title: string;
  description: string | null;
  briefing_date: string;
  briefing_time: string | null;
  location: string | null;
  address: string | null;
  status: string;
  bid_status: string;
  bid_date: string | null;
  attendance_status: string;
  attendees: Array<{ name: string; department?: string }> | null;
  attendee_count: number;
  site_count: number;
  construction_start_date: string | null;
  construction_end_date: string | null;
  vat_type: string;
  partner?: {
    id: number;
    name: string;
  };
}

interface _ApiQuoteStats {
  total_count: number;
  pending_count: number;
  completed_count: number;
}

// Legacy API types (for backward compatibility)
interface _ApiSiteBriefingInfo {
  briefing_code: string;
  partner_name: string;
  company_name: string;
  briefing_date: string;
  attendee: string;
}

interface _ApiBidInfo {
  project_name: string;
  bid_date: string;
  site_count: number;
  construction_period: string;
  construction_start_date: string;
  construction_end_date: string;
  vat_type: string;
  work_report: string;
  documents: ApiBidDocument[];
}

interface ApiBidDocument {
  id: number;
  file_name: string;
  file_url: string;
  file_size: number;
}

// ========================================
// 타입 변환 함수
// ========================================

/**
 * API 응답 (Quote) → Estimate 타입 변환
 * 기존 프론트엔드 타입과 호환성 유지
 */
function transformQuoteToEstimate(apiData: ApiQuote): Estimate {
  const status = mapQuoteStatusToEstimateStatus(apiData.status);

  // 완료 상태인 경우 updated_at을 완료일로 사용
  // (상태가 완료로 변경될 때 updated_at이 갱신되므로)
  const completedDate = status === 'completed' && apiData.updated_at
    ? formatDate(apiData.updated_at) // ISO 형식에서 날짜만 추출
    : null;

  return {
    id: String(apiData.id),
    estimateCode: apiData.quote_number || '',
    partnerId: apiData.client_id ? String(apiData.client_id) : '',
    partnerName: apiData.client_name || '',
    projectName: apiData.site_name || '',
    estimatorId: apiData.created_by ? String(apiData.created_by) : '',
    estimatorName: apiData.author || '',
    estimateCompanyManager: '', // API에서 제공 시 매핑 필요
    estimateCompanyManagerContact: '', // API에서 제공 시 매핑 필요
    itemCount: apiData.items?.length || 0,
    estimateAmount: Number(apiData.total_amount) || 0,
    completedDate,
    bidDate: apiData.registration_date || null,
    status,
    createdAt: apiData.created_at || '',
    updatedAt: apiData.updated_at || '',
    createdBy: apiData.created_by ? String(apiData.created_by) : '',
  };
}

/**
 * Quote 상태 → Estimate 상태 매핑
 */
function mapQuoteStatusToEstimateStatus(
  quoteStatus: string
): 'pending' | 'approval_waiting' | 'completed' | 'rejected' | 'hold' {
  const statusMap: Record<string, 'pending' | 'approval_waiting' | 'completed' | 'rejected' | 'hold'> = {
    pending: 'pending',
    draft: 'pending',
    sent: 'approval_waiting',
    approved: 'completed',
    rejected: 'rejected',
    finalized: 'completed',
    converted: 'completed',
  };
  return statusMap[quoteStatus] || 'pending';
}

/**
 * API 응답 → EstimateDetail 타입 변환
 */
function transformQuoteToEstimateDetail(apiData: ApiQuote): EstimateDetail {
  const base = transformQuoteToEstimate(apiData);
  const sb = apiData.site_briefing;

  // 참석자 정보 변환
  const attendeeNames = sb?.attendees
    ? sb.attendees.map((a) => a.name).join(', ')
    : '';

  // 공사기간 문자열 생성
  const constructionPeriod =
    sb?.construction_start_date && sb?.construction_end_date
      ? `${sb.construction_start_date} ~ ${sb.construction_end_date}`
      : '';

  const siteBriefing: SiteBriefingInfo = sb
    ? {
        briefingCode: sb.briefing_code || '',
        partnerName: sb.partner?.name || '',
        companyName: sb.partner?.name || '',
        briefingDate: sb.briefing_date || '',
        attendee: attendeeNames,
      }
    : { briefingCode: '', partnerName: '', companyName: '', briefingDate: '', attendee: '' };

  const bidInfo: BidInfo = {
    projectName: sb?.title || apiData.site_name || '',
    bidDate: sb?.bid_date || apiData.registration_date || '',
    siteCount: sb?.site_count || 0,
    constructionPeriod,
    constructionStartDate: sb?.construction_start_date || '',
    constructionEndDate: sb?.construction_end_date || '',
    vatType: (sb?.vat_type as 'excluded' | 'included') || 'excluded',
    workReport: sb?.description || '',
    documents: [],
  };

  // options에서 데이터 변환
  const opts = apiData.options;

  const summaryItems: EstimateSummaryItem[] = (opts?.summary_items || []).map((item) => ({
    id: item.id,
    name: item.name,
    quantity: item.quantity,
    unit: item.unit,
    materialCost: item.material_cost,
    laborCost: item.labor_cost,
    totalCost: item.total_cost,
    remarks: item.remarks || '',
  }));

  const expenseItems: ExpenseItem[] = (opts?.expense_items || []).map((item) => ({
    id: item.id,
    name: item.name,
    amount: item.amount,
  }));

  const priceAdjustments: PriceAdjustmentItem[] = (opts?.price_adjustments || []).map((item) => ({
    id: item.id,
    category: item.category,
    unitPrice: item.unit_price,
    coating: item.coating,
    batting: item.batting,
    boxReinforce: item.box_reinforce,
    painting: item.painting,
    total: item.total,
  }));

  // 품목 단가 조정 (신규 구조) - API 응답에서 변환
  const priceAdjustmentData: PriceAdjustmentData = opts?.price_adjustment_data
    ? {
        caulking: opts.price_adjustment_data.caulking || getEmptyPriceAdjustmentData().caulking,
        rail: opts.price_adjustment_data.rail || getEmptyPriceAdjustmentData().rail,
        bottom: opts.price_adjustment_data.bottom || getEmptyPriceAdjustmentData().bottom,
        boxReinforce: opts.price_adjustment_data.boxReinforce || getEmptyPriceAdjustmentData().boxReinforce,
        shaft: opts.price_adjustment_data.shaft || getEmptyPriceAdjustmentData().shaft,
        painting: opts.price_adjustment_data.painting || getEmptyPriceAdjustmentData().painting,
        motor: opts.price_adjustment_data.motor || getEmptyPriceAdjustmentData().motor,
        controller: opts.price_adjustment_data.controller || getEmptyPriceAdjustmentData().controller,
      }
    : getEmptyPriceAdjustmentData();

  // 견적 상세 항목 - options.detail_items 우선 사용 (저장된 전체 데이터)
  // 없으면 quote_items 테이블에서 기본 정보만 가져옴
  const detailItems: EstimateDetailItem[] = opts?.detail_items
    ? opts.detail_items.map((item) => ({
        id: item.id,
        no: item.no,
        name: item.name,
        material: item.material,
        width: item.width ?? 0,
        height: item.height ?? 0,
        quantity: item.quantity ?? 0,
        box: item.box ?? 0,
        assembly: item.assembly ?? 0,
        coating: item.coating ?? 0,
        batting: item.batting ?? 0,
        mounting: item.mounting ?? 0,
        fitting: item.fitting ?? 0,
        controller: item.controller ?? 0,
        widthConstruction: item.width_construction ?? 0,
        heightConstruction: item.height_construction ?? 0,
        materialCost: item.material_cost ?? 0,
        laborCost: item.labor_cost ?? 0,
        quantityPrice: item.quantity_price ?? 0,
        expenseQuantity: item.expense_quantity ?? 0,
        expenseTotal: item.expense_total ?? 0,
        totalCost: item.total_cost ?? 0,
        otherCost: item.other_cost ?? 0,
        marginCost: item.margin_cost ?? 0,
        totalPrice: item.total_price ?? 0,
        unitPrice: item.unit_price ?? 0,
        expense: item.expense ?? 0,
        marginRate: item.margin_rate ?? 0,
        unitQuantity: item.unit_quantity ?? 0,
        expenseResult: item.expense_result ?? 0,
        marginActual: item.margin_actual ?? 0,
        // 계산 필드
        calcWeight: item.calc_weight,
        calcArea: item.calc_area,
        calcSteelScreen: item.calc_steel_screen,
        calcCaulking: item.calc_caulking,
        calcRail: item.calc_rail,
        calcBottom: item.calc_bottom,
        calcBoxReinforce: item.calc_box_reinforce,
        calcShaft: item.calc_shaft,
        calcUnitPrice: item.calc_unit_price,
        calcExpense: item.calc_expense,
        // 조정단가 필드
        adjustedCaulking: item.adjusted_caulking,
        adjustedRail: item.adjusted_rail,
        adjustedBottom: item.adjusted_bottom,
        adjustedBoxReinforce: item.adjusted_box_reinforce,
        adjustedShaft: item.adjusted_shaft,
        adjustedPainting: item.adjusted_painting,
        adjustedMotor: item.adjusted_motor,
        adjustedController: item.adjusted_controller,
      }))
    : (apiData.items || []).map((item, index) => ({
        id: String(item.id),
        no: index + 1,
        name: item.item_name || '',
        material: item.specification || '',
        width: 0,
        height: 0,
        quantity: item.calculated_quantity || 0,
        box: 0,
        assembly: 0,
        coating: 0,
        batting: 0,
        mounting: 0,
        fitting: 0,
        controller: 0,
        widthConstruction: 0,
        heightConstruction: 0,
        materialCost: 0,
        laborCost: 0,
        quantityPrice: item.unit_price || 0,
        expenseQuantity: 0,
        expenseTotal: 0,
        totalCost: item.total_price || 0,
        otherCost: 0,
        marginCost: 0,
        totalPrice: item.total_price || 0,
        unitPrice: item.unit_price || 0,
        expense: 0,
        marginRate: 0,
        unitQuantity: item.base_quantity || 0,
        expenseResult: 0,
        marginActual: 0,
      }));

  return {
    ...base,
    siteBriefing,
    bidInfo,
    summaryItems,
    expenseItems,
    priceAdjustments,
    priceAdjustmentData,
    detailItems,
  };
}

/**
 * EstimateDetailFormData → API 요청 데이터 변환
 */
function transformToApiRequest(data: Partial<EstimateDetailFormData>): Record<string, unknown> {
  const apiData: Record<string, unknown> = {};

  if (data.estimateCode !== undefined) apiData.quote_number = data.estimateCode;
  if (data.estimatorId !== undefined) apiData.created_by = data.estimatorId || null;
  if (data.estimatorName !== undefined) apiData.author = data.estimatorName || null;
  if (data.estimateAmount !== undefined) apiData.total_amount = data.estimateAmount;
  if (data.status !== undefined) {
    // Estimate 상태 → Quote 상태 역매핑
    const reverseStatusMap: Record<string, string> = {
      pending: 'pending',
      approval_waiting: 'sent',
      completed: 'finalized',
      rejected: 'rejected',
      hold: 'draft',
    };
    apiData.status = reverseStatusMap[data.status] || 'pending';
  }

  if (data.bidInfo !== undefined) {
    apiData.site_name = data.bidInfo.projectName;
    apiData.registration_date = data.bidInfo.bidDate;
  }

  // options 데이터 역변환
  const options: Record<string, unknown> = {};

  if (data.summaryItems !== undefined) {
    options.summary_items = data.summaryItems.map((item) => ({
      id: item.id,
      name: item.name,
      quantity: item.quantity,
      unit: item.unit,
      material_cost: item.materialCost,
      labor_cost: item.laborCost,
      total_cost: item.totalCost,
      remarks: item.remarks,
    }));
  }

  if (data.expenseItems !== undefined) {
    options.expense_items = data.expenseItems.map((item) => ({
      id: item.id,
      name: item.name,
      amount: item.amount,
    }));
  }

  if (data.priceAdjustments !== undefined) {
    options.price_adjustments = data.priceAdjustments.map((item) => ({
      id: item.id,
      category: item.category,
      unit_price: item.unitPrice,
      coating: item.coating,
      batting: item.batting,
      box_reinforce: item.boxReinforce,
      painting: item.painting,
      total: item.total,
    }));
  }

  // 품목 단가 조정 (신규 구조) 저장
  if (data.priceAdjustmentData !== undefined) {
    options.price_adjustment_data = data.priceAdjustmentData;
  }

  // 견적 상세 (detailItems) 저장
  if (data.detailItems !== undefined && data.detailItems.length > 0) {
    options.detail_items = data.detailItems.map((item, index) => ({
      id: item.id,
      no: item.no ?? index + 1,
      name: item.name,
      material: item.material,
      width: item.width,
      height: item.height,
      quantity: item.quantity,
      box: item.box,
      assembly: item.assembly,
      coating: item.coating,
      batting: item.batting,
      mounting: item.mounting,
      fitting: item.fitting,
      controller: item.controller,
      width_construction: item.widthConstruction,
      height_construction: item.heightConstruction,
      material_cost: item.materialCost,
      labor_cost: item.laborCost,
      quantity_price: item.quantityPrice,
      expense_quantity: item.expenseQuantity,
      expense_total: item.expenseTotal,
      total_cost: item.totalCost,
      other_cost: item.otherCost,
      margin_cost: item.marginCost,
      total_price: item.totalPrice,
      unit_price: item.unitPrice,
      expense: item.expense,
      margin_rate: item.marginRate,
      unit_quantity: item.unitQuantity,
      expense_result: item.expenseResult,
      margin_actual: item.marginActual,
      // 계산 필드
      calc_weight: item.calcWeight,
      calc_area: item.calcArea,
      calc_steel_screen: item.calcSteelScreen,
      calc_caulking: item.calcCaulking,
      calc_rail: item.calcRail,
      calc_bottom: item.calcBottom,
      calc_box_reinforce: item.calcBoxReinforce,
      calc_shaft: item.calcShaft,
      calc_unit_price: item.calcUnitPrice,
      calc_expense: item.calcExpense,
      // 조정단가 필드
      adjusted_caulking: item.adjustedCaulking,
      adjusted_rail: item.adjustedRail,
      adjusted_bottom: item.adjustedBottom,
      adjusted_box_reinforce: item.adjustedBoxReinforce,
      adjusted_shaft: item.adjustedShaft,
      adjusted_painting: item.adjustedPainting,
      adjusted_motor: item.adjustedMotor,
      adjusted_controller: item.adjustedController,
    }));
  }

  if (Object.keys(options).length > 0) {
    apiData.options = options;
  }

  return apiData;
}

// ========================================
// API 함수 (quotes API 사용)
// ========================================

/**
 * 건설 견적 목록 조회
 * GET /api/v1/quotes?quote_type=construction
 */
export async function getEstimateList(filter?: EstimateFilter): Promise<{
  success: boolean;
  data?: EstimateListResponse;
  error?: string;
}> {
  try {
    const queryParams: Record<string, string> = {
      quote_type: 'construction', // 건설 견적만 조회
    };

    // 검색
    if (filter?.search) queryParams.q = filter.search;

    // 필터
    if (filter?.status && filter.status !== 'all') {
      // Estimate 상태 → Quote 상태로 변환
      const statusMap: Record<string, string> = {
        pending: 'pending',
        approval_waiting: 'sent',
        completed: 'finalized',
        rejected: 'rejected',
        hold: 'draft',
      };
      queryParams.status = statusMap[filter.status] || filter.status;
    }
    if (filter?.partnerId) queryParams.client_id = filter.partnerId;

    // 날짜 범위
    if (filter?.startDate) queryParams.date_from = filter.startDate;
    if (filter?.endDate) queryParams.date_to = filter.endDate;

    // 페이지네이션
    if (filter?.page) queryParams.page = String(filter.page);
    if (filter?.size) queryParams.size = String(filter.size);

    // 정렬
    if (filter?.sortBy) {
      const sortMap: Record<string, { field: string; dir: string }> = {
        latest: { field: 'created_at', dir: 'desc' },
        oldest: { field: 'created_at', dir: 'asc' },
        amountDesc: { field: 'total_amount', dir: 'desc' },
        amountAsc: { field: 'total_amount', dir: 'asc' },
        bidDateDesc: { field: 'registration_date', dir: 'desc' },
        partnerNameAsc: { field: 'client_name', dir: 'asc' },
        partnerNameDesc: { field: 'client_name', dir: 'desc' },
        projectNameAsc: { field: 'site_name', dir: 'asc' },
        projectNameDesc: { field: 'site_name', dir: 'desc' },
      };
      const sort = sortMap[filter.sortBy];
      if (sort) {
        queryParams.sort_by = sort.field;
        queryParams.sort_order = sort.dir;
      }
    }

    const response = await apiClient.get<{
      success: boolean;
      data: {
        data: ApiQuote[];
        current_page: number;
        per_page: number;
        total: number;
        last_page: number;
      };
    }>('/quotes', { params: queryParams });

    const paginatedData = response.data;
    const items = (paginatedData.data || []).map(transformQuoteToEstimate);

    return {
      success: true,
      data: {
        items,
        total: paginatedData.total || 0,
        page: paginatedData.current_page || 1,
        size: paginatedData.per_page || 20,
        totalPages: paginatedData.last_page || 1,
      },
    };
  } catch (error) {
    console.error('견적 목록 조회 오류:', error);
    return { success: false, error: '견적 목록을 불러오는데 실패했습니다.' };
  }
}

/**
 * 견적 단건 조회
 * GET /api/v1/quotes/{id}
 */
export async function getEstimate(id: string): Promise<{
  success: boolean;
  data?: Estimate;
  error?: string;
}> {
  try {
    const response = await apiClient.get<{ success: boolean; data: ApiQuote }>(`/quotes/${id}`);
    return { success: true, data: transformQuoteToEstimate(response.data) };
  } catch (error) {
    console.error('견적 조회 오류:', error);
    return { success: false, error: '견적 정보를 찾을 수 없습니다.' };
  }
}

/**
 * 견적 상세 조회 (첨부 정보 포함)
 * GET /api/v1/quotes/{id}
 */
export async function getEstimateDetail(id: string): Promise<{
  success: boolean;
  data?: EstimateDetail;
  error?: string;
}> {
  try {
    const response = await apiClient.get<{ success: boolean; data: ApiQuote }>(`/quotes/${id}`);
    
    // 🔍 디버깅: 로드된 데이터 확인
    
    const transformed = transformQuoteToEstimateDetail(response.data);
    
    
    return { success: true, data: transformed };
  } catch (error) {
    console.error('❌ 견적 상세 조회 오류:', error);
    return { success: false, error: '견적 상세 정보를 불러오는데 실패했습니다.' };
  }
}

/**
 * 견적 통계 조회
 * GET /api/v1/quotes/stats (건설용)
 * 현재는 목록 조회로 대체
 */
export async function getEstimateStats(): Promise<{
  success: boolean;
  data?: EstimateStats;
  error?: string;
}> {
  try {
    // 통계 API가 없으므로 목록 조회로 대체
    const [allResponse, pendingResponse] = await Promise.all([
      apiClient.get<{ success: boolean; data: { total: number } }>('/quotes', {
        params: { quote_type: 'construction', size: '1' },
      }),
      apiClient.get<{ success: boolean; data: { total: number } }>('/quotes', {
        params: { quote_type: 'construction', status: 'pending', size: '1' },
      }),
    ]);

    const total = allResponse.data?.total || 0;
    const pending = pendingResponse.data?.total || 0;

    return {
      success: true,
      data: {
        total,
        pending,
        completed: total - pending,
      },
    };
  } catch (error) {
    console.error('견적 통계 조회 오류:', error);
    return { success: false, error: '통계를 불러오는데 실패했습니다.' };
  }
}

/**
 * 견적 등록
 * POST /api/v1/quotes
 */
export async function createEstimate(data: EstimateDetailFormData): Promise<{
  success: boolean;
  data?: Estimate;
  error?: string;
}> {
  try {
    const apiData = {
      ...transformToApiRequest(data),
      quote_type: 'construction', // 건설 견적으로 생성
    };
    const response = await apiClient.post<ApiQuote>('/quotes', apiData);
    return { success: true, data: transformQuoteToEstimate(response) };
  } catch (error) {
    console.error('견적 등록 오류:', error);
    return { success: false, error: '견적 등록에 실패했습니다.' };
  }
}

/**
 * 견적 수정
 * PUT /api/v1/quotes/{id}
 */
export async function updateEstimate(
  id: string,
  data: Partial<EstimateDetailFormData>
): Promise<{
  success: boolean;
  data?: Estimate;
  error?: string;
}> {
  try {
    const apiData = transformToApiRequest(data);
    
    // 🔍 디버깅: 저장 데이터 확인
    
    const response = await apiClient.put<ApiQuote>(`/quotes/${id}`, apiData);
    
    
    return { success: true, data: transformQuoteToEstimate(response) };
  } catch (error) {
    console.error('❌ 견적 수정 오류:', error);
    return { success: false, error: '견적 수정에 실패했습니다.' };
  }
}

/**
 * 견적 삭제
 * DELETE /api/v1/quotes/{id}
 */
export async function deleteEstimate(id: string): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    await apiClient.delete(`/quotes/${id}`);
    return { success: true };
  } catch (error) {
    console.error('견적 삭제 오류:', error);
    return { success: false, error: '견적 삭제에 실패했습니다.' };
  }
}

/**
 * 견적 일괄 삭제
 * DELETE /api/v1/quotes/bulk
 */
export async function deleteEstimates(ids: string[]): Promise<{
  success: boolean;
  deletedCount?: number;
  error?: string;
}> {
  try {
    await apiClient.delete('/quotes/bulk', {
      data: { ids: ids.map((id) => Number(id)) },
    });
    return { success: true, deletedCount: ids.length };
  } catch (error) {
    console.error('견적 일괄 삭제 오류:', error);
    return { success: false, error: '일괄 삭제에 실패했습니다.' };
  }
}

// ========================================
// 공과 품목 조회 (Items API)
// ========================================

/**
 * 공과 품목 옵션
 */
export interface ExpenseItemOption {
  value: string; // 품목 ID
  label: string; // 품목명
  code: string; // 품목코드
  unit: string; // 단위
}

/**
 * 공과 품목 목록 조회
 * GET /api/v1/items?type=RM
 * 품목관리에서 item_type='RM' (공과) 인 품목만 조회
 */
export async function getExpenseItemOptions(): Promise<{
  success: boolean;
  data?: ExpenseItemOption[];
  error?: string;
}> {
  try {
    const response = await apiClient.get<{
      success: boolean;
      message: string;
      data: {
        data: Array<{
          id: number;
          code: string;
          name: string;
          unit: string | null;
          item_type: string;
          is_active: boolean;
        }>;
        current_page: number;
        per_page: number;
        total: number;
      };
    }>('/items', {
      params: {
        item_type: 'RM', // 공과 품목만 조회
        active: '1', // 활성 품목만
        size: '100', // 충분한 수량
      },
    });

    // API 응답: { success, message, data: { data: [...items], current_page, ... } }
    const paginatedData = response.data;
    const items = Array.isArray(paginatedData.data) ? paginatedData.data : [];
    const options: ExpenseItemOption[] = items.map((item) => ({
      value: String(item.id),
      label: item.name,
      code: item.code,
      unit: item.unit || 'EA',
    }));

    return { success: true, data: options };
  } catch (error) {
    console.error('공과 품목 목록 조회 오류:', error);
    return { success: false, error: '공과 품목 목록을 불러오는데 실패했습니다.' };
  }
}

// ==================== 공통코드/거래처/사용자 API ====================

/**
 * 공통코드 옵션 타입
 */
export interface CommonCodeOption {
  value: string;
  label: string;
  code: string;
  price?: number;
  attributes?: Record<string, unknown>;
}

/**
 * 특정 그룹의 공통코드 목록 조회
 * GET /api/v1/settings/common/{group}
 */
export async function getCommonCodes(group: string): Promise<{
  success: boolean;
  data?: CommonCodeOption[];
  error?: string;
}> {
  try {
    const response = await apiClient.get<{
      success: boolean;
      message: string;
      data: Array<{
        id: number;
        code: string;
        name: string;
        attributes: string | null;
        sort_order: number;
      }>;
    }>(`/settings/common/${group}`);

    const items = Array.isArray(response.data) ? response.data : [];
    const options: CommonCodeOption[] = items.map((item) => {
      const attrs = item.attributes ? JSON.parse(item.attributes) : {};
      return {
        value: attrs.price !== undefined ? String(attrs.price) : item.code,
        label: item.name,
        code: item.code,
        price: attrs.price,
        attributes: attrs,
      };
    });

    return { success: true, data: options };
  } catch (error) {
    console.error(`공통코드(${group}) 목록 조회 오류:`, error);
    return { success: false, error: `공통코드(${group}) 목록을 불러오는데 실패했습니다.` };
  }
}

/**
 * 거래처 옵션 타입
 */
export interface ClientOption {
  value: string;
  label: string;
}

/**
 * 거래처 목록 조회 (셀렉트 옵션용)
 * GET /api/v1/clients
 */
export async function getClientOptions(): Promise<{
  success: boolean;
  data?: ClientOption[];
  error?: string;
}> {
  try {
    const response = await apiClient.get<{
      success: boolean;
      message: string;
      data: {
        data: Array<{
          id: number;
          name: string;
          code?: string;
        }>;
      };
    }>('/clients', {
      params: {
        active: '1',
        size: '100',
      },
    });

    const paginatedData = response.data;
    const items = Array.isArray(paginatedData.data) ? paginatedData.data : [];
    const options: ClientOption[] = items.map((item) => ({
      value: String(item.id),
      label: item.name,
    }));

    return { success: true, data: options };
  } catch (error) {
    console.error('거래처 목록 조회 오류:', error);
    return { success: false, error: '거래처 목록을 불러오는데 실패했습니다.' };
  }
}

/**
 * 사용자 옵션 타입
 */
export interface UserOption {
  value: string;
  label: string;
}

/**
 * 사용자 목록 조회 (견적자 셀렉트 옵션용)
 * GET /api/v1/users
 */
export async function getUserOptions(): Promise<{
  success: boolean;
  data?: UserOption[];
  error?: string;
}> {
  try {
    const response = await apiClient.get<{
      success: boolean;
      message: string;
      data: {
        data: Array<{
          id: number;
          name: string;
          email?: string;
        }>;
      };
    }>('/users/index', {
      params: {
        active: '1',
        per_page: '100',
      },
    });

    const paginatedData = response.data;
    const items = Array.isArray(paginatedData.data) ? paginatedData.data : [];
    const options: UserOption[] = items.map((item) => ({
      value: String(item.id),
      label: item.name,
    }));

    return { success: true, data: options };
  } catch (error) {
    console.error('사용자 목록 조회 오류:', error);
    return { success: false, error: '사용자 목록을 불러오는데 실패했습니다.' };
  }
}

/**
 * 견적서 옵션 데이터 일괄 조회
 * 제품, 도장, 모터, 제어기, 시공비 등 모든 셀렉트 옵션
 */
export interface EstimateOptionsData {
  materials: CommonCodeOption[];
  paintings: CommonCodeOption[];
  motors: CommonCodeOption[];
  controllers: CommonCodeOption[];
  widthConstructions: CommonCodeOption[];
  heightConstructions: CommonCodeOption[];
}

export async function getEstimateOptions(): Promise<{
  success: boolean;
  data?: EstimateOptionsData;
  error?: string;
}> {
  try {
    const [materials, paintings, motors, controllers, widthConstructions, heightConstructions] =
      await Promise.all([
        getCommonCodes('material_type'),
        getCommonCodes('painting_type'),
        getCommonCodes('motor_type'),
        getCommonCodes('controller_type'),
        getCommonCodes('width_construction_cost'),
        getCommonCodes('height_construction_cost'),
      ]);

    return {
      success: true,
      data: {
        materials: materials.data || [],
        paintings: paintings.data || [],
        motors: motors.data || [],
        controllers: controllers.data || [],
        widthConstructions: widthConstructions.data || [],
        heightConstructions: heightConstructions.data || [],
      },
    };
  } catch (error) {
    console.error('견적서 옵션 일괄 조회 오류:', error);
    return { success: false, error: '견적서 옵션을 불러오는데 실패했습니다.' };
  }
}

// ========================================
// 회사 정보 조회 (Tenant API)
// ========================================

/**
 * 회사 정보 타입 (견적서용)
 */
export interface CompanyInfo {
  companyName: string;
  representativeName: string;
  address: string;
  phone: string;
  fax: string;
  email: string;
  managerName: string;
  managerPhone: string;
}

/**
 * 회사 정보 조회 (견적서 모달용)
 * GET /api/v1/tenants
 */
export async function getCompanyInfo(): Promise<{
  success: boolean;
  data?: CompanyInfo;
  error?: string;
}> {
  try {
    const response = await apiClient.get<{
      success: boolean;
      message: string;
      data: {
        id: number;
        company_name: string;
        ceo_name?: string;
        email?: string;
        phone?: string;
        fax?: string;
        address?: string;
        options?: {
          manager_name?: string;
          address_detail?: string;
          zip_code?: string;
        };
      };
    }>('/tenants');

    const tenant = response.data;
    const opts = tenant.options || {};

    // 주소 조합: 우편번호 + 주소 + 상세주소
    const fullAddress = [opts.zip_code, tenant.address, opts.address_detail]
      .filter(Boolean)
      .join(' ');

    return {
      success: true,
      data: {
        companyName: tenant.company_name || '',
        representativeName: tenant.ceo_name || '',
        address: fullAddress || tenant.address || '',
        phone: tenant.phone || '',
        fax: tenant.fax || '',
        email: tenant.email || '',
        managerName: opts.manager_name || '',
        managerPhone: tenant.phone || '',
      },
    };
  } catch (error) {
    console.error('회사 정보 조회 오류:', error);
    return { success: false, error: '회사 정보를 불러오는데 실패했습니다.' };
  }
}