import { api } from '$lib/api';
import type { ApiResponse } from '$lib/api';

// --- Interfaces para detalles (Hijos) ---

export interface DodaContainerSeal {
    id: number;
    doda_sys_id: number;
    seal_line: number;
    seal_value?: string;
}

export interface DodaContainerSealCreate {
    seal_value?: string;
}

export interface DodaContainer {
    id: number;
    doda_sys_id: number;
    container_line: number;
    container_value?: string;
    seals?: string;
    seals_detail?: DodaContainerSeal[];
}

export interface DodaContainerCreate {
    container_value?: string;
    seals?: string;
    seals_detail?: DodaContainerSealCreate[];
}

export interface DodaAmericanPedimento {
    id: number;
    doda_sys_id: number;
    american_pedimento_line: number;
    american_pedimento_type?: string;
    american_pedimento_value?: string;
}

export interface DodaAmericanPedimentoCreate {
    american_pedimento_type?: string;
    american_pedimento_value?: string;
}

export interface DodaPedimento {
    id: number;
    doda_sys_id: number;
    pedimento_line: number;
    authorization_patent?: string;
    document?: string;
    shipment?: string;
    cove?: string;
    umc?: string;
    effective_amount_usd?: number;
    difference_amount_usd?: number;
    dta_niu?: string;
    article_7?: boolean;
    pedimento_sys_id?: number;
    invoice_line?: number;
    part_ii_line?: number;
    pedimento_type?: string;
    zero_packaging_validation?: boolean;
}

export interface DodaPedimentoCreate {
    authorization_patent?: string;
    document?: string;
    shipment?: string;
    effective_amount_usd?: number;
}

// --- Interfaces Principales (Padre) ---

export interface Doda {
    id: number;
    integration_number?: string;
    doda_date?: number;
    doda_time?: number;
    dispatch_customs?: string;
    customs_sections?: string;
    patent?: string;
    pedimentos?: string;
    caat?: string;
    transport_identification?: string;
    fast_id?: string;
    operation_type?: string;
    status?: string;

    // Relaciones
    containers?: DodaContainer[];
    american_pedimentos?: DodaAmericanPedimento[];
    pedimentos_detail?: DodaPedimento[];

    // Metadata
    tenant_id?: string;
    created_at?: string;
    updated_at?: string;

    // Campos extra del formulario que vimos en el frontend
    selected?: boolean;
    user_selected?: string;
    last_user?: string;
    responsible?: string;
    carrier?: string;
    shipments?: string;
    pedimento_type?: string;
    original_chain?: string;
    serial_number?: string;
    electronic_signature?: string;
    transaction_number?: string;
    linq_sat_qr?: string;
    sat_certificate?: string;
    sat_digital_seal?: string;
    xml_doda_sent_path?: string;
    xml_doda_response_path?: string;
    sat_original_chain?: string;
    customs_clearance?: number;
    unique_badge_number?: string;
}

export interface DodaCreate {
    integration_number?: string;
    doda_date?: number;
    doda_time?: number;
    dispatch_customs?: string;
    customs_sections?: string;
    patent?: string;
    pedimentos?: string;
    caat?: string;
    transport_identification?: string;
    fast_id?: string;
    operation_type?: string;
    selected?: boolean;
    user_selected?: string;
    last_user?: string;
    responsible?: string;
    carrier?: string;
    shipments?: string;
    pedimento_type?: string;
    original_chain?: string;
    serial_number?: string;
    electronic_signature?: string;
    transaction_number?: string;
    status?: string;
    linq_sat_qr?: string;
    sat_certificate?: string;
    sat_digital_seal?: string;
    xml_doda_sent_path?: string;
    xml_doda_response_path?: string;
    sat_original_chain?: string;
    customs_clearance?: number;
    unique_badge_number?: string;
}

export interface DodaUpdate extends Partial<DodaCreate> { }

export interface DodaListResponse {
    items: Doda[];
    total: number;
    page: number;
    page_size: number;
    pages: number;
}

// --- Funciones de API ---

export async function getDodas(
    page: number = 1,
    pageSize: number = 50,
    filters: Record<string, any> = {},
    companyId?: number
): Promise<ApiResponse<DodaListResponse>> {
    const params = new URLSearchParams({
        page: page.toString(),
        page_size: pageSize.toString(),
        ...filters
    });
    if (companyId) {
        params.append('company_id', companyId.toString());
    }
    return await api.get(`/v1/a76/doda/?${params.toString()}`);
}

export const dodaApi = {
    list: (page = 1, pageSize = 50, companyId: number, filters: any = {}) => 
        getDodas(page, pageSize, filters, companyId),
    get: (id: number, companyId: number) => 
        api.get<Doda>(`/v1/a76/doda/${id}/detail?company_id=${companyId}`),
    create: (data: DodaCreate, companyId: number) => 
        api.post<Doda>(`/v1/a76/doda/?company_id=${companyId}`, data),
    update: (id: number, data: DodaUpdate, companyId: number) => 
        api.put<Doda>(`/v1/a76/doda/${id}/?company_id=${companyId}`, data),
    delete: (id: number, companyId: number) => 
        api.delete(`/v1/a76/doda/${id}/?company_id=${companyId}`)
};

export async function getDoda(id: number, companyId?: number): Promise<Doda> {
    const params = new URLSearchParams();
    if (companyId) {
        params.append('company_id', companyId.toString());
    }
    const response = await api.get<Doda>(`/v1/a76/doda/${id}/detail?${params.toString()}`);
    if (response.error || !response.data) {
        throw new Error(response.error || 'Error al obtener el DODA');
    }
    return response.data;
}

export async function createDoda(data: DodaCreate, companyId: number): Promise<Doda> {
    const response = await api.post<Doda>(`/v1/a76/doda/?company_id=${companyId}`, data);
    if (response.error || !response.data) {
        throw new Error(response.error || 'Error al crear el DODA');
    }
    return response.data;
}

/** POST /v1/a76/doda/{dodaId}/containers — añade contenedor al DODA existente. */
export async function addDodaContainer(
    dodaId: number,
    body: DodaContainerCreate,
    companyId: number
): Promise<DodaContainer> {
    const params = new URLSearchParams({ company_id: companyId.toString() });
    const response = await api.post<DodaContainer>(
        `/v1/a76/doda/${dodaId}/containers?${params.toString()}`,
        body
    );
    if (response.error || !response.data) {
        throw new Error(response.error || 'Error al agregar el contenedor');
    }
    return response.data;
}

export async function deleteDodaContainer(
    dodaId: number,
    containerLine: number,
    companyId: number
): Promise<void> {
    const params = new URLSearchParams({ company_id: companyId.toString() });
    const response = await api.delete(
        `/v1/a76/doda/${dodaId}/containers/${containerLine}?${params.toString()}`
    );
    if (response.error) {
        throw new Error(response.error);
    }
}

export async function updateDodaContainer(
	dodaId: number,
	containerLine: number,
	body: DodaContainerCreate,
	companyId: number
): Promise<DodaContainer> {
	const params = new URLSearchParams({ company_id: companyId.toString() });
	const response = await api.put<DodaContainer>(
		`/v1/a76/doda/${dodaId}/containers/${containerLine}?${params.toString()}`,
		body
	);
	if (response.error || !response.data) {
		throw new Error(response.error || 'Error al actualizar el contenedor');
	}
	return response.data;
}

/** POST /v1/a76/doda/{dodaId}/containers/{containerLine}/seals — añade precinto. */
export async function addDodaSeal(
    dodaId: number,
    containerLine: number,
    sealValue: string,
    companyId: number
): Promise<DodaContainerSeal> {
    const params = new URLSearchParams({ company_id: companyId.toString() });
    const response = await api.post<DodaContainerSeal>(
        `/v1/a76/doda/${dodaId}/containers/${containerLine}/seals?${params.toString()}`,
        { seal_value: sealValue }
    );
    if (response.error || !response.data) {
        throw new Error(response.error || 'Error al agregar el precinto');
    }
    return response.data;
}

export async function deleteDodaSeal(
    dodaId: number,
    containerLine: number,
    sealLine: number,
    companyId: number
): Promise<void> {
    const params = new URLSearchParams({ company_id: companyId.toString() });
    const response = await api.delete(
        `/v1/a76/doda/${dodaId}/containers/${containerLine}/seals/${sealLine}?${params.toString()}`
    );
    if (response.error) {
        throw new Error(response.error);
    }
}

/** POST /v1/a76/doda/{dodaId}/pedimentos — añade línea al DODA existente. */
export async function addDodaPedimento(
    dodaId: number,
    body: DodaPedimentoCreate,
    companyId: number
): Promise<DodaPedimento> {
    const params = new URLSearchParams({ company_id: companyId.toString() });
    const response = await api.post<DodaPedimento>(
        `/v1/a76/doda/${dodaId}/pedimentos?${params.toString()}`,
        body
    );
    if (response.error || !response.data) {
        throw new Error(response.error || 'Error al guardar el pedimento');
    }
    return response.data;
}

/** POST /v1/a76/doda/{dodaId}/american-pedimentos */
export async function addDodaAmericanPedimento(
    dodaId: number,
    body: DodaAmericanPedimentoCreate,
    companyId: number
): Promise<DodaAmericanPedimento> {
    const params = new URLSearchParams({ company_id: companyId.toString() });
    const response = await api.post<DodaAmericanPedimento>(
        `/v1/a76/doda/${dodaId}/american-pedimentos?${params.toString()}`,
        body
    );
    if (response.error || !response.data) {
        throw new Error(response.error || 'Error al guardar el pedimento americano');
    }
    return response.data;
}

export async function deleteDodaAmericanPedimento(
    dodaId: number,
    pedimentoLine: number,
    companyId: number
): Promise<void> {
    const params = new URLSearchParams({ company_id: companyId.toString() });
    const response = await api.delete(
        `/v1/a76/doda/${dodaId}/american-pedimentos/${pedimentoLine}?${params.toString()}`
    );
    if (response.error) {
        throw new Error(response.error);
    }
}

export async function updateDoda(id: number, data: DodaUpdate, companyId: number): Promise<Doda> {
    const response = await api.put<Doda>(`/v1/a76/doda/${id}/?company_id=${companyId}`, data);
    if (response.error || !response.data) {
        throw new Error(response.error || 'Error al actualizar el DODA');
    }
    return response.data;
}

export async function deleteDoda(id: number, companyId: number): Promise<void> {
    const response = await api.delete(`/v1/a76/doda/${id}?company_id=${companyId}`);
    if (response.error) {
        throw new Error(response.error);
    }
}

/**
 * GET /v1/a76/doda/{id}/print — PDF (requiere sello digital SAT en backend)
 */
export async function printDoda(dodaId: number, companyId: number): Promise<void> {
	const params = new URLSearchParams({ company_id: String(companyId) });
	const blob = await api.getBlob(`/v1/a76/doda/${dodaId}/print?${params.toString()}`);
	const url = URL.createObjectURL(blob);
	const a = document.createElement('a');
	a.href = url;
	a.target = '_blank';
	a.rel = 'noopener';
	a.download = `doda_${dodaId}.pdf`;
	document.body.appendChild(a);
	a.click();
	a.remove();
	URL.revokeObjectURL(url);
}

export type DodaExportFileFormat = 'csv' | 'xls' | 'txt';
export type DodaExportDateMode = 'raw' | 'formatted';

/**
 * GET /v1/a76/doda/export — listado por rango (Fecha DODA YYYYMMDD en BD)
 */
export async function exportDodaList(
	companyId: number,
	opts: {
		dateFrom: string;
		dateTo: string;
		format: DodaExportFileFormat;
		dateMode: DodaExportDateMode;
	}
): Promise<void> {
	const params = new URLSearchParams({
		company_id: String(companyId),
		date_from: opts.dateFrom,
		date_to: opts.dateTo,
		format: opts.format,
		date_mode: opts.dateMode
	});
	const ext = opts.format;
	const blob = await api.getBlob(`/v1/a76/doda/export?${params.toString()}`);
	const url = URL.createObjectURL(blob);
	const a = document.createElement('a');
	a.href = url;
	a.download = `doda_export_${opts.dateFrom}_${opts.dateTo}.${ext}`;
	document.body.appendChild(a);
	a.click();
	a.remove();
	URL.revokeObjectURL(url);
}

/**
 * GET /v1/a76/doda/export/pedimentos/{id} — líneas de pedimento del DODA (TSV/csv/txt).
 */
export async function exportDodaPedimentosDetail(
	dodaId: number,
	companyId: number,
	format: DodaExportFileFormat = 'xls'
): Promise<void> {
	const params = new URLSearchParams({
		company_id: String(companyId),
		format
	});
	const blob = await api.getBlob(`/v1/a76/doda/export/pedimentos/${dodaId}?${params.toString()}`);
	const url = URL.createObjectURL(blob);
	const a = document.createElement('a');
	a.href = url;
	a.download = `doda_pedimentos_${dodaId}.${format}`;
	document.body.appendChild(a);
	a.click();
	a.remove();
	URL.revokeObjectURL(url);
}

// ── Alta DODA API ─────────────────────────────────────────────────────────── //

export interface DodaAltaResponse {
    task_id: string;
    status: string;
    message: string;
}

export interface DodaAltaStatusResponse {
    state?: string;
    status?: string;
    message?: string;
    result?: Record<string, unknown>;
    error?: string;
}

export interface DodaElegibilidadReason {
    field: string;
    message: string;
    solution?: string;
}

export interface DodaElegibilidadResponse {
    can_alta: boolean;
    reasons: DodaElegibilidadReason[];
}

export async function postDodaAlta(
    dodaId: number,
    companyId: number,
    variant: 'doda' | 'pita' = 'doda'
): Promise<ApiResponse<DodaAltaResponse>> {
    const params = new URLSearchParams({
        company_id: companyId.toString(),
        variant,
    });
    return api.post<DodaAltaResponse>(`/v1/a76/doda/${dodaId}/alta?${params}`, {});
}

export async function getDodaAltaStatus(
    taskId: string
): Promise<ApiResponse<DodaAltaStatusResponse>> {
    return api.get<DodaAltaStatusResponse>(`/v1/a76/doda/alta-status/${taskId}`);
}

export async function postDodaConsulta(
    dodaId: number,
    companyId: number,
    variant: 'doda' | 'pita' = 'doda'
): Promise<ApiResponse<DodaAltaResponse>> {
    const params = new URLSearchParams({
        company_id: companyId.toString(),
        variant,
    });
    return api.post<DodaAltaResponse>(`/v1/a76/doda/${dodaId}/consulta?${params}`, {});
}

export async function getDodaConsultaStatus(
    taskId: string
): Promise<ApiResponse<DodaAltaStatusResponse>> {
    return api.get<DodaAltaStatusResponse>(`/v1/a76/doda/consulta-status/${taskId}`);
}

export async function postDodaConsultaApply(
    dodaId: number,
    taskId: string,
    companyId: number
): Promise<ApiResponse<Record<string, unknown>>> {
    const params = new URLSearchParams({
        company_id: companyId.toString(),
    });
    return api.post<Record<string, unknown>>(
        `/v1/a76/doda/${dodaId}/consulta-apply/${taskId}?${params}`,
        {}
    );
}

export async function postDodaEliminar(
    dodaId: number,
    companyId: number,
    variant: 'doda' | 'pita' = 'doda'
): Promise<ApiResponse<DodaAltaResponse>> {
    const params = new URLSearchParams({
        company_id: companyId.toString(),
        variant,
    });
    return api.post<DodaAltaResponse>(`/v1/a76/doda/${dodaId}/eliminar?${params}`, {});
}

export async function getDodaEliminarStatus(
    taskId: string
): Promise<ApiResponse<DodaAltaStatusResponse>> {
    return api.get<DodaAltaStatusResponse>(`/v1/a76/doda/eliminar-status/${taskId}`);
}

export async function getDodaElegibilidad(
    dodaId: number,
    companyId: number,
    variant: 'doda' | 'pita' = 'doda'
): Promise<ApiResponse<DodaElegibilidadResponse>> {
    const params = new URLSearchParams({
        company_id: companyId.toString(),
        variant,
    });
    return api.get<DodaElegibilidadResponse>(
        `/v1/a76/doda/${dodaId}/alta/elegibilidad?${params}`
    );
}