/**
 * Dealer Claim API Service
 * Handles API calls for dealer claim management operations
 */

import apiClient from './authApi';

export interface CreateClaimRequestPayload {
  activityName: string;
  activityType: string;
  dealerCode: string;
  dealerName: string;
  dealerEmail?: string;
  dealerPhone?: string;
  dealerAddress?: string;
  activityDate?: string; // ISO date string
  location: string;
  requestDescription: string;
  periodStartDate?: string; // ISO date string
  periodEndDate?: string; // ISO date string
  estimatedBudget?: string | number;
  approvers?: Array<{
    email: string;
    name?: string;
    userId?: string;
    level: number;
    tat?: number | string;
    tatType?: 'hours' | 'days';
  }>;
}

export interface ClaimRequestResponse {
  request: {
    requestId: string;
    requestNumber: string;
    title: string;
    description: string;
    status: string;
    workflowType: string;
    // ... other fields
  };
  message: string;
}

/**
 * Create a new dealer claim request
 * POST /api/v1/dealer-claims
 */
export async function createClaimRequest(payload: CreateClaimRequestPayload): Promise<ClaimRequestResponse> {
  try {
    const response = await apiClient.post('/dealer-claims', payload);
    return response.data?.data || response.data;
  } catch (error: any) {
    console.error('[DealerClaimAPI] Error creating claim request:', error);
    throw error;
  }
}

/**
 * Get claim details
 * GET /api/v1/dealer-claims/:requestId
 */
export async function getClaimDetails(requestId: string): Promise<any> {
  try {
    const response = await apiClient.get(`/dealer-claims/${requestId}`);
    return response.data?.data || response.data;
  } catch (error: any) {
    console.error('[DealerClaimAPI] Error fetching claim details:', error);
    throw error;
  }
}

/**
 * Submit dealer proposal (Step 1)
 * POST /api/v1/dealer-claims/:requestId/proposal
 */
export async function submitProposal(
  requestId: string,
  proposalData: {
    proposalDocument?: File;
    costBreakup?: Array<{
      description: string;
      amount: number;
      hsnCode?: string;
      isService?: boolean;
      quantity?: number;
      gstRate?: number;
      gstAmt?: number;
      cgstRate?: number;
      cgstAmt?: number;
      sgstRate?: number;
      sgstAmt?: number;
      igstRate?: number;
      igstAmt?: number;
      totalAmt?: number;
    }>;
    totalEstimatedBudget?: number;
    timelineMode?: 'date' | 'days';
    expectedCompletionDate?: string;
    expectedCompletionDays?: number;
    dealerComments?: string;
  }
): Promise<any> {
  try {
    const formData = new FormData();

    if (proposalData.proposalDocument) {
      formData.append('proposalDocument', proposalData.proposalDocument);
    }

    if (proposalData.costBreakup) {
      formData.append('costBreakup', JSON.stringify(proposalData.costBreakup));
    }

    if (proposalData.totalEstimatedBudget !== undefined) {
      formData.append('totalEstimatedBudget', proposalData.totalEstimatedBudget.toString());
    }

    if (proposalData.timelineMode) {
      formData.append('timelineMode', proposalData.timelineMode);
    }

    if (proposalData.expectedCompletionDate) {
      formData.append('expectedCompletionDate', proposalData.expectedCompletionDate);
    }

    if (proposalData.expectedCompletionDays !== undefined) {
      formData.append('expectedCompletionDays', proposalData.expectedCompletionDays.toString());
    }

    if (proposalData.dealerComments) {
      formData.append('dealerComments', proposalData.dealerComments);
    }

    const response = await apiClient.post(`/dealer-claims/${requestId}/proposal`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });

    return response.data?.data || response.data;
  } catch (error: any) {
    console.error('[DealerClaimAPI] Error submitting proposal:', error);
    throw error;
  }
}

/**
 * Submit completion documents (Step 5)
 * POST /api/v1/dealer-claims/:requestId/completion
 */
export async function submitCompletion(
  requestId: string,
  completionData: {
    activityCompletionDate: string; // ISO date string
    numberOfParticipants?: number;
    closedExpenses?: Array<{
      description: string;
      amount: number;
      hsnCode?: string;
      isService?: boolean;
      quantity?: number;
      gstRate?: number;
      gstAmt?: number;
      totalAmt?: number;
    }>;
    totalClosedExpenses?: number;
    completionDocuments?: File[];
    activityPhotos?: File[];
    completionDescription?: string;
  }
): Promise<any> {
  try {
    const formData = new FormData();

    formData.append('activityCompletionDate', completionData.activityCompletionDate);

    if (completionData.numberOfParticipants !== undefined) {
      formData.append('numberOfParticipants', completionData.numberOfParticipants.toString());
    }

    if (completionData.closedExpenses) {
      formData.append('closedExpenses', JSON.stringify(completionData.closedExpenses));
    }

    if (completionData.totalClosedExpenses !== undefined) {
      formData.append('totalClosedExpenses', completionData.totalClosedExpenses.toString());
    }

    if (completionData.completionDescription) {
      formData.append('completionDescription', completionData.completionDescription);
    }

    if (completionData.completionDocuments) {
      completionData.completionDocuments.forEach((file) => {
        formData.append('completionDocuments', file);
      });
    }

    if (completionData.activityPhotos) {
      completionData.activityPhotos.forEach((file) => {
        formData.append('activityPhotos', file);
      });
    }

    const response = await apiClient.post(`/dealer-claims/${requestId}/completion`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });

    return response.data?.data || response.data;
  } catch (error: any) {
    console.error('[DealerClaimAPI] Error submitting completion:', error);
    throw error;
  }
}

/**
 * Validate/Fetch IO details from SAP (returns dummy data for now)
 * GET /api/v1/dealer-claims/:requestId/io/validate?ioNumber=IO1234
 * This only validates and returns IO details, does not store anything
 */
export async function validateIO(
  requestId: string,
  ioNumber: string
): Promise<{
  ioNumber: string;
  availableBalance: number;
  currency: string;
  isValid: boolean;
}> {
  try {
    const response = await apiClient.get(`/dealer-claims/${requestId}/io/validate`, {
      params: { ioNumber }
    });
    return response.data?.data || response.data;
  } catch (error: any) {
    console.error('[DealerClaimAPI] Error validating IO:', error);
    throw error;
  }
}

/**
 * Update IO details and block amount (Step 3)
 * PUT /api/v1/dealer-claims/:requestId/io
 * Only stores data when blocking amount > 0
 */
export async function updateIODetails(
  requestId: string,
  ioData: {
    ioNumber: string;
    ioRemark?: string;
    ioAvailableBalance?: number;
    ioBlockedAmount?: number;
    ioRemainingBalance?: number;
  }
): Promise<any> {
  try {
    // Map frontend field names to backend expected field names
    // Only include balance fields if they are explicitly provided (not undefined)
    // This prevents overwriting existing balance values when only updating ioNumber/ioRemark
    const payload: any = {
      ioNumber: ioData.ioNumber,
      ioRemark: ioData.ioRemark || '',
    };

    // Only include balance fields if explicitly provided
    if (ioData.ioAvailableBalance !== undefined) {
      payload.availableBalance = ioData.ioAvailableBalance;
    }
    if (ioData.ioBlockedAmount !== undefined) {
      payload.blockedAmount = ioData.ioBlockedAmount;
    }
    if (ioData.ioRemainingBalance !== undefined) {
      payload.remainingBalance = ioData.ioRemainingBalance;
    }

    const response = await apiClient.put(`/dealer-claims/${requestId}/io`, payload);
    return response.data?.data || response.data;
  } catch (error) {
    console.error('Error updating IO details:', error);
    throw error;
  }
}

/**
 * Update E-Invoice details (Step 7)
 * PUT /api/v1/dealer-claims/:requestId/e-invoice
 */
export async function updateEInvoice(
  requestId: string,
  eInvoiceData: {
    eInvoiceNumber?: string;
    eInvoiceDate: string; // ISO date string
    dmsNumber?: string;
  }
): Promise<any> {
  try {
    const response = await apiClient.put(`/dealer-claims/${requestId}/e-invoice`, eInvoiceData);
    return response.data?.data || response.data;
  } catch (error: any) {
    console.error('[DealerClaimAPI] Error updating e-invoice:', error);
    throw error;
  }
}

/**
 * Update Credit Note details (Step 8)
 * PUT /api/v1/dealer-claims/:requestId/credit-note
 */
export async function updateCreditNote(
  requestId: string,
  creditNoteData: {
    creditNoteNumber?: string;
    creditNoteDate: string; // ISO date string
    creditNoteAmount: number;
  }
): Promise<any> {
  try {
    const response = await apiClient.put(`/dealer-claims/${requestId}/credit-note`, creditNoteData);
    return response.data?.data || response.data;
  } catch (error: any) {
    console.error('[DealerClaimAPI] Error updating credit note:', error);
    throw error;
  }
}

/**
 * Send credit note to dealer and auto-approve Step 8
 * POST /api/v1/dealer-claims/:requestId/credit-note/send
 */
export async function sendCreditNoteToDealer(requestId: string): Promise<any> {
  try {
    const response = await apiClient.post(`/dealer-claims/${requestId}/credit-note/send`);
    return response.data?.data || response.data;
  } catch (error: any) {
    console.error('[DealerClaimAPI] Error sending credit note to dealer:', error);
    throw error;
  }
}

export interface DashboardKPIs {
  totalClaims: number;
  totalValue: number;
  approved: number;
  rejected: number;
  pending: number;
  credited: number;
  pendingCredit: number;
  approvedValue: number;
  rejectedValue: number;
  pendingValue: number;
  creditedValue: number;
  pendingCreditValue: number;
}

export interface CategoryData {
  activityType: string;
  raised: number;
  raisedValue: number;
  approved: number;
  approvedValue: number;
  rejected: number;
  rejectedValue: number;
  pending: number;
  pendingValue: number;
  credited: number;
  creditedValue: number;
  pendingCredit: number;
  pendingCreditValue: number;
  approvalRate: number;
  creditRate: number;
}

export interface DealerDashboardData {
  kpis: DashboardKPIs;
  categoryData: CategoryData[];
}

/**
 * Get dealer dashboard KPIs and category data
 * GET /api/v1/dealer-claims/dashboard
 */
export async function getDealerDashboard(
  dateRange?: string,
  startDate?: string,
  endDate?: string
): Promise<DealerDashboardData> {
  try {
    const params: any = {};
    if (dateRange) params.dateRange = dateRange;
    if (startDate) params.startDate = startDate;
    if (endDate) params.endDate = endDate;

    const response = await apiClient.get('/dealer-claims/dashboard', { params });
    return response.data?.data || response.data;
  } catch (error: any) {
    console.error('[DealerClaimAPI] Error fetching dealer dashboard:', error);
    throw error;
  }
}

/**
 * Re-trigger WFM CSV push
 * POST /api/v1/dealer-claims/:requestId/wfm/retrigger
 */
export async function retriggerWFMPush(requestId: string): Promise<any> {
  try {
    const response = await apiClient.post(`/dealer-claims/${requestId}/wfm/retrigger`);
    return response.data?.data || response.data;
  } catch (error: any) {
    console.error('[DealerClaimAPI] Error re-triggering WFM push:', error);
    throw error;
  }
}
