import { getJurnalByTransId } from '@/api/api_jurnal';
import { formatNumber } from '@/helper';
import { JurnalTransaksi, TransaksiInterface } from '@/types';
import { Check, Trash } from 'lucide-react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ButtonSubmit } from '../costum/button_submit';
import { Column } from '../costum/DataTable';
import { EmptyJurnal, LoadingJurnal } from './modalJurnal';
import { usePage } from '@inertiajs/react';

//
interface CustomModalProps {
    show: boolean;
    onClose: () => void;
    size?: 'sm' | 'md' | 'lg' | 'xl';
    children: React.ReactNode;
    onExited?: () => void;
}

const modalSizeClass = {
    sm: 'modal-sm',
    md: '',
    lg: 'modal-lg',
    xl: 'modal-xl',
};

export const CustomModal: React.FC<CustomModalProps> = ({ show, onClose, size = 'md', children, onExited }) => {
    const modalRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (show) {
            document.body.style.overflow = 'hidden';
        } else {
            document.body.style.overflow = '';
            if (onExited) onExited();
        }
        return () => {
            document.body.style.overflow = '';
        };
    }, [show, onExited]);

    useEffect(() => {
        const handleKeyDown = (e: KeyboardEvent) => {
            if (e.key === 'Escape' && show) {
                onClose();
            }
        };
        window.addEventListener('keydown', handleKeyDown);
        return () => window.removeEventListener('keydown', handleKeyDown);
    }, [show, onClose]);

    if (!show) return null;

    return (
        <div
            className="custom-modal-backdrop"
            style={{
                position: 'fixed',
                top: 0,
                left: 0,
                width: '100vw',
                height: '100vh',
                background: 'rgba(0,0,0,0.5)',
                zIndex: 1050,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
            }}
            onClick={onClose}
            aria-modal="true"
            role="dialog"
        >
            <div
                // className={`custom-modal-content ${modalSizeClass[size]}`}
                className={`custom-modal-content`}
                style={{
                    borderRadius: 8,
                    maxHeight: '90vh',
                    overflow: 'auto',
                    minWidth: 1320,
                    maxWidth: 1320,
                    // minWidth: size === 'xl' ? 900 : size === 'lg' ? 700 : 500,
                    boxShadow: '0 2px 16px rgba(0,0,0,0.2)',
                    position: 'relative',
                }}
                ref={modalRef}
                onClick={(e) => e.stopPropagation()}
            >
                {children}
            </div>
        </div>
    );
};

// Contoh penggunaan CustomModal untuk modal jurnal
export function useCostumModalJurnal<T>({
    column,
    onValidate,
    onDelete,
    onPrint,
}: {
    column?: Column<T>[];
    onValidate?: (transId?: string) => boolean | Promise<boolean>;
    onDelete?: (transId?: string) => boolean | Promise<boolean>;
    onPrint?: (transId?: string) => void;
}) {
    const [show, setShow] = useState(false);
    const [jurnal, setJurnal] = useState<JurnalTransaksi[]>();
    const [transaksi, setTransaksi] = useState<TransaksiInterface>();
    const [loading, setLoading] = useState(true);
    const { token } = usePage().props;

    const open = (trans: TransaksiInterface) => {
        setShow(true);
        setTransaksi(trans);
        getJurnalTransaksi(trans.trans_id!).then(() => {
            setLoading(false);
        });
    };

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

    const getJurnalTransaksi = async (trans_id: string) => {
        const response = await getJurnalByTransId(trans_id, token as string);
        const responseBody = await response.json();
        if (response.status == 200) {
            setJurnal(responseBody);
        }
    };

    const DisplayTableTransaksi = useCallback(
        () => (
            <table className="table-bordered table-sm mb-0 table table-fixed" style={{ width: '100%' }}>
                <thead>
                    <tr>
                        {column &&
                            column?.map((col, index) => {
                                if (index < column.length - 1) {
                                    return (
                                        <th key={index} style={col.style} className={col.class}>
                                            {col.label}
                                        </th>
                                    );
                                }
                                return null;
                            })}
                    </tr>
                </thead>
                <tbody>
                    {column &&
                        [transaksi].map((item, index) => {
                            return (
                                <tr key={index} style={{ verticalAlign: 'middle' }}>
                                    {column.map((col, colIndex) => {
                                        if (colIndex < column.length - 1) {
                                            return (
                                                <td key={colIndex} width={col.width} align={col.align} className={col.class} style={col.style}>
                                                    {item && col.value ? (col.value(item, index) ?? '') : <div style={{ height: '22.75px' }}></div>}
                                                </td>
                                            );
                                        }
                                        return null;
                                    })}
                                </tr>
                            );
                        })}
                </tbody>
            </table>
        ),
        [column, transaksi],
    );

    const DisplayTableJurnal = useCallback(
        ({ loading, transaksi }: { loading: boolean; transaksi?: TransaksiInterface }) => {
            if (loading) {
                return <LoadingJurnal className='mt-3' />;
            }
            if (jurnal && transaksi) {
                if (transaksi.status == 9 || jurnal.length == 0) {
                    return <EmptyJurnal />;
                }
                if (transaksi.status == 1) {
                    return (
                        <div>
                            <h6 className="my-3">Jurnal Transaksi</h6>
                            <table className="table-bordered table-sm table-responsive mb-0 table table-fixed" style={{ width: '100%' }}>
                                <thead>
                                    <tr>
                                        <th className="text-center">#</th>
                                        <th className="text-center">Kode Akun</th>
                                        <th className="ellipsis text-center">Nama Akun</th>
                                        <th className="text-center">Debet</th>
                                        <th className="text-center">Kredit</th>
                                        <th className="ellipsis">Keterangan</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {jurnal.map((item, index) => (
                                        <tr key={index}>
                                            <td className="text-center" width={50}>
                                                {index + 1}
                                            </td>
                                            <td className="text-center" width={100}>
                                                {item.akun.kode_akun}
                                            </td>
                                            <td width={250}>{item.akun.nama}</td>
                                            <td width={120} className="text-end">
                                                {formatNumber(item.debet)}
                                            </td>
                                            <td width={120} className="text-end">
                                                {formatNumber(item.kredit)}
                                            </td>
                                            <td className="ellipsis">{item.keterangan}</td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    );
                }
            }
            return <EmptyJurnal />;
        },
        [jurnal],
    );

    const modal = useMemo(() => {
        return (
            <CustomModal show={show} onClose={close} size="xl" onExited={() => setLoading(true)}>
                <div className="modal-header bg-white p-3 border-bottom-1" style={{ borderTopLeftRadius: 8, borderTopRightRadius: 8 }}>
                    <h5 className="mb-0">Transaksi ID : {transaksi?.trans_id}</h5>
                </div>
                <div className="modal-body p-3 bg-white">
                    <DisplayTableTransaksi />
                    <DisplayTableJurnal loading={loading} transaksi={transaksi} />
                </div>
                <div className="modal-footer bg-white p-3 d-flex gap-2" style={{ borderBottomLeftRadius: 8, borderBottomRightRadius: 8, borderTop: '1px solid #dee2e6' }}>
                    <button className="btn btn-secondary" onClick={close}>
                        Kembali
                    </button>
                    {onPrint && (
                        <button className="btn btn-primary align-center flex" onClick={() => onPrint(transaksi?.trans_id)}>
                            <i className="ri-printer-line mr-2" />
                            Cetak
                        </button>
                    )}
                    {transaksi?.status == 1 && (
                        <ButtonSubmit
                            className="btn btn-danger align-center flex"
                            icon={<Trash size={18} />}
                            onClick={async () => {
                                if (onDelete) {
                                    const deleted = await onDelete(transaksi.trans_id);
                                    if (deleted) {
                                        close();
                                    }
                                }
                            }}
                        >
                            Batalkan Transaksi
                        </ButtonSubmit>
                    )}
                    {transaksi?.status == 9 && (
                        <ButtonSubmit
                            className="btn btn-success"
                            icon={<Check size={18} />}
                            onClick={async () => {
                                if (onValidate) {
                                    const validated = await onValidate(transaksi.trans_id);
                                    if (validated) {
                                        close();
                                    }
                                }
                            }}
                        >
                            Validasi Transaksi
                        </ButtonSubmit>
                    )}
                </div>
            </CustomModal>
        );
    }, [show, transaksi, DisplayTableTransaksi, DisplayTableJurnal, loading, onPrint, onDelete, onValidate]);

    return { modal, open, close };
}
