import { saveTransaksiTabungan } from '@/api/api_tabungan';
import { JENIS_TRANSAKSI_TABUNGAN } from '@/const';
import { formatDate, formatTanggal } from '@/helper';
import { Tabungan, TransaksiKas, TransaksiTabungan } from '@/types';
import { Save, X } from 'lucide-react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Modal } from 'react-bootstrap';
import { NumericFormat } from 'react-number-format';
import { alertError, alertSuccess } from '../costum/alert';
import { ButtonSubmit } from '../costum/button_submit';
import { Select } from '../costum/Select';
import { useModalBrowseRekeningTabungan } from './modalBrowseRekeningTabungan';
import { useTabungan } from '@/useQuery/query';
import { usePage } from '@inertiajs/react';

export const useModalTransaksiTabungan = ({ onSubmit }: { onSubmit?: (user: TransaksiKas) => boolean | Promise<boolean> }) => {
    const [showModal, setShowModal] = useState(false);
    const [validasi, setValidasi] = useState<boolean>(false);
    const [loading, setLoading] = useState<boolean>(false);
    const [dataTransaksi, setDataTransaksi] = useState<TransaksiTabungan>({
        trans_tglbuku: formatDate(new Date()),
    });
    const { token } = usePage().props;

    const tabungan = useTabungan();

    const modalRekening = useModalBrowseRekeningTabungan({
        onSelected: (tab: Tabungan) => {
            console.log(tab);
            setDataTransaksi({ ...dataTransaksi, tabungan: tab, rekening: tab.rekening });
        },
    });

    const open = (data?: TransaksiKas) => {
        if (data) {
            setDataTransaksi(data);
        }
        setShowModal(true);
    };

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

    const clear = () => {
        setDataTransaksi({
            trans_tglbuku: formatDate(new Date()),
        });
        setValidasi(false);
        setLoading(false);
    };

    useEffect(() => {
        if (dataTransaksi?.trans_kode) {
            const saldo_awal = dataTransaksi.tabungan?.saldo ?? 0;
            const nominal = dataTransaksi?.nominal ?? 0;
            const trans_kode = dataTransaksi?.trans_kode;
            if (trans_kode == '31') {
                setDataTransaksi((prev) => ({ ...prev, saldo_akhir: saldo_awal + nominal }));
            }
            if (trans_kode == '32') {
                setDataTransaksi((prev) => ({ ...prev, saldo_akhir: saldo_awal - nominal }));
            }
        } else {
            setDataTransaksi((prev) => ({ ...prev, saldo_akhir: undefined }));
        }
    }, [dataTransaksi?.nominal, dataTransaksi.tabungan?.saldo, dataTransaksi?.trans_kode]);

    const saveTransaksi = useCallback(async () => {
        const response = await saveTransaksiTabungan(dataTransaksi, token as string);
        const responseBody = await response.json();
        if (response.status == 200 || response.status == 201) {
            setValidasi(true);
            tabungan.refetch();
            if (onSubmit) {
                const result = await onSubmit(responseBody);
                if (result === false) {
                    setLoading(false);
                    return;
                }
            }
            await alertSuccess('Transaksi Berhasil disimpan');
            close();
        } else {
            await alertError(responseBody.message);
        }
    }, [dataTransaksi, onSubmit, tabungan, token]);

    const modal = useMemo(() => {
        return (
            <>
                <Modal show={showModal} onHide={close} onExited={clear} size="lg">
                    <Modal.Header closeButton>
                        <h5 className="mb-0">Transaksi Kas</h5>
                    </Modal.Header>
                    <Modal.Body>
                        <div className="form-group row mb-2">
                            <label className="col-form-label col-md-3">Tanggal</label>
                            <div className="col-md-4">
                                <div className="input-group">
                                    <input
                                        type="date"
                                        className="form-control text-center"
                                        value={dataTransaksi?.trans_tglbuku ?? ''}
                                        onChange={(e) => {
                                            setDataTransaksi({ ...dataTransaksi, trans_tglbuku: e.target.value });
                                        }}
                                    />
                                </div>
                            </div>
                            <label className="col-form-label col-md-5">
                                <i>{formatTanggal(dataTransaksi?.trans_tglbuku)}</i>
                            </label>
                        </div>
                        <div className="form-group row mb-2">
                            <label className="col-form-label col-md-3">Rekening</label>
                            <div className="col-md-5">
                                <div className="input-group">
                                    <input className="form-control" placeholder="Rekening" readOnly value={dataTransaksi?.tabungan?.rekening ?? ''} />
                                    <button className="btn btn-primary" onClick={() => modalRekening.open()}>
                                        Browse
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div id="data-anggota">
                            <div className="form-group row mb-2">
                                <label className="col-form-label col-md-3">Nama Anggota</label>
                                <div className="col-md-9">
                                    <input
                                        className="form-control"
                                        placeholder="Nama Anggota"
                                        readOnly
                                        value={dataTransaksi?.tabungan?.anggota?.nama_lengkap ?? ''}
                                    />
                                </div>
                            </div>
                            <div className="form-group row mb-2">
                                <label className="col-form-label col-md-3">Alamat</label>
                                <div className="col-md-9">
                                    <input
                                        className="form-control"
                                        placeholder="Alamat"
                                        readOnly
                                        value={dataTransaksi?.tabungan?.anggota?.alamat ?? ''}
                                    />
                                </div>
                            </div>
                            <div className="row mb-2">
                                <label className="col-form-label col-md-3" />
                                <div className="col-md-3">
                                    <div className="input-group">
                                        <span className="input-group-text bg-white border-end-0">RT</span>
                                        <input
                                            className="form-control border-start-0 text-center"
                                            readOnly
                                            value={dataTransaksi?.tabungan?.anggota?.rt ?? ''}
                                        />
                                    </div>
                                </div>
                                <div className="col-md-3">
                                    <div className="input-group">
                                        <span className="input-group-text bg-white border-end-0">RW</span>
                                        <input
                                            className="form-control border-start-0 text-center"
                                            readOnly
                                            value={dataTransaksi?.tabungan?.anggota?.rw ?? ''}
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>
                        <hr />
                        <div id="data-transaksi">
                            <div className="form-group row mb-2">
                                <label className="col-form-label col-md-3">Jenis Transaksi</label>
                                <div className="col-md-7">
                                    <Select
                                        placeholder="Pilih Jenis Transaksi"
                                        options={JENIS_TRANSAKSI_TABUNGAN.map((item) => ({ label: item.label, value: item.value }))}
                                        onChange={(newValue: unknown) => {
                                            const option = newValue as { label: string; value: string } | null;
                                            setDataTransaksi({ ...dataTransaksi, trans_kode: option?.value });
                                        }}
                                    />
                                </div>
                            </div>
                            <div className="form-group row mb-2">
                                <label className="col-form-label col-md-3">Saldo Awal</label>
                                <div className="col-md-4">
                                    <div className="input-group">
                                        <span className="input-group-text bg-white border-end-0">Rp</span>
                                        <NumericFormat
                                            className="form-control border-start-0 text-end"
                                            readOnly
                                            thousandSeparator="."
                                            decimalSeparator=","
                                            value={dataTransaksi?.tabungan?.saldo ?? '0'}
                                        />
                                    </div>
                                </div>
                            </div>
                            <div className="form-group row mb-2">
                                <label className="col-form-label col-md-3">Nominal</label>
                                <div className="col-md-4">
                                    <div className="input-group">
                                        <span className="input-group-text bg-white border-end-0">Rp</span>
                                        <NumericFormat
                                            className="form-control border-start-0 text-end"
                                            thousandSeparator="."
                                            decimalSeparator=","
                                            value={dataTransaksi?.nominal ?? ''}
                                            placeholder="0"
                                            onValueChange={(values) => {
                                                setDataTransaksi({ ...dataTransaksi, nominal: parseInt(values.value) });
                                            }}
                                        />
                                    </div>
                                </div>
                            </div>
                            <div className="form-group row mb-2">
                                <label className="col-form-label col-md-3">Saldo Akhir</label>
                                <div className="col-md-4">
                                    <div className="input-group">
                                        <span className="input-group-text bg-white border-end-0">Rp</span>
                                        <NumericFormat
                                            className="form-control border-start-0 text-end"
                                            readOnly
                                            thousandSeparator="."
                                            decimalSeparator=","
                                            value={dataTransaksi?.saldo_akhir ?? 0}
                                        />
                                    </div>
                                </div>
                            </div>
                            <hr className="mt-3" />
                            <div className="form-group row">
                                <label className="col-form-label col-md-3">Keterangan</label>
                                <div className="col-md-9">
                                    <input
                                        className="form-control"
                                        placeholder="Keterangan Transaksi"
                                        value={dataTransaksi?.keterangan ?? ''}
                                        onChange={(e) => {
                                            setDataTransaksi({ ...dataTransaksi, keterangan: e.target.value });
                                        }}
                                    />
                                </div>
                            </div>
                        </div>
                    </Modal.Body>
                    <Modal.Footer className="justify-content-between d-flex">
                        <button onClick={close} className="btn btn-danger align-items-center d-flex gap-2">
                            <X size={18} />
                            Tutup
                        </button>
                        <ButtonSubmit
                            className="btn btn-success"
                            icon={<Save size={18} />}
                            disable={validasi || loading}
                            onClick={async () => {
                                await saveTransaksi();
                            }}
                        >
                            Simpan
                        </ButtonSubmit>
                    </Modal.Footer>
                </Modal>
                {modalRekening.modal}
            </>
        );
    }, [dataTransaksi, loading, modalRekening, saveTransaksi, showModal, validasi]);

    return { modal, open, close };
};
