import { saveTransaksiKas } from '@/api/api_kas';
import { alertError, alertSuccess } from '@/components/costum/alert';
import { ButtonSubmit } from '@/components/costum/button_submit';
import { Select } from '@/components/costum/Select';
import { SelectRekeningBank } from '@/components/costum/SelectRekeningBank';
import { SelectTransaksiBank } from '@/components/costum/SelectTransaksiBank';
import { SelectTransaksiKas } from '@/components/costum/SelectTransaksiKas';
import { useModalBrowseAkun } from '@/components/modal/modalBrowseAkun';
import { SUMBER_KAS } from '@/const';
import { formatDate, formatTanggal } from '@/helper';
import { Akun, PenempatanBank, TransaksiKas } from '@/types';
import { usePenempatanBank } from '@/useQuery/query';
import { usePage } from '@inertiajs/react';
import { ArrowLeft, Save } from 'lucide-react';
import { useEffect, useState } from 'react';
import { NumericFormat } from 'react-number-format';
import { useNavigate } from 'react-router';

export default function FormTransaksiKasPage() {
    const { token } = usePage().props;
    const penempatan = usePenempatanBank();
    const [validasi, setValidasi] = useState<boolean>(false);
    const [loading, setLoading] = useState<boolean>(false);
    const [dataTransaksi, setDataTransaksi] = useState<TransaksiKas>({
        trans_tglbuku: formatDate(new Date()),
    });
    const navigate = useNavigate();

    const modalAkun = useModalBrowseAkun({
        onSelected: ({ akun }: { akun: Akun; selector?: string }) => {
            setDataTransaksi({ ...dataTransaksi, akun: akun, kode_akun: akun.kode_akun });
        },
    });

    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 = async () => {
        setLoading(true);
        try {
            if(dataTransaksi.sumber_kas){
                const response = await saveTransaksiKas(dataTransaksi!, token as string);
                console.log(response);
                const responseBody = await response?.json();
                if (response?.status == 200 || response?.status == 201) {
                    setValidasi(true);
                    await alertSuccess('Transaksi Berhasil disimpan');
                } else {
                    alertError(responseBody.message);
                }
            }
        } catch (error) {
            await alertError((error as Error).message);
        }
        setLoading(false);
    };

    return (
        <div className="py-1 container">
            <div className="my-3 container" style={{ width: 720 }}>
                <div className="card border-primary">
                    <div className="card-header bg-primary text-white">
                        <h5 className="mb-0">Transaksi Kas</h5>
                    </div>
                    <div className="card-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 id="data-anggota">
                            <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;
                                            setDataTransaksi({
                                                ...dataTransaksi,
                                                sumber_kas: option?.value,
                                                rekening: '',
                                                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>
                    </div>
                    <div className="card-footer justify-content-between d-flex">
                        <button onClick={() => navigate(-1)} className="btn btn-danger align-items-center d-flex gap-2">
                            <ArrowLeft size={18} />
                            Kembali
                        </button>
                        <ButtonSubmit
                            className="btn btn-success"
                            icon={<Save size={18} />}
                            disable={validasi || loading}
                            onClick={async () => {
                                await saveTransaction();
                            }}
                        >
                            Simpan
                        </ButtonSubmit>
                    </div>
                </div>
            </div>

            {modalAkun.modal}
        </div>
    );
}
