import { savePenempatanBank } from '@/api/api_penempatan_bank';
import { formatDate } from '@/helper';
import { Bank, PenempatanBank, TransaksiKas } from '@/types';
import { useBank } from '@/useQuery/query';
import { Save, X } from 'lucide-react';
import { useCallback, useMemo, useState } from 'react';
import { Modal } from 'react-bootstrap';
import { alertError, alertSuccess } from '../costum/alert';
import { ButtonSubmit } from '../costum/button_submit';
import { SelectBank } from '../costum/SelectBank';
import { useModalBrowseAkun } from './modalBrowseAkun';
import { usePage } from '@inertiajs/react';

export const useModalAddPenempatanBank = ({ 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 [dataPenempatanBank, setDataPenempatanBank] = useState<PenempatanBank>({
        tgl_penempatan: formatDate(new Date()),
    });
    const { token } = usePage().props;
    const banks = useBank();

    const modalAkun = useModalBrowseAkun({
        onSelected: ({ akun, selector }) => {
            if (selector == 'jurnal') {
                setDataPenempatanBank({
                    ...dataPenempatanBank,
                    jurnal: akun,
                    akun_penempatan: akun.kode_akun,
                });
            }
        },
    });

    const savePenempatan = useCallback(async () => {
        const response = await savePenempatanBank(dataPenempatanBank!, token as string);
        const responseBody = await response.json();

        if (response.status == 201 || response.status == 200) {
            const id = responseBody.id;
            setDataPenempatanBank({
                ...dataPenempatanBank,
                id: id,
            });
            if (onSubmit) {
                const result = await onSubmit(responseBody);
                if (result === false) {
                    setLoading(false);
                    return;
                }
            }
            await alertSuccess('Data berhasil disimpan');
            return;
        } else {
            alertError(responseBody.message);
        }
    }, [dataPenempatanBank, onSubmit, token]);

    const handleChange = useCallback(
        (e: React.ChangeEvent<HTMLInputElement>) => {
            setDataPenempatanBank({
                ...dataPenempatanBank,
                [e.target.name]: e.target.value.toUpperCase(),
            });
        },
        [dataPenempatanBank],
    );

    const open = () => {
        setShowModal(true);
    };

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

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

    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="row mb-2">
                            <label className="col-form-label col-md-3">Rekening Bank</label>
                            <div className="col-md-5">
                                <div className="input-group">
                                    <input
                                        className="form-control"
                                        placeholder="Rekening Bank"
                                        value={dataPenempatanBank.rekening ?? ''}
                                        name="rekening"
                                        onChange={handleChange}
                                    />
                                </div>
                            </div>
                        </div>
                        <div className="row mb-2">
                            <label className="col-form-label col-md-3">Nama Rekening</label>
                            <div className="col-md-9">
                                <div className="input-group">
                                    <input
                                        className="form-control"
                                        placeholder="Nama Rekening"
                                        value={dataPenempatanBank.nama ?? ''}
                                        name="nama"
                                        onChange={handleChange}
                                    />
                                </div>
                            </div>
                        </div>
                        <div className="row mb-2">
                            <label className="col-form-label col-md-3">Bank</label>
                            <div className="col-md-9">
                                <SelectBank
                                    value={dataPenempatanBank.bank?.id ?? ''}
                                    onChange={(value: string) => {
                                        const bank = banks.data?.find((item: Bank) => item.id?.toString() == value);
                                        setDataPenempatanBank({
                                            ...dataPenempatanBank,
                                            bank: bank,
                                            bank_id: bank.id,
                                        });
                                    }}
                                />
                            </div>
                        </div>
                        <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={dataPenempatanBank.bank?.alamat ?? ''} />
                            </div>
                        </div>
                        <div className="row mb-2">
                            <label className="col-form-label col-md-3">No.Telp</label>
                            <div className="col-md-4">
                                <input className="form-control" readOnly value={dataPenempatanBank.bank?.nomor_telp ?? ''} />
                            </div>
                            <label className="col-form-label col-md-2 text-end">Tgl Buka</label>
                            <div className="col-md-3">
                                <input
                                    className="form-control"
                                    type="date"
                                    name="tgl_penempatan"
                                    value={dataPenempatanBank.tgl_penempatan ?? ''}
                                    onChange={handleChange}
                                />
                            </div>
                        </div>
                        <div>
                            <hr className="mt-3" />
                            <div className="form-group row mb-2">
                                <label className="col-form-label col-md-3">Akun Jurnal</label>
                                <div className="col-md-5">
                                    <div className="input-group">
                                        <input
                                            className="form-control"
                                            placeholder="Rekening"
                                            readOnly
                                            value={dataPenempatanBank.jurnal?.kode_akun ?? ''}
                                        />
                                        <button className="btn btn-primary" onClick={() => modalAkun.open('jurnal')}>
                                            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 Akun</label>
                                    <div className="col-md-9">
                                        <input
                                            className="form-control"
                                            placeholder="Nama Akun"
                                            readOnly
                                            value={dataPenempatanBank.jurnal?.nama ?? ''}
                                        />
                                    </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 savePenempatan();
                            }}
                        >
                            Simpan
                        </ButtonSubmit>
                    </Modal.Footer>
                </Modal>
                {modalAkun.modal}
            </>
        );
    }, [banks.data, dataPenempatanBank, handleChange, loading, modalAkun, savePenempatan, showModal, validasi]);

    return { modal, open, close };
};
