import { getSaldoAkun } from '@/api/api_jurnal';
import { getBukuBesar } from '@/api/api_laporan';
import { ButtonSubmit } from '@/components/costum/button_submit';
import { useModalBrowseAkun } from '@/components/modal/modalBrowseAkun';
import { formatDate, formatNumber, formatTanggal, yesterday } from '@/helper';
import { Akun, Filter, StatementModel } from '@/types';
import { usePage } from '@inertiajs/react';
import { useCallback, useMemo, useState } from 'react';
import { Modal } from 'react-bootstrap';

export interface LaporanBukuBesarProps {
    status?: number;
    tgl_awal?: string;
    tgl_akhir?: string;
    akun?: Akun;
    kode_akun?: string;
    saldo_awal?: number;
    saldo_akhir?: number;
}

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

    const modalBukuBesar = useModalBukuBesar();
    const modalAkun = useModalBrowseAkun({
        onSelected: ({ akun }) => {
            console.log(akun);
            setLaporan({
                ...laporan,
                akun: akun,
                kode_akun: akun?.kode_akun,
            });
        },
    });

    const getLaporan = useCallback(async () => {
        const response = await getBukuBesar(laporan, token as string);
        const responseBody = await response.json();

        const getSaldo = await getSaldoAkun(laporan.kode_akun!, yesterday(laporan.tgl_awal!), token as string);
        const saldo = await getSaldo.json();

        modalBukuBesar.open(responseBody, { ...laporan, saldo_awal: saldo });
    }, [laporan, modalBukuBesar, 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">Buku Besar</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">Akun</label>
                                <div className="col-md-6">
                                    <div className="input-group">
                                        <input className="form-control" readOnly placeholder="Kode Akun" value={laporan.akun?.kode_akun ?? ''} />
                                        <button
                                            className="btn btn-primary"
                                            onClick={() => {
                                                modalAkun.open();
                                            }}
                                        >
                                            Browse
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div className="row mb-2">
                                <label className="col-form-label col-md-4"></label>
                                <div className="col-md-8">
                                    <input className="form-control" readOnly placeholder="Nama Akun" value={laporan.akun?.nama ?? ''} />
                                </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>
            {modalBukuBesar.modal}
            {modalAkun.modal}
        </>
    );
}

const useModalBukuBesar = () => {
    const [show, setShow] = useState<boolean>(false);
    const [laporan, setLaporan] = useState<StatementModel[]>([]);
    const [filter, setFilter] = useState<LaporanBukuBesarProps>();

    const open = (data: StatementModel[], filter: Filter & { saldo_awal: number }) => {
        setFilter(filter);
        setLaporan(data);
        setShow(true);
    };
    const close = () => setShow(false);

    const modal = useMemo(() => {
        let saldo = filter?.saldo_awal ?? 0;
        return (
            <Modal show={show} onHide={close} fullscreen>
                <Modal.Header closeButton>
                    <h6 className="m-0">Buku Besar</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 Buku Besar</h6>
                            <h6 className="m-0">Periode</h6>
                        </div>
                        <div className="d-flex justify-content-center gap-2 align-items-center">
                            <h6 className="m-0">{formatTanggal(filter?.tgl_awal)}</h6>
                            <span>{` sampai `}</span>
                            <h6 className="m-0">{formatTanggal(filter?.tgl_akhir)}</h6>
                        </div>
                        <div className="mb-3 text-center">
                            <label className="col-form-label col-md-4">
                                {filter?.akun?.kode_akun} - {filter?.akun?.nama}
                            </label>
                        </div>
                        <table className="table-bordered table-sm table">
                            <thead>
                                <tr className="bg-light">
                                    <th className="text-center" style={{ width: 120 }}>
                                        Tanggal
                                    </th>
                                    <th className="text-center" style={{ width: 250 }}>
                                        Transaksi
                                    </th>
                                    <th className="text-center">Keterangan</th>
                                    <th className="text-center" style={{ width: 120 }}>
                                        Debet
                                    </th>
                                    <th className="text-center" style={{ width: 120 }}>
                                        Kredit
                                    </th>
                                    <th className="text-center" style={{ width: 120 }}>
                                        saldo
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                {laporan.length == 0 && (
                                    <tr>
                                        <td colSpan={6} className="p-3 text-center">
                                            Tidak ada transaksi
                                        </td>
                                    </tr>
                                )}
                                {laporan.length != 0 &&
                                    laporan?.map((item: StatementModel, idx: number) => (
                                        <tr key={idx}>
                                            <td width={120} className="text-center">
                                                {formatDate(item.trans_tglbuku)}
                                            </td>
                                            <td width={150}>{`${item.trans_kode} : ${item.transaksi?.nama}`}</td>
                                            <td>{item.keterangan}</td>
                                            <td width={120} className="text-end">
                                                {formatNumber(item.debet)}
                                            </td>
                                            <td width={120} className="text-end">
                                                {formatNumber(item.kredit)}
                                            </td>
                                            <td width={120} className="text-end">
                                                {formatNumber(
                                                    filter?.akun?.jurnal == 'D'
                                                        ? (saldo += item.debet - item.kredit)
                                                        : (saldo += item.kredit - item.debet),
                                                )}
                                            </td>
                                        </tr>
                                    ))}
                            </tbody>
                            <tfoot>
                                <tr className="bg-light">
                                    <td colSpan={3} className="fw-bold text-end">
                                        Total
                                    </td>
                                    <td className="fw-bold text-end">
                                        {formatNumber(laporan.reduce((total, item) => total + (item.debet ?? 0), 0))}
                                    </td>
                                    <td className="fw-bold text-end">
                                        {formatNumber(laporan.reduce((total, item) => total + (item.kredit ?? 0), 0))}
                                    </td>
                                    <td className="fw-bold text-end">{formatNumber(saldo)}</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(filter?.saldo_awal)}</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.debet ?? 0), 0) -
                                        laporan.reduce((total, item) => total + (item.kredit ?? 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(filter?.saldo_awal) +
                                        laporan.reduce((total, item) => total + (item.debet ?? 0), 0) -
                                        laporan.reduce((total, item) => total + (item.kredit ?? 0), 0),
                                )}
                            </label>
                        </div>
                    </div>
                </Modal.Body>
                <Modal.Footer></Modal.Footer>
            </Modal>
        );
    }, [filter?.akun?.jurnal, filter?.akun?.kode_akun, filter?.akun?.nama, filter?.saldo_awal, filter?.tgl_akhir, filter?.tgl_awal, laporan, show]);

    return { modal, open, close };
};
