'use client'

import { useAtomValue } from "jotai"
import { exportFlowToDocx } from "../export"
import { instantDataAtom, stepsNodesAtom } from "../store"
import { twMerge } from "tailwind-merge"
import { renderAsync } from 'docx-preview'
import { useEffect, useRef, useState } from "react"
import saveAs from "file-saver"

export default function PreviewModal({ open, onClose }: { open: boolean, onClose: () => void }) {
  const instantData = useAtomValue(instantDataAtom)
  const stepsNodes = useAtomValue(stepsNodesAtom)
  const [blob, setBlob] = useState(null)
  const previewRef = useRef()


  useEffect(() => {
    if (open) {
      (async () => {
        const stepsInstantData = stepsNodes.map(node => instantData[node.id])
        const blob = await exportFlowToDocx(stepsInstantData)
        setBlob(blob)
        await renderAsync(blob, previewRef.current)
      })()
    } else {
      setBlob(null)
    }
  }, [open])

  const onExport = async () => {
    blob && saveAs(blob, "课程设计.docx", { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" })
  }

  return (
    <dialog className={twMerge("modal", open ? "modal-open" : "")}>
      <div className="modal-box w-11/12 max-w-5xl pb-5">
        <div ref={previewRef}></div>
      </div>
      <div className="modal-action mb-6">
        <form method="dialog" className="flex gap-4">
          <button className="btn btn-wide" onClick={onClose}>关闭</button>
          <button className="btn btn-wide btn-primary" disabled={!blob} onClick={onExport}>
            {blob
              ? '导出'
              : <span className="loading loading-spinner"></span>}
          </button>
        </form>
      </div>
    </dialog>
  )
}