import { getLaporanTransaksiRekap, getLaporanTransaksiRincian } from '@/api/api_laporan';
import { alertError } from '@/components/costum/alert';
import { ButtonSubmit } from '@/components/costum/button_submit';
import { Select } from '@/components/costum/Select';
import { formatDate, formatNumber, formatTanggal } from '@/helper';
import { Filter, Statement, StatementModel } from '@/types';
import { usePage } from '@inertiajs/react';
import { useCallback, useMemo, useState } from 'react';
import { Modal } from 'react-bootstrap';

const OPTION_JENIS_LAPORAN_TRANSAKSI = [
    {
        label: '1 : Rincian Transaksi',
        value: '1',
    },
    {
        label: '2 : Rekap Transaksi',
        value: '2',
    },
];

const OPTION_JENIS_TRANSAKSI = [
    {
        label: '1.1 : Transaksi Kas',
        value: 'kas',
    },
    {
        label: '1.2 : Transaksi Bank',
        value: 'penempatan_bank',
    },
    {
        label: '1.3 : Transaksi Tabungan',
        value: 'tabungan',
    },
    {
        label: '1.4 : Transaksi Deposito',
        value: 'deposito',
    },
];



export default function LaporanTransaksiPage() {
    const { token } = usePage().props;
    const [laporan, setLaporan] = useState<Filter>({
        jenis_laporan: '',
        jenis_transaksi: '',
        tgl_awal: formatDate(new Date()),
        tgl_akhir: formatDate(new Date()),
    });

    const modalLaporanRincian = useModalLaporanRincian();
    const modalLaporanRekap = useModalLaporanRekap();

    const getLaporan = useCallback(async () => {
        console.log(laporan);
        if (laporan.jenis_laporan == '1') {
            const response = await getLaporanTransaksiRincian(laporan, token as string);
            const responseBody = await response.json();
            console.log(responseBody);
            modalLaporanRincian.open(responseBody, laporan);
        } else if (laporan.jenis_laporan == '2') {
            const response = await getLaporanTransaksiRekap(laporan, token as string);
            const responseBody = await response.json();
            console.log(responseBody);
            modalLaporanRekap.open(responseBody, laporan);
        } else {
            alertError('Jenis Laporan belum dipilih.');
        }
    }, [laporan, modalLaporanRekap, modalLaporanRincian, token]);

    return (
        <>
            <div>
                <div className="container" style={{ width: 640 }}>
                    <div className="card rounded-4 shadow-lg">
                        <div className="card-header py-3 bg-transparent">
                            <h5 className="m-0">Laporan Transaksi</h5>
                        </div>
                        <div className="card-body">
                            <div className="row mb-2">
                                <label className="col-form-label col-md-4">Periode</label>
                                <div className="col-md-8">
                                    <div className="input-group">
                                        <input
                                            className="form-control border-end-0 text-center"
                                            type="date"
                                            value={laporan.tgl_awal}
                                            onChange={(e) => {
                                                setLaporan({ ...laporan, tgl_awal: e.target.value });
                                            }}
                                        />
                                        <span className="input-group-text bg-white">sd</span>
                                        <input
                                            className="form-control border-start-0 text-center"
                                            type="date"
                                            value={laporan.tgl_akhir}
                                            onChange={(e) => {
                                                setLaporan({ ...laporan, tgl_akhir: e.target.value });
                                            }}
                                        />
                                    </div>
                                </div>
                            </div>
                            <div className="row mb-2">
                                <label className="col-form-label col-md-4">Jenis Laporan</label>
                                <div className="col-md-8">
                                    <Select
                                        options={OPTION_JENIS_LAPORAN_TRANSAKSI}
                                        placeholder="Pilih Jenis Laporan"
                                        onChange={(value: unknown) => {
                                            if (value) {
                                                const option = value as { label: string; value: string };
                                                setLaporan({ ...laporan, jenis_laporan: option.value, jenis_transaksi: '' });
                                            } else {
                                                setLaporan({ ...laporan, jenis_laporan: '', jenis_transaksi: '' });
                                            }
                                        }}
                                    />
                                </div>
                            </div>
                            {laporan.jenis_laporan == '1' && (
                                <div className="row mb-2">
                                    <label className="col-form-label col-md-4">Jenis Transaksi</label>
                                    <div className="col-md-8">
                                        <Select
                                            options={OPTION_JENIS_TRANSAKSI}
                                            placeholder="Pilih Jenis Transaksi"
                                            onChange={(value: unknown) => {
                                                if (value) {
                                                    const option = value as { label: string; value: string };
                                                    setLaporan({ ...laporan, jenis_transaksi: option.value });
                                                } else {
                                                    setLaporan({ ...laporan, jenis_transaksi: '' });
                                                }
                                            }}
                                        />
                                    </div>
                                </div>
                            )}
                        </div>
                        <div className="card-footer py-3 justify-content-end d-flex bg-transparent">
                            <ButtonSubmit className="btn btn-primary" onClick={async () => getLaporan()}>
                                Sumbit
                            </ButtonSubmit>
                        </div>
                    </div>
                </div>
            </div>
            {modalLaporanRincian.modal}
            {modalLaporanRekap.modal}
        </>
    );
}



const useModalLaporanRincian = () => {
    const [show, setShow] = useState<boolean>(false);
    const [laporan, setLaporan] = useState<Statement[]>();
    const [saldoAwal, setSaldoAwal] = useState<number>(0);
    const [filter, setFilter] = useState<Filter>();

    const open = (data: { kas_awal: number; statement: Statement[] }, filter: Filter) => {
        console.log(data);
        setFilter(filter);
        setLaporan(data.statement);
        setSaldoAwal(data.kas_awal);
        setShow(true);
    };
    const close = () => setShow(false);

    const modal = useMemo(() => {
        return (
            <Modal show={show} onHide={close} fullscreen>
                <Modal.Header closeButton>
                    <h6 className="m-0">Laporan Transaksi</h6>
                </Modal.Header>
                <Modal.Body className="bg-secondary">
                    <div className="bg-white p-3 container" style={{ width: 1024 }}>
                        <div className="text-center">
                            <h6 className="fw-bold">Laporan Transaksi Rincian</h6>
                            <h6 className="m-0">Periode</h6>
                        </div>
                        <div className="d-flex justify-content-center gap-2 align-items-center mb-3">
                            <h6 className="m-0">{formatTanggal(filter?.tgl_awal)}</h6>
                            <span>{` sampai `}</span>
                            <h6 className="m-0">{formatTanggal(filter?.tgl_akhir)}</h6>
                        </div>
                        {laporan?.length == 0 && (
                            <table className="table-bordered table-sm table">
                                <thead>
                                    <tr className="bg-light">
                                        <th style={{ width: 120 }} className="text-center">Tanggal</th>
                                        <th style={{ width: 120 }} className="text-center">Rekening</th>
                                        <th>Keterangan</th>
                                        <th style={{ width: 120 }} className="text-center">Masuk</th>
                                        <th style={{ width: 120 }}>Keluar</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td colSpan={5}className="text-center p-3">Tidak ada transaksi</td>
                                    </tr>
                                </tbody>
                                <tfoot>
                                    <tr className="bg-light">
                                        <td colSpan={3} className="fw-bold text-end">
                                            Sub Total
                                        </td>
                                        <td className="fw-bold text-end">0</td>
                                        <td className="fw-bold text-end">0</td>
                                    </tr>
                                </tfoot>
                            </table>
                        )}
                        {laporan?.length != 0 &&
                            laporan?.map((item) => {
                                return (
                                    <table className="table-bordered table-sm table" key={item.jenis_transaksi}>
                                        <thead>
                                            <tr>
                                                <th colSpan={5}>{item.jenis_transaksi?.toUpperCase()}</th>
                                            </tr>
                                        </thead>
                                        <thead>
                                            <tr className="bg-light">
                                                <th className="text-center">Tanggal</th>
                                                <th className="text-center">Rekening</th>
                                                <th>Keterangan</th>
                                                <th className="text-center">Masuk</th>
                                                <th>Keluar</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {item.data?.map((data: StatementModel, index: number) => {
                                                return (
                                                    <tr key={index}>
                                                        <td width={120} className="text-center">
                                                            {formatDate(data.trans_tglbuku)}
                                                        </td>
                                                        <td width={120} className="text-center">
                                                            {data.rekening}
                                                        </td>
                                                        <td>{data.keterangan}</td>
                                                        <td width={120} className="text-end">
                                                            {formatNumber(data.masuk)}
                                                        </td>
                                                        <td width={120} className="text-end">
                                                            {formatNumber(data.keluar)}
                                                        </td>
                                                    </tr>
                                                );
                                            })}
                                        </tbody>
                                        <tfoot>
                                            <tr className="bg-light">
                                                <td colSpan={3} className="fw-bold text-end">
                                                    Sub Total
                                                </td>
                                                <td className="fw-bold text-end">
                                                    {formatNumber(item.data?.reduce((total, data) => total + (Number(data.masuk) || 0), 0))}
                                                </td>
                                                <td className="fw-bold text-end">
                                                    {formatNumber(item.data?.reduce((total, data) => total + (Number(data.keluar) || 0), 0))}
                                                </td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                );
                            })}
                        <table className="table-bordered table">
                            <tfoot>
                                <tr className="bg-light">
                                    <td className="fw-bold text-end">Total</td>
                                    <td width={120} className="fw-bold text-end">
                                        {formatNumber(
                                            laporan?.reduce(
                                                (total, item) =>
                                                    total + (item.data?.reduce((subTotal, data) => subTotal + (Number(data.masuk) || 0), 0) || 0),
                                                0,
                                            ),
                                        )}
                                    </td>
                                    <td width={120} className="fw-bold text-end">
                                        {formatNumber(
                                            laporan?.reduce(
                                                (total, item) =>
                                                    total + (item.data?.reduce((subTotal, data) => subTotal + (Number(data.keluar) || 0), 0) || 0),
                                                0,
                                            ),
                                        )}
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                        <div className="row">
                            <label className="col-form-label col-md-2">Saldo Awal</label>
                            <label className="col-form-label col-md-2 text-end">{formatNumber(saldoAwal)}</label>
                        </div>
                        <div className="row">
                            <label className="col-form-label col-md-2">Mutasi</label>
                            <label className="col-form-label col-md-2 text-end">
                                {formatNumber(
                                    (laporan?.reduce(
                                        (total, item) =>
                                            total + (item.data?.reduce((subTotal, data) => subTotal + (Number(data.masuk) || 0), 0) || 0),
                                        0,
                                    ) || 0) -
                                        (laporan?.reduce(
                                            (total, item) =>
                                                total + (item.data?.reduce((subTotal, data) => subTotal + (Number(data.keluar) || 0), 0) || 0),
                                            0,
                                        ) || 0),
                                )}
                            </label>
                        </div>
                        <div className="row">
                            <label className="col-form-label col-md-2">Saldo Akhir</label>
                            <label className="col-form-label col-md-2 text-end">
                                {formatNumber(
                                    Number(saldoAwal) +
                                        (laporan?.reduce(
                                            (total, item) =>
                                                total + (item.data?.reduce((subTotal, data) => subTotal + (Number(data.masuk) || 0), 0) || 0),
                                            0,
                                        ) || 0) -
                                        (laporan?.reduce(
                                            (total, item) =>
                                                total + (item.data?.reduce((subTotal, data) => subTotal + (Number(data.keluar) || 0), 0) || 0),
                                            0,
                                        ) || 0),
                                )}
                            </label>
                        </div>
                    </div>
                </Modal.Body>
                <Modal.Footer></Modal.Footer>
            </Modal>
        );
    }, [filter?.tgl_akhir, filter?.tgl_awal, laporan, saldoAwal, show]);

    return { modal, open, close };
};

const useModalLaporanRekap = () => {
    const [show, setShow] = useState<boolean>(false);
    const [laporan, setLaporan] = useState<Statement[]>();
    const [filter, setFilter] = useState<Filter>();

    const open = (data: { kas_awal: number; statement: Statement[] }, filter: Filter) => {
        setFilter(filter);
        setLaporan(data.statement);
        setShow(true);
    };
    const close = () => setShow(false);

    const modal = useMemo(() => {
        return (
            <Modal show={show} onHide={close} fullscreen>
                <Modal.Header closeButton>
                    <h6 className="m-0">Laporan Transaksi Rekap</h6>
                </Modal.Header>
                <Modal.Body className="bg-secondary">
                    <div className="bg-white p-3 container" style={{ width: 1024 }}>
                        <div className="text-center">
                            <h6 className="fw-bold">Laporan Transaksi Rekap</h6>
                            <h6 className="m-0">Periode</h6>
                        </div>
                        <div className="d-flex justify-content-center gap-2 align-items-center mb-3">
                            <h6 className="m-0">{formatTanggal(filter?.tgl_awal)}</h6>
                            <span>{` sampai `}</span>
                            <h6 className="m-0">{formatTanggal(filter?.tgl_akhir)}</h6>
                        </div>
                        {laporan?.map((item) => {
                            return (
                                <table className="table-bordered table-sm table">
                                    <thead>
                                        <tr>
                                            <th colSpan={5}>{item.jenis_transaksi?.toUpperCase()}</th>
                                        </tr>
                                    </thead>
                                    <thead>
                                        <tr className="bg-light">
                                            <th>No</th>
                                            <th>Jenis</th>
                                            <th>Keterangan</th>
                                            <th>Masuk</th>
                                            <th>Keluar</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {item.data?.map((data, index) => {
                                            return (
                                                <tr key={index}>
                                                    <td className="text-center" width={50}>
                                                        {index + 1}
                                                    </td>
                                                    <td width={150}>{data.jenis_transaksi}</td>
                                                    <td>{`${data.trans_kode} : ${data.transaksi?.nama}`}</td>
                                                    <td width={120} className="text-end">
                                                        {formatNumber(data.masuk)}
                                                    </td>
                                                    <td width={120} className="text-end">
                                                        {formatNumber(data.keluar)}
                                                    </td>
                                                </tr>
                                            );
                                        })}
                                    </tbody>
                                    <tfoot>
                                        <tr className="bg-light">
                                            <td colSpan={3} className="fw-bold text-end">
                                                Sub Total
                                            </td>
                                            <td className="fw-bold text-end">
                                                {formatNumber(item.data?.reduce((total, data) => total + (Number(data.masuk) || 0), 0))}
                                            </td>
                                            <td className="fw-bold text-end">
                                                {formatNumber(item.data?.reduce((total, data) => total + (Number(data.keluar) || 0), 0))}
                                            </td>
                                        </tr>
                                    </tfoot>
                                </table>
                            );
                        })}
                        <table className="table-bordered table">
                            <tfoot>
                                <tr className="bg-light">
                                    <td className="fw-bold text-end">Total</td>
                                    <td width={120} className="fw-bold text-end">
                                        {formatNumber(
                                            laporan?.reduce(
                                                (total, item) =>
                                                    total + (item.data?.reduce((subTotal, data) => subTotal + (Number(data.masuk) || 0), 0) || 0),
                                                0,
                                            ),
                                        )}
                                    </td>
                                    <td width={120} className="fw-bold text-end">
                                        {formatNumber(
                                            laporan?.reduce(
                                                (total, item) =>
                                                    total + (item.data?.reduce((subTotal, data) => subTotal + (Number(data.keluar) || 0), 0) || 0),
                                                0,
                                            ),
                                        )}
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </Modal.Body>
                <Modal.Footer></Modal.Footer>
            </Modal>
        );
    }, [filter?.tgl_akhir, filter?.tgl_awal, laporan, show]);

    return { modal, open, close };
};
