import type { Route } from './+types'

import { HttpMethod, request as req } from '@repo/util/request'
import { useFetcher } from 'react-router'

// import { RrwebRecorder } from '@/components/rrweb-recorder'
import { ScormPlayer } from '@/components/scorm-player'
// import { useLocalStorage } from '@/hooks/useLocalStorage'
// import SHA256 from 'crypto-js/sha256'

export function meta({ params }: Route.MetaArgs) {
  return [{ title: '' }]
}

export const loader = async ({
  params,
  request,
  context
}: Route.ActionArgs) => {
  const { id } = params
  const r = await req({
    url: `/enrollments/${id}/scorm`,
    request,
    context
  })
  return { data: await r.json() }
}

export async function action({ params, request, context }: Route.ActionArgs) {
  const { id } = params
  const body = JSON.stringify(await request.json())

  console.log(body)

  await req({
    url: `/enrollments/${id}`,
    method: HttpMethod.POST,
    body,
    headers: new Headers({ 'Content-Type': 'application/json' }),
    request,
    context
  })
  console.log(body)

  return {}
}

export default function Route({ loaderData: { data } }: Route.ComponentProps) {
  const fetcher = useFetcher()
  const course = {
    id: 'fbad867a-0022-4605-814f-db8ebe2b17fb',
    // courseName: 'All Golf',
    scormContentPath:
      // 'nr-33-espacos-confinados-conteudo-de-demonstracao-scorm12/scormdriver/indexAPI.html'
      // 'cipa-pt-1-scorm12/scormdriver/indexAPI.html'
      'test-scorm2004_4/scormdriver/indexAPI.html'
  }

  const scormState = data?.['last_commit']?.cmi || {}
  // const suspendData = JSON.parse(scormState?.cmi?.suspend_data || '{}')
  // const d = lzwCompress.unpack(suspendData?.d)
  // const d2 = JSON.parse(d || '{}')
  // console.log(d2?.progress?.p ?? null)

  return (
    <>
      {/*      <RrwebRecorder
        onEventBatch={(data) => {
          console.log(JSON.stringify(data))
        }}
      />*/}

      <ScormPlayer
        settings={{
          autocommit: true
          // throwExceptions: false,
          // logLevel: 2,
          // compatibilityMode: 1
        }}
        scormVersion="2004"
        scormState={scormState}
        scormContentPath={course.scormContentPath}
        className="w-full h-full border-0"
        onCommit={async (data) => {
          console.log(data)
          await fetcher.submit(JSON.stringify(data), {
            method: 'post',
            encType: 'application/json'
          })
        }}
      />
    </>
  )
}
