'use client'
import { Box, Button, Flex, Group, Image, Modal, rem, Skeleton, Stack, Text } from '@mantine/core';
import { useShallowEffect } from '@mantine/hooks';
import dynamic from 'next/dynamic';
import { useState } from 'react';
import toast from 'react-hot-toast';
import { TransformComponent, TransformWrapper } from "react-zoom-pan-pinch";
import { funReadPdf } from '../fun/read_pdf';
const PdfToImage = dynamic(() => import('./../components/pdf_viewer').then((mod) => mod.default), { ssr: false });

export default function LayoutModal({ opened, onClose, extension, fitur, name, file }: { opened: boolean, onClose: () => void, extension: string, fitur: string, name?: string, file: string }) {
   const [zoom, setZoom] = useState(1)
   const [loadingPdf, setLoadingPdf] = useState(true)
   const [dataPdf, setDataPdf] = useState([])
   const [totalPage, setTotalPage] = useState(0)
   const [page, setPage] = useState(1)

   const handleZoomIn = () => {
      setZoom(zoom + 0.1)
   }

   const handleZoomOut = () => {
      setZoom(zoom - 0.1)
   }

   async function getPdfToImg(pages: number) {
      try {
         setLoadingPdf(true)
         setPage(pages)
         const res = await funReadPdf({ file: file, page: pages })
         if (res.success) {
            setDataPdf(res.data.pages)
            setTotalPage(res.data.totalPages)
         }
      } catch (error) {
         console.error(error)
         toast.error("Gagal mendapatkan file, coba lagi nanti");
      } finally {
         setLoadingPdf(false)
      }
   }

   useShallowEffect(() => {
      if (extension == "pdf") {
         getPdfToImg(1)
      } else {
         setLoadingPdf(false)
      }
   }, [file, extension])

   return (
      <>
         <Modal.Root styles={{
            content: {
               maxWidth: 550,
            }
         }} opened={opened} onClose={onClose} centered closeOnClickOutside={false} fullScreen>
            <Modal.Overlay />
            <Modal.Content>
               <Modal.Header py={0}>
                  <Modal.Title>
                     <Text lineClamp={1}>{name}</Text>
                  </Modal.Title>
                  <Modal.CloseButton />
               </Modal.Header>
               <Modal.Body pl={0} pr={0}>
                  <Box
                     pos="sticky"
                     top={60}
                     right={0}
                     w={"100%"}
                     pb={10}
                     px={10}

                     style={{
                        background: 'white',
                        zIndex: 999,
                     }}
                  >
                     <Group justify="flex-start">
                        {/* <Flex direction="row" gap="xs" align="center">
                           <Button variant="light" onClick={handleZoomOut}> - </Button>
                           <Button variant="light" onClick={handleZoomIn}> + </Button>
                        </Flex> */}
                        {
                           extension == "pdf" &&
                           <Flex direction="row" gap="xs" align="center">
                              <Button variant="light" disabled={page == 1 ? true : false} onClick={() => { getPdfToImg(page - 1) }}> Prev </Button>
                              <Text c={"gray"}> {page} / {totalPage} </Text>
                              <Button variant="light" disabled={page == totalPage ? true : false} onClick={() => { getPdfToImg(page + 1) }}> Next </Button>
                           </Flex>
                        }
                     </Group>

                  </Box>
                  <Box pos={"relative"} style={{
                     transform: `scale(${zoom})`,
                     transformOrigin: 'center',
                     maxWidth: rem(550),
                     paddingLeft: 10,
                     paddingRight: 10
                  }}>
                     {
                        loadingPdf ?
                           <Stack p="md" align="stretch" justify="center">
                              {[...Array(1)].map((_, index) => (
                                 <Skeleton key={index} height={500} />
                              ))}
                           </Stack>
                           :
                           <TransformWrapper>
                              <TransformComponent>
                                 {
                                    extension === 'pdf' ?
                                       <>
                                          {dataPdf.map((item: any, index: any) => (
                                             <Image
                                                style={{
                                                   maxWidth: '100%',
                                                   maxHeight: '100%',
                                                }}
                                                fit="contain"
                                                alt={file}
                                                key={index}
                                                src={item.imageUrl}
                                             />
                                          ))}
                                       </>
                                       :
                                       <Image
                                          style={{
                                             maxWidth: '100%',
                                             maxHeight: '100%',
                                          }}
                                          fit="contain"
                                          src={`https://wibu-storage.wibudev.com/api/files/${file}`}
                                          alt={file}
                                       />
                                 }
                              </TransformComponent>
                           </TransformWrapper>
                     }
                     {/* <div style={{ transform: `scale(${zoom})`, transformOrigin: 'center' }}>
                        {
                           extension === 'pdf' ?
                              // <PdfToImage md={`https://wibu-storage.wibudev.com/api/files/${file}`} />
                              loadingPdf ?
                                 <Stack p="md">
                                    {[...Array(1)].map((_, index) => (
                                       <Skeleton key={index} height={500} />
                                    ))}
                                 </Stack>
                                 :
                                 <>
                                    {dataPdf.map((item: any, index: any) => (
                                       <Image
                                          w={"100%"}
                                          alt={file}
                                          key={index}
                                          src={item.imageUrl}
                                       />
                                    ))}
                                 </>
                              :
                              <Image
                                 style={{
                                    maxWidth: '100%',
                                    maxHeight: '100%',
                                 }}
                                 fit="contain"
                                 src={`https://wibu-storage.wibudev.com/api/files/${file}`}
                                 alt={file}
                              />
                        }
                     </div> */}
                  </Box>
               </Modal.Body>
            </Modal.Content>
         </Modal.Root>
      </>
   );
}

