// composables/useAxiosForm.ts
import axios, { AxiosError } from 'axios'
import { computed, reactive, ref, toRaw } from 'vue'
import NProgress from 'nprogress'

type FormErrors<T> = Partial<Record<keyof T, string>>

export interface AxiosFormResponse {
	success: boolean
	message?: string
}

export class ApiResponseError extends Error {
	constructor( public response: AxiosFormResponse ) {
		super( response.message ?? 'Request failed' )
	}
}

type SubmitOptions<R = AxiosFormResponse> = {
	onSuccess?: ( data: R ) => void
	onError?: ( e: unknown, message: string ) => void
}

type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete'

const DEFAULT_ERROR = 'Nastala chyba'

export const errorMessage = ( e: unknown, fallback = DEFAULT_ERROR ): string => {
	if ( e instanceof ApiResponseError ) return e.message
	return ( e as AxiosError<{ message?: string }> )?.response?.data?.message ?? fallback
}

export function useAxiosForm<T extends object>( defaults: T ) {
	const factory = () => structuredClone( defaults )

	const form = reactive<T>( factory() ) as T
	const snapshot = ref<T>( factory() )

	const errors = reactive<FormErrors<T>>( {} )
	const processing = ref( false )
	const recentlySuccessful = ref( false )
	let recentlySuccessfulTimeout: ReturnType<typeof setTimeout> | null = null

	const isDirty = computed( () =>
		( Object.keys( snapshot.value ) as ( keyof T )[] ).some( key => {
			const a = form[key]
			const b = snapshot.value[key]

			if ( a instanceof Date && b instanceof Date ) {
				return a.getTime() !== b.getTime()
			}

			return a !== b
		} )
	)

	let transformFn: ( ( data: T ) => Record<string, unknown> ) | null = null

	const rawData = (): T => {
		const keys = Object.keys( defaults ) as ( keyof T )[]
		return keys.reduce( ( acc, key ) => {
			acc[key] = toRaw( form[key] )
			return acc
		}, {} as T )
	}

	const extractData = (): Record<string, unknown> => {
		const raw = rawData()
		return transformFn ? transformFn( raw ) : raw as Record<string, unknown>
	}

	const transform = ( fn: ( data: T ) => Record<string, unknown> ) => {
		transformFn = fn
	}

	const reset = () => {
		Object.assign( form, factory() )
	}

	const clearErrors = () => {
		Object.keys( errors ).forEach( key => {
			delete ( errors as Record<string, unknown> )[key]
		} )
	}

	const setErrors = ( incoming: FormErrors<T> ) => {
		clearErrors()
		Object.assign( errors, incoming )
	}

	const takeSnapshot = () => {
		snapshot.value = structuredClone( rawData() )
	}

	const submit = async <R = AxiosFormResponse>(
		handler: ( data: Record<string, unknown> ) => Promise<R>,
		options?: SubmitOptions<R>
	): Promise<boolean> => {
		processing.value = true
		clearErrors()
		NProgress.start()

		let result: R

		try {
			result = await handler( extractData() )

			// HTTP 2xx, ale server hlási zlyhanie v tele
			if ( ( result as Partial<AxiosFormResponse> )?.success === false ) {
				throw new ApiResponseError( result as AxiosFormResponse )
			}
		} catch ( e ) {
			const axiosError = e as AxiosError<{ errors?: FormErrors<T>, message?: string }>

			if ( axiosError?.response?.status === 422 ) {
				setErrors( axiosError.response.data?.errors ?? {} )
			}

			if ( options?.onError ) options.onError( e, errorMessage( e ) )
			else console.error( e )

			return false
		} finally {
			processing.value = false
			NProgress.done()
		}

		// mimo try, aby chyba v onSuccess nespustila onError
		takeSnapshot()

		if ( recentlySuccessfulTimeout ) clearTimeout( recentlySuccessfulTimeout )
		recentlySuccessful.value = true
		recentlySuccessfulTimeout = setTimeout( () => {
			recentlySuccessful.value = false
		}, 3000 )

		options?.onSuccess?.( result )
		return true
	}

	const send = <R = AxiosFormResponse>( method: HttpMethod, url: string, options?: SubmitOptions<R> ) =>
		submit<R>( async ( data ) => {
			const res = await axios.request<R>( {
				method,
				url,
				...( method === 'get' ? { params: data } : { data } ),
			} )
			return res.data
		}, options )

	const destroy = <R = AxiosFormResponse>( url: string, o?: SubmitOptions<R> ) => send<R>( 'delete', url, o )
	const get     = <R = AxiosFormResponse>( url: string, o?: SubmitOptions<R> ) => send<R>( 'get', url, o )
	const patch   = <R = AxiosFormResponse>( url: string, o?: SubmitOptions<R> ) => send<R>( 'patch', url, o )
	const post    = <R = AxiosFormResponse>( url: string, o?: SubmitOptions<R> ) => send<R>( 'post', url, o )
	const put     = <R = AxiosFormResponse>( url: string, o?: SubmitOptions<R> ) => send<R>( 'put', url, o )

	const api = {
		errors,
		isDirty,
		processing,
		recentlySuccessful,
		clearErrors,
		destroy,
		get,
		patch,
		post,
		put,
		reset,
		setErrors,
		submit,
		takeSnapshot,
		transform,
	}

	return reactive( Object.assign( form, api ) )
}
