'use client'

import { suitableApi } from '@/api/suitable'
import { useQuery } from '@tanstack/react-query'
import generatePDF, { usePDF, Options } from 'react-to-pdf'
import PDFContent from './SuitablePdf'

const pdfOptions: Options = {
  filename: 'page.pdf',
  method: 'save',
  page: { format: 'a4', margin: 10 },
  overrides: {
    pdf: {
      compress: true,
    },
  },
}

export default function SuitableDetails({ roofMaterial }: { roofMaterial: string }) {
  const { data, isLoading } = useQuery({
    queryKey: ['suitable-details'],
    queryFn: () => suitableApi.getDetails(roofMaterial),
    staleTime: 0,
    enabled: !!roofMaterial,
  })

  const { toPDF, targetRef } = usePDF({ ...pdfOptions, method: 'open' })

  if (isLoading) {
    return <div>Loading...</div>
  }

  return (
    <>
      <button className="inline-block bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" onClick={() => toPDF()}>
        OPEN PDF
      </button>
      <button
        className="inline-block bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
        onClick={() => generatePDF(targetRef, pdfOptions)}
      >
        SAVE PDF
      </button>
      {/* <button onClick={handleDownloadPDF}>Download PDF</button> */}
      {/* <div ref={targetRef} className="pdf-content"> */}
      <div>
        <h1 className="text-4xl font-bold">Searched Roof Material: {decodeURIComponent(roofMaterial as string)}</h1>
        {data &&
          data.map((item) => (
            <div key={item.id}>
              <br />
              <div>product_name: {item.product_name}</div>
              <div>manufacturer: {item.manufacturer}</div>
              <div>roof_material: {item.roof_material}</div>
              <div>shape: {item.shape}</div>
              <div>support_roof_tile: {item.support_roof_tile}</div>
              <div>support_roof_bracket: {item.support_roof_bracket}</div>
              <div>yg_anchor: {item.yg_anchor}</div>
            </div>
          ))}
      </div>
      {/* <div style={{ display: 'none' }}> */}
      <div>
        <div ref={targetRef}>
          <h1 className="text-4xl font-bold">PDF 내용 나와라</h1>
          <PDFContent data={data ?? []} />
        </div>
      </div>
    </>
  )
}
