import { saveKas } from '@/api/api_kas';
import { Kas, TransaksiKas } from '@/types';
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 { useModalBrowseAkun } from './modalBrowseAkun';
import { usePage } from '@inertiajs/react';

export const useModalAddKas = ({ 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 [dataKas, setDataKas] = useState<Kas>();
    const { token } = usePage().props;

    const modalAkun = useModalBrowseAkun({
        onSelected: ({ akun, selector }) => {
            if (selector == 'jurnal') {
                setDataKas({
                    ...dataKas,
                    jurnal: akun,
                    akun_kas: akun.kode_akun,
                });
            }
        },
    });

    const saveDataKas = useCallback(async () => {
        const response = await saveKas(dataKas!, token as string);
        const responseBody = await response.json();

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

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

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

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

    const clear = () => {
        setDataKas(undefined);
        setValidasi(false);
        setLoading(false);
    };

    const modal = useMemo(() => {
        return (
            <>
                <Modal show={showModal} onHide={close} onExited={clear} size="lg">
                    <Modal.Header closeButton>
                        <h5 className="mb-0">Data Kas</h5>
                    </Modal.Header>
                    <Modal.Body>
                        <div className="row mb-2">
                            <label className="col-form-label col-md-3">Nama Kas</label>
                            <div className="col-md-9">
                                <div className="input-group">
                                    <input
                                        className="form-control"
                                        placeholder="Nama Rekening"
                                        value={dataKas?.nama ?? ''}
                                        name="nama"
                                        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={dataKas?.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={dataKas?.jurnal?.nama ?? ''} />
                                </div>
                            </div>
                        </div>
                        <hr className="mt-3" />
                        <div className="form-group row mb-2">
                            <label className="col-form-label col-md-3">Atur sebagai default</label>
                            <div className="col-md-5 d-flex align-items-center">
                                <div className="form-check form-switch">
                                    <input
                                        className="form-check-input"
                                        type="checkbox"
                                        role="switch"
                                        id="switchCheckChecked"
                                        checked={dataKas?.is_default ? true : false}
                                        onChange={() => setDataKas({ ...dataKas, is_default: !dataKas?.is_default == true ? 1 : 0 })}
                                    />
                                </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 saveDataKas();
                            }}
                        >
                            Simpan
                        </ButtonSubmit>
                    </Modal.Footer>
                </Modal>
                {modalAkun.modal}
            </>
        );
    }, [dataKas, handleChange, loading, modalAkun, saveDataKas, showModal, validasi]);

    return { modal, open, close };
};
