import { getSaldoAkun } from '@/api/api_jurnal';
import { saveTransaksiKas } from '@/api/api_kas';
import { SUMBER_KAS } from '@/const';
import { formatDate, formatTanggal } from '@/helper';
import { Akun, Kas, PenempatanBank, TransaksiKas } from '@/types';
import { useKas, usePenempatanBank } 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';
import { alertError, alertSuccess } from '../../../components/costum/alert';
import { ButtonSubmit } from '../../../components/costum/button_submit';
import { Select } from '../../../components/costum/Select';
import { SelectKas } from '../../../components/costum/SelectKas';
import { SelectRekeningBank } from '../../../components/costum/SelectRekeningBank';
import { SelectTransaksiBank } from '../../../components/costum/SelectTransaksiBank';
import { SelectTransaksiKas } from '../../../components/costum/SelectTransaksiKas';
import { useModalBrowseAkun } from '../../../components/modal/modalBrowseAkun';

export const useModalTransaksiKas = ({ onSubmit }: { onSubmit?: (user: TransaksiKas) => boolean | Promise<boolean> }) => {
    const { token } = usePage().props;
    const [showModal, setShowModal] = useState(false);

    const penempatan = usePenempatanBank();
    const kas = useKas();
    const [validasi, setValidasi] = useState<boolean>(false);
    const [loading, setLoading] = useState<boolean>(false);
    const [dataTransaksi, setDataTransaksi] = useState<TransaksiKas>({
        trans_tglbuku: formatDate(new Date()),
    });

    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);
    };

    const modalAkun = useModalBrowseAkun({
        onSelected: async ({ akun }: { akun: Akun; selector?: string }) => {
            const response = await getSaldoAkun(akun.kode_akun!, dataTransaksi.trans_tglbuku ?? formatDate(new Date()), token as string);
            const responseBody = await response?.json();
            console.log(responseBody);
            if (response.status != 200) {
                return alertError(responseBody.message);
            }
            setDataTransaksi({ ...dataTransaksi, akun: akun, kode_akun: akun.kode_akun, saldo_awal_akun: responseBody });
        },
    });

    useEffect(() => {
        // kas masuk
        if (['11', '21'].includes(dataTransaksi.trans_kode ?? '')) {
            setDataTransaksi((prev) => ({
                ...prev,
                saldo_akhir_kas: (dataTransaksi?.saldo_awal_kas ?? 0) + (dataTransaksi.nominal ?? 0),
                saldo_akhir_akun: (dataTransaksi?.saldo_awal_akun ?? 0) + (dataTransaksi.nominal ?? 0),
            }));
            if (dataTransaksi.akun) {
                let saldo_akhir_akun = (dataTransaksi?.saldo_awal_akun ?? 0) - (dataTransaksi.nominal ?? 0);
                if (dataTransaksi.akun.jurnal == 'D') {
                    saldo_akhir_akun = (dataTransaksi?.saldo_awal_akun ?? 0) - (dataTransaksi.nominal ?? 0);
                } else if (dataTransaksi.akun.jurnal == 'K') {
                    saldo_akhir_akun = (dataTransaksi?.saldo_awal_akun ?? 0) + (dataTransaksi.nominal ?? 0);
                }
                setDataTransaksi((prev) => ({
                    ...prev,
                    saldo_akhir_akun: saldo_akhir_akun,
                }));
            }
        }
        // kas keluar
        if (['12', '22'].includes(dataTransaksi.trans_kode ?? '')) {
            setDataTransaksi((prev) => ({
                ...prev,
                saldo_akhir_kas: (dataTransaksi?.saldo_awal_kas ?? 0) - (dataTransaksi.nominal ?? 0),
            }));
            if (dataTransaksi.akun) {
                let saldo_akhir_akun = (dataTransaksi?.saldo_awal_akun ?? 0) - (dataTransaksi.nominal ?? 0);
                if (dataTransaksi.akun.jurnal == 'D') {
                    saldo_akhir_akun = (dataTransaksi?.saldo_awal_akun ?? 0) + (dataTransaksi.nominal ?? 0);
                } else if (dataTransaksi.akun.jurnal == 'K') {
                    saldo_akhir_akun = (dataTransaksi?.saldo_awal_akun ?? 0) - (dataTransaksi.nominal ?? 0);
                }
                setDataTransaksi((prev) => ({
                    ...prev,
                    saldo_akhir_akun: saldo_akhir_akun,
                }));
            }
        }
    }, [
        dataTransaksi.akun,
        dataTransaksi.nominal,
        dataTransaksi.rekening,
        dataTransaksi?.saldo_awal_akun,
        dataTransaksi?.saldo_awal_kas,
        dataTransaksi.trans_kode,
    ]);

    const saveTransaction = useCallback(async () => {
        try {
            setLoading(true);
            console.log(dataTransaksi);
            const response = await saveTransaksiKas(dataTransaksi, token as string);
            const responseBody = await response?.json();
            if (response?.status == 200 || response?.status == 201) {
                setValidasi(true);
                penempatan.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);
            }
        } catch (error) {
            alertError((error as Error).message);
        } finally {
            setLoading(false);
        }
    }, [dataTransaksi, onSubmit, penempatan, 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}
                                        disabled={validasi || loading}
                                        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>
                            <div className="form-group row mb-2">
                                <label className="col-form-label col-md-3">Sumber Kas</label>
                                <div className="col-md-7">
                                    <Select
                                        placeholder="Pilih Sumber Kas"
                                        isDisabled={validasi || loading}
                                        options={SUMBER_KAS.map((item) => ({ label: item.label, value: item.value }))}
                                        onChange={(newValue: unknown) => {
                                            const option = newValue as { label: string; value: string } | null;
                                            if (kas.data?.length != 0) {
                                                let _kas = kas.data?.[0] as Kas;
                                                if (option?.value == '1') {
                                                    const defaultKas: Kas = kas.data?.find((item: Kas) => item.is_default == 1);

                                                    if (defaultKas) {
                                                        _kas = defaultKas;
                                                    }
                                                }

                                                setDataTransaksi({
                                                    ...dataTransaksi,
                                                    sumber_kas: option?.value,
                                                    rekening: '',
                                                    kas_id: option?.value == '1' ? _kas.id : '',
                                                    saldo_awal_kas: _kas?.saldo ?? 0,
                                                    saldo_akhir_kas: 0,
                                                });
                                            } else {
                                                setDataTransaksi({
                                                    ...dataTransaksi,
                                                    sumber_kas: option?.value,
                                                });
                                            }
                                        }}
                                    />
                                </div>
                            </div>
                            {dataTransaksi?.sumber_kas == '1' && (
                                <div className="form-group row mb-2">
                                    <label className="col-form-label col-md-3">Kas</label>
                                    <div className="col-md-7">
                                        <SelectKas
                                            disable={validasi || loading}
                                            value={dataTransaksi?.kas_id ?? kas.data[0]?.id}
                                            onChange={(rek: string) => {
                                                if (rek) {
                                                    const data: Kas = kas.data?.find((item: Kas) => item.id == rek);
                                                    setDataTransaksi({
                                                        ...dataTransaksi,
                                                        kas_id: data?.id,
                                                        saldo_awal_kas: data.saldo,
                                                    });
                                                } else {
                                                    setDataTransaksi({
                                                        ...dataTransaksi,
                                                        kas_id: '',
                                                        saldo_awal_kas: 0,
                                                        saldo_akhir_kas: 0,
                                                    });
                                                }
                                            }}
                                        />
                                    </div>
                                </div>
                            )}
                            {dataTransaksi?.sumber_kas == '2' && (
                                <div className="form-group row mb-2">
                                    <label className="col-form-label col-md-3">Rekening Bank</label>
                                    <div className="col-md-7">
                                        <SelectRekeningBank
                                            disable={validasi || loading}
                                            value={dataTransaksi?.rekening ?? ''}
                                            onChange={(rek: string) => {
                                                if (rek) {
                                                    const data: PenempatanBank = penempatan.data?.find(
                                                        (item: PenempatanBank) => item.rekening == rek,
                                                    );
                                                    setDataTransaksi({
                                                        ...dataTransaksi,
                                                        rekening: data?.rekening,
                                                        saldo_awal_kas: data.saldo,
                                                    });
                                                } else {
                                                    setDataTransaksi({
                                                        ...dataTransaksi,
                                                        rekening: '',
                                                        saldo_awal_kas: 0,
                                                        saldo_akhir_kas: 0,
                                                    });
                                                }
                                            }}
                                        />
                                    </div>
                                </div>
                            )}
                            <div className="form-group row mb-2">
                                <label className="col-form-label col-md-3">Saldo Awal</label>
                                <div className="col-md-9">
                                    <div className="input-group">
                                        <span className={`input-group-text border-end-0 ${loading || validasi ? 'bg-mute' : 'bg-white'}`}>Rp</span>
                                        <NumericFormat
                                            className="form-control border-start-0 text-end"
                                            readOnly
                                            disabled={validasi || loading}
                                            thousandSeparator="."
                                            decimalSeparator=","
                                            value={dataTransaksi?.saldo_awal_kas ?? 0}
                                        />
                                        <span className="input-group-text bg-white">{'>'}</span>
                                        <span className={`input-group-text border-end-0 ${loading || validasi ? 'bg-mute' : 'bg-white'}`}>Rp</span>
                                        <NumericFormat
                                            className="form-control border-start-0 text-end"
                                            readOnly
                                            disabled={validasi || loading}
                                            thousandSeparator="."
                                            decimalSeparator=","
                                            value={dataTransaksi?.saldo_akhir_kas ?? 0}
                                        />
                                    </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">
                                    {dataTransaksi.sumber_kas == '1' ? (
                                        <SelectTransaksiKas
                                            disable={validasi || loading}
                                            value={dataTransaksi.trans_kode}
                                            onChange={(value: string) => {
                                                setDataTransaksi({ ...dataTransaksi, trans_kode: value });
                                            }}
                                        />
                                    ) : dataTransaksi.sumber_kas == '2' ? (
                                        <SelectTransaksiBank
                                            disable={validasi || loading}
                                            value={dataTransaksi.trans_kode}
                                            onChange={(value: string) => {
                                                setDataTransaksi({ ...dataTransaksi, trans_kode: value });
                                            }}
                                        />
                                    ) : (
                                        <Select placeholder="Pilih Jenis Transaksi" isDisabled={validasi || loading} />
                                    )}
                                </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 border-end-0 ${loading || validasi ? 'bg-mute' : 'bg-white'}`}>Rp</span>
                                        <NumericFormat
                                            className="form-control border-start-0 text-end"
                                            thousandSeparator="."
                                            decimalSeparator=","
                                            value={dataTransaksi?.nominal ?? ''}
                                            placeholder="0"
                                            disabled={validasi || loading}
                                            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">Akun</label>
                                <div className="col-md-5">
                                    <div className="input-group">
                                        <input
                                            className="form-control"
                                            placeholder="Akun"
                                            readOnly
                                            value={dataTransaksi?.akun?.kode_akun ?? ''}
                                            disabled={validasi || loading}
                                        />
                                        <button className="btn btn-primary" onClick={() => modalAkun.open()} disabled={validasi || loading}>
                                            Browse
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <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={dataTransaksi?.akun?.nama ?? ''}
                                        disabled={validasi || loading}
                                    />
                                </div>
                            </div>
                            <div className="form-group row mb-2">
                                <label className="col-form-label col-md-3">Saldo Akun</label>
                                <div className="col-md-9">
                                    <div className="input-group">
                                        <span className={`input-group-text border-end-0 ${loading || validasi ? 'bg-mute' : 'bg-white'}`}>Rp</span>
                                        <NumericFormat
                                            className="form-control border-start-0 text-end"
                                            readOnly
                                            thousandSeparator="."
                                            decimalSeparator=","
                                            disabled={validasi || loading}
                                            value={dataTransaksi?.saldo_awal_akun ?? 0}
                                        />
                                        <span className="input-group-text bg-white">{'>'}</span>
                                        <span className={`input-group-text border-end-0 ${loading || validasi ? 'bg-mute' : 'bg-white'}`}>Rp</span>
                                        <NumericFormat
                                            className="form-control border-start-0 text-end"
                                            readOnly
                                            thousandSeparator="."
                                            decimalSeparator=","
                                            disabled={validasi || loading}
                                            value={dataTransaksi?.saldo_akhir_akun ?? 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 ?? ''}
                                        disabled={validasi || loading}
                                        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 saveTransaction();
                            }}
                        >
                            Simpan
                        </ButtonSubmit>
                    </Modal.Footer>
                </Modal>
                {modalAkun.modal}
            </>
        );
    }, [dataTransaksi, kas, loading, modalAkun, penempatan.data, saveTransaction, showModal, validasi]);

    return { modal, open, close };
};
