import { getJurnalByTransId } from '@/api/api_jurnal';
import { formatNumber } from '@/helper';
import { JurnalTransaksi, TransaksiInterface } from '@/types';
import { Check, Info, Trash } from 'lucide-react';
import { useCallback, useMemo, useState } from 'react';
import { Modal, Spinner } from 'react-bootstrap';
import { Column } from '../costum/DataTable';
import { ButtonSubmit } from '../costum/button_submit';
import { usePage } from '@inertiajs/react';

export default function useModalJurnal<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();
        console.log(responseBody);
        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 />;
            }
            if (jurnal && transaksi) {
                if (transaksi.status == 9 || jurnal.length == 0) {
                    return <EmptyJurnal />;
                }
                if (transaksi.status == 1) {
                    return (
                        <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>
                    );
                }
            }
            return <EmptyJurnal />;
        },
        [jurnal],
    );

    const modal = useMemo(() => {
        return (
            <>
                <Modal show={show} onHide={() => close()} size="xl" aria-hidden="false" onExited={() => setLoading(true)}>
                    <Modal.Header className="bg-primary text-white">
                        <h5 className="mb-0">Jurnal : {transaksi?.trans_id}</h5>
                    </Modal.Header>
                    <Modal.Body>
                        <DisplayTableTransaksi />
                        <h6 className="my-3">Jurnal Transaksi</h6>
                        <DisplayTableJurnal loading={loading} transaksi={transaksi} />
                    </Modal.Body>
                    <Modal.Footer>
                        <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>
                        )}
                    </Modal.Footer>
                </Modal>
            </>
        );
    }, [show, transaksi, DisplayTableTransaksi, DisplayTableJurnal, loading, onPrint, onDelete, onValidate]);

    return { modal, open, close };
}

export const EmptyJurnal = () => {
    return (
        <div className="alert alert-danger mb-0 mt-3">
            <div className="d-flex align-items-center flex-column gap-2">
                <Info />
                <span>Jurnal transaksi tidak ditemukan.</span>
            </div>
        </div>
    );
};

export const LoadingJurnal = ({ className }: { className?: string }) => {
    return (
        <div className={`d-flex justify-content-center align-items-center p-3 ${className ?? ''}`}>
            <Spinner size="sm" />
        </div>
    );
};
