import {GetServerSideProps, NextPage} from 'next';
import BrowseRingtonesTemplate from '../components/templates/BrowseRingtones';
import {getSession, Session} from '@auth0/nextjs-auth0';
import {models} from '@tonality/library-common';
import RingtoneClient from '../modules/ringtone/client';
import {useEffect, useState} from 'react';
import getFormValues from '@theoryofnekomata/formxtra';
import {useRouter} from 'next/router';

type Props = {
	session: Partial<Session>,
	ringtones: models.Ringtone[],
	skip: number,
	take: number,
	total: number,
}

const IndexPage: NextPage<Props> = ({
	session,
	ringtones: ringtonesProp,
	skip: skipProp,
	take: takeProp,
	total: totalProp,
}) => {
	const [ringtoneClient, setRingtoneClient] = useState<RingtoneClient>(null)
	const [ringtones, setRingtones] = useState(ringtonesProp)
	const [skip, setSkip] = useState(skipProp)
	const [take, setTake] = useState(takeProp)
	const [total, setTotal] = useState(totalProp)
	const [loading, setLoading] = useState(false)
	const router = useRouter()

	const getNextPage = async (e) => {
		// e.preventDefault()
		// const values = getFormValues(e.target)
		// setLoading(true)
		// try {
		// 	const {data: ringtones, skip, take, total} = await ringtoneClient.browse({
		// 		skip: Number(values.skip),
		// 		take: Number(values.take)
		// 	})
		// 	setRingtones(ringtones)
		// 	setSkip(skip)
		// 	setTake(take)
		// 	setTotal(total)
		// 	router.push({
		// 		query: {
		// 			skip: Number(values.skip),
		// 			take: Number(values.take),
		// 		},
		// 	})
		// } catch (err) {
		// 	console.log(err)
		// }
		// setLoading(false)
	}

	useEffect(() => {
		setRingtoneClient(new RingtoneClient(process.env.NEXT_PUBLIC_API_BASE_URL, session))
	}, [])

	return (
		<BrowseRingtonesTemplate
			session={session}
			ringtones={ringtones}
			skip={skip}
			take={take}
			total={total}
			loading={loading}
			onNextPage={getNextPage}
		/>
	);
};

export const getServerSideProps: GetServerSideProps = async ({ req, res, query }) => {
	const authSession = getSession(req, res)
	const session = authSession
		? {
			idToken: authSession.idToken,
			token_type: authSession.token_type,
			user: authSession.user,
		}
		: null
	const client = new RingtoneClient(process.env.NEXT_PUBLIC_API_BASE_URL, session)
	const browseParams: { skip: number, take: number } = {} as any
	if (query.skip) {
		browseParams.skip = Number(query.skip)
	}
	if (query.skip) {
		browseParams.take = Number(query.take)
	}
	const { data: ringtones, skip, take, total } = await client.browse(browseParams)

	return {
		props: {
			session,
			ringtones,
			skip,
			take,
			total,
		}
	}
}

export default IndexPage;
