import { saveDeposito } from '@/api/api_deposito';
import { alertError, alertSuccess } from '@/components/costum/alert';
import { ButtonSubmit } from '@/components/costum/button_submit';
import { SelectProdukDeposito } from '@/components/costum/SelectProdukDeposito';
import { useModalBrowseAnggota } from '@/components/modal/modalBrowseAnggota';
import { useModalBrowseRekeningTabungan } from '@/components/modal/modalBrowseRekeningTabungan';
import { formatDate, hitungJatuhTempo } from '@/helper';
import { Anggota, Deposito, ProdukDeposito, Tabungan } from '@/types';
import { useDetailDeposito, useProdukDeposito } from '@/useQuery/query';
import { usePage } from '@inertiajs/react';
import { Save, X } from 'lucide-react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Modal } from 'react-bootstrap';
import { NumericFormat } from 'react-number-format';

export const useModalDetailDeposito = ({ onSubmit }: { onSubmit?: (user: Tabungan) => boolean | Promise<boolean> }) => {
    const { token } = usePage().props;
    const [showModal, setShowModal] = useState(false);
    const [validasi, setValidasi] = useState<boolean>(false);
    const [loading, setLoading] = useState<boolean>(false);

    const [dataDeposito, setDataDeposito] = useState<Deposito>({
        tgl_valuta: formatDate(new Date()),
    });

    const detailDeposito = useDetailDeposito(dataDeposito?.rekening);

    const modalAnggota = useModalBrowseAnggota({
        onSelected: (anggota: Anggota) => {
            setDataDeposito({
                ...dataDeposito,
                anggota: anggota,
            });
        },
    });

    const modalRekening = useModalBrowseRekeningTabungan({
        onSelected: (tab: Tabungan) => {
            setDataDeposito({
                ...dataDeposito,
                tabungan: tab,
                rekening_tabungan: tab.rekening,
            });
        },
    });

    const produkDeposito = useProdukDeposito();

    const saveDataDeposito = useCallback(async () => {
        const response = await saveDeposito(dataDeposito!, token as string);
        const responseBody = await response.json();

        if (response.status == 201 || response.status == 200) {
            const rekening = responseBody.rekening;
            setDataDeposito({
                ...dataDeposito,
                rekening: rekening,
            });
            await detailDeposito.refetch();
            if (onSubmit) onSubmit(dataDeposito);
            await alertSuccess('Data berhasil disimpan');
            return;
        } else {
            alertError(responseBody.message);
        }
    }, [dataDeposito, detailDeposito, onSubmit, token]);

    useEffect(() => {
        if (detailDeposito.data) {
            setDataDeposito(detailDeposito.data);
        }
    }, [detailDeposito.data]);

    useEffect(() => {
        if (dataDeposito.produk && dataDeposito.tgl_valuta) {
            const tgl_jatuh_tempo = hitungJatuhTempo(dataDeposito.tgl_valuta, dataDeposito.produk.jkw!);
            setDataDeposito((prev) => ({
                ...prev,
                tgl_jatuh_tempo: tgl_jatuh_tempo,
            }));
        }
    }, [dataDeposito.tgl_valuta, dataDeposito.produk]);

    const open = (id?: string) => {
        setShowModal(true);
        if (id) {
            setDataDeposito({ rekening: id });
            detailDeposito.refetch();
        }
    };

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

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

    const modal = useMemo(() => {
        return (
            <>
                <Modal show={showModal} onHide={close} onExited={clear} size="lg" centered>
                    <Modal.Header closeButton>
                        <h5 className="mb-0">Detail Tabungan</h5>
                    </Modal.Header>
                    <Modal.Body>
                        <div className="row">
                            <div className="col-md-12">
                                <div className="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={dataDeposito.rekening ?? ''} />
                                        </div>
                                    </div>
                                </div>
                                <div className="row mb-2">
                                    <label className="col-form-label col-md-3">Anggota</label>
                                    <div className="col-md-5">
                                        <div className="input-group">
                                            <input className="form-control" placeholder="Anggota" readOnly value={dataDeposito.anggota?.id ?? ''} />
                                            <button className="btn btn-primary" onClick={() => modalAnggota.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 Lengkap</label>
                                        <div className="col-md-9">
                                            <input
                                                className="form-control"
                                                placeholder="Nama Lengkap"
                                                readOnly
                                                value={dataDeposito.anggota?.nama_lengkap ?? ''}
                                            />
                                        </div>
                                    </div>
                                    <hr />
                                    <div className="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={dataDeposito.anggota?.alamat ?? ''}
                                            />
                                        </div>
                                    </div>
                                    <div className="row mb-2">
                                        <label className="col-form-label col-md-3" />
                                        <div className="col-md-2">
                                            <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"
                                                    placeholder="______"
                                                    readOnly
                                                    value={dataDeposito.anggota?.rt ?? ''}
                                                />
                                            </div>
                                        </div>
                                        <div className="col-md-2">
                                            <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"
                                                    placeholder="______"
                                                    readOnly
                                                    value={dataDeposito.anggota?.rw ?? ''}
                                                />
                                            </div>
                                        </div>
                                        <div className="col-md-3">
                                            <div className="input-group">
                                                <span className="input-group-text bg-white border-end-0">Kode Pos</span>
                                                <input
                                                    className="form-control border-start-0 text-center"
                                                    placeholder="_________"
                                                    readOnly
                                                    value={dataDeposito.anggota?.kode_pos ?? ''}
                                                />
                                            </div>
                                        </div>
                                    </div>
                                    <div className="row mb-2">
                                        <label className="col-form-label col-md-3">Kelurahan</label>
                                        <div className="col-md-4">
                                            <input
                                                className="form-control"
                                                placeholder="Kelurahan"
                                                readOnly
                                                value={dataDeposito.anggota?.kelurahan ?? ''}
                                            />
                                        </div>
                                        <label className="col-form-label col-md-1">Kec.</label>
                                        <div className="col-md-4">
                                            <input
                                                className="form-control"
                                                placeholder="Kecamatan"
                                                readOnly
                                                value={dataDeposito.anggota?.kecamatan ?? ''}
                                            />
                                        </div>
                                    </div>
                                    <div className="row mb-2">
                                        <label className="col-form-label col-md-3">Kota/Kabupaten</label>
                                        <div className="col-md-4">
                                            <input
                                                className="form-control"
                                                placeholder="Kota/Kabupaten"
                                                readOnly
                                                value={dataDeposito.anggota?.kabupaten ?? ''}
                                            />
                                        </div>
                                        <label className="col-form-label col-md-1">Telp.</label>
                                        <div className="col-md-4">
                                            <input
                                                className="form-control"
                                                readOnly
                                                placeholder="Nomor Telp/HP"
                                                value={dataDeposito.anggota?.nomor_telp ?? ''}
                                            />
                                        </div>
                                    </div>
                                    <hr />
                                    <div className="row mb-2">
                                        <label className="col-form-label col-md-3">Nomor Bilyet</label>
                                        <div className="col-md-5">
                                            <input
                                                className="form-control"
                                                value={dataDeposito.nomor_bilyet ?? ''}
                                                onChange={(e) => setDataDeposito({ ...dataDeposito, nomor_bilyet: e.target.value })}
                                            />
                                        </div>
                                    </div>
                                    <div className="row mb-2">
                                        <label className="col-form-label col-md-3">Jangka Waktu</label>
                                        <div className="col-md-5">
                                            <SelectProdukDeposito
                                                value={dataDeposito.produk?.id?.toString() ?? ''}
                                                onChange={(value) => {
                                                    const produk = produkDeposito.data?.find((item: ProdukDeposito) => item.id?.toString() == value);
                                                    const data = { ...dataDeposito, produk: produk };
                                                    setDataDeposito(data);
                                                }}
                                            />
                                        </div>
                                    </div>
                                    <div className="row mb-2">
                                        <label className="col-form-label col-md-3">Tgl Valuta</label>
                                        <div className="col-md-3">
                                            <input
                                                className="form-control"
                                                type="date"
                                                value={dataDeposito.tgl_valuta ?? ''}
                                                onChange={(e) => setDataDeposito({ ...dataDeposito, tgl_valuta: e.target.value })}
                                            />
                                        </div>
                                        <label className="col-form-label col-md-3 text-end">Tgl Jatuh Tempo</label>
                                        <div className="col-md-3">
                                            <input className="form-control" readOnly type="date" value={dataDeposito.tgl_jatuh_tempo ?? ''} />
                                        </div>
                                    </div>
                                    <hr />
                                    <div className="form-group row mb-2">
                                        <label className="col-form-label col-md-3">Nilai Valuta</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={dataDeposito.nilai_valuta ?? ''}
                                                    onValueChange={(e) => {
                                                        setDataDeposito({ ...dataDeposito, nilai_valuta: parseInt(e.value) });
                                                    }}
                                                />
                                            </div>
                                        </div>
                                        <label className="col-form-label col-md-3 text-end">Bunga/Th</label>
                                        <div className="col-md-2">
                                            <div className="input-group">
                                                <input className="form-control border-end-0" readOnly value={dataDeposito.produk?.suku_bunga ?? ''} />
                                                <span className="input-group-text bg-white">%</span>
                                            </div>
                                        </div>
                                    </div>
                                    <hr />
                                    <div className="form-group row mb-2">
                                        <label className="col-form-label col-md-3">Penampungan Bunga</label>
                                        <div className="col-md-5">
                                            <div className="input-group">
                                                <input
                                                    className="form-control"
                                                    placeholder="Rekening"
                                                    readOnly
                                                    value={dataDeposito.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={dataDeposito.tabungan?.anggota?.nama_lengkap ?? ''}
                                                />
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            {/* <div className="col-md-3">
                                <div className="row gap-2">
                                    <div className="col-md-12 gap-2 d-flex flex-column">
                                        <div className="d-flex">
                                            <button
                                                className="btn btn-primary flex-grow-1"
                                                disabled={!dataTabungan.rekening}
                                                // onClick={() => navigate(`/app/master/anggota/${dataTabungan.anggota?.id}`)}
                                            >
                                                Data Anggota
                                            </button>
                                        </div>
                                        <hr className="my-1" />
                                        <div className="d-flex">
                                            <button
                                                className="btn btn-primary flex-grow-1"
                                                disabled={!dataTabungan.rekening}
                                                // onClick={() => navigate(`/app/master/tabungan/${dataTabungan.rekening}/rekening-koran`)}
                                            >
                                                Rekening Koran
                                            </button>
                                        </div>
                                        <div className="d-flex">
                                            <button
                                                disabled={!dataTabungan.rekening}
                                                className="btn btn-primary flex-grow-1"
                                                // onClick={() => navigate(`/app/master/tabungan/${dataTabungan.rekening}/statement-transaksi`)}
                                            >
                                                Statement Transaksi
                                            </button>
                                        </div>
                                    </div>
                                </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 saveDataDeposito();
                            }}
                        >
                            Simpan
                        </ButtonSubmit>
                    </Modal.Footer>
                </Modal>
                {modalAnggota.modal}
                {modalRekening.modal}
            </>
        );
    }, [dataDeposito, loading, modalAnggota, modalRekening, produkDeposito.data, saveDataDeposito, showModal, validasi]);

    return { modal, open, close };
};
