import { Anggota } from '@/types';
import { useAnggota, useProfil } from '@/useQuery/query';
import html2pdf from 'html2pdf.js';
import { useEffect, useMemo, useRef, useState } from 'react';
import { Modal } from 'react-bootstrap';

export default function useModalNominatifAnggota() {
    const [showModal, setShowModal] = useState(false);
    const contentRef = useRef<HTMLDivElement>(null);
    const [pdfUrl, setPdfUrl] = useState<string | null>(null);
    const profil = useProfil();
    const anggota = useAnggota();

    // Generate PDF after modal is shown
    useEffect(() => {
        if (showModal && contentRef.current) {
            const opt = {
                margin: 0,
                filename: 'preview.pdf',
                image: { type: 'jpeg', quality: 1 },
                html2canvas: { scale: 2 },
                jsPDF: { unit: 'in', format: 'letter', orientation: 'landscape' },
            };

            html2pdf()
                .from(contentRef.current)
                .set(opt)
                .outputPdf('bloburl')
                .then((pdfBlobUrl: string) => {
                    setPdfUrl(pdfBlobUrl);
                });
        } else {
            setPdfUrl(null);
        }
    }, [showModal]);

    const open = () => {
        setShowModal(true);
    };

    const close = () => {
        setShowModal(false);
    };

    const Template = useMemo(() => {
        return (
            <div style={{ display: 'none' }}>
                <div ref={contentRef} className="bg-white p-6 shadow-md w-[21cm]">
                    <div
                        style={{
                            padding: '0.5cm',
                        }}
                    >
                        <div className="align-items-center d-flex gap-3">
                            <span>{profil.data?.logo && <img src={profil.data?.logo} style={{ maxHeight: 70 }} />}</span>
                            <span>
                                <h5 className="mb-1 fw-bold">{profil.data?.nama}</h5>
                                <h6 className="mb-1 fw-bold">KECAMATAN PURWOKERTO TIMUR KABUPATEN BANYUMAS PROVINSI JAWA TENGAH</h6>
                                <div className="mb-0">{profil.data?.alamat}</div>
                            </span>
                        </div>
                        <hr />
                        {anggota.data && anggota.data.length > 0 ? (
                            <div className="text-center">
                                <h5 className="mb-1 fw-bold">LAPORAN NOMINATIF ANGGOTA</h5>
                                <h6 className="mb-1 fw-bold">PERIODE: {new Date().toLocaleDateString()}</h6>
                            </div>
                        ) : (
                            <div className="text-center">
                                <h5 className="mb-1 fw-bold">Tidak ada data anggota</h5>
                            </div>
                        )}
                        {anggota.data && anggota.data.length > 0 && (
                            <table className="table-bordered mt-3 table"
                                style={{
                                    fontSize: '9px',
                                    fontFamily: 'Arial, sans-serif',
                                 }}
                            >
                                <thead>
                                    <tr>
                                        <th>No</th>
                                        <th>Nama</th>
                                        <th>NIK</th>
                                        <th>Alamat</th>
                                        <th>Jenis Kelamin</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {anggota.data.map((item: Anggota, idx: number) => (
                                        <tr key={item.id || idx}>
                                            <td>{idx + 1}</td>
                                            <td>{item.nama_lengkap}</td>
                                            <td>{item.nik}</td>
                                            <td>{item.alamat}</td>
                                            <td>{item.jenis_kelamin}</td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        )}
                    </div>
                </div>
            </div>
        );
    }, [anggota.data, profil.data?.alamat, profil.data?.logo, profil.data?.nama]);

    const modal = useMemo(() => {
        return (
            <>
                {/* Render hidden content only once for PDF generation */}
                {Template}

                {/* Modal for displaying PDF */}
                <Modal show={showModal} onHide={close} fullscreen>
                    <Modal.Header closeButton className="py-2">
                        <h6 className="modal-title m-0">Laporan Nominatif Anggota</h6>
                    </Modal.Header>
                    <Modal.Body className="p-0 d-flex">
                        {pdfUrl ? (
                            <iframe
                                src={pdfUrl}
                                title="Preview PDF"
                                className="border"
                                style={{
                                    width: '100%',
                                }}
                            />
                        ) : (
                            <div>Loading PDF...</div>
                        )}
                    </Modal.Body>
                    {/* <Modal.Footer>
                        <button type="button" className="btn btn-secondary" onClick={close}>
                            Tutup
                        </button>
                        <button type="button" className="btn btn-primary">
                            Proses
                        </button>
                    </Modal.Footer> */}
                </Modal>
            </>
        );
    }, [Template, pdfUrl, showModal]);

    return { modal, open, close };
}
