import { saveTransaksiTabungan } from '@/api/api_tabungan';
import { alertError, alertSuccess } from '@/components/costum/alert';
import { ButtonSubmit } from '@/components/costum/button_submit';
import { Select } from '@/components/costum/Select';
import { useModalBrowseRekeningTabungan } from '@/components/modal/modalBrowseRekeningTabungan';
import { JENIS_TRANSAKSI_TABUNGAN } from '@/const';
import { formatDate, formatTanggal } from '@/helper';
import { Tabungan, TransaksiTabungan } from '@/types';
import { usePage } from '@inertiajs/react';
import { ArrowLeft, Save } from 'lucide-react';
import { useEffect, useState } from 'react';
import { NumericFormat } from 'react-number-format';
import { Link } from 'react-router';

export default function FormTransaksiTabunganPage() {
    const { token } = usePage().props;

    const [dataTransaksi, setDataTransaksi] = useState<TransaksiTabungan>({
        trans_tglbuku: formatDate(new Date()),
    });

    const modalRekening = useModalBrowseRekeningTabungan({
        onSelected: (tab: Tabungan) => {
            console.log(tab);
            setDataTransaksi({ ...dataTransaksi, tabungan: tab, rekening: tab.rekening });
        },
    });

    useEffect(() => {
        if (dataTransaksi?.trans_kode) {
            const saldo_awal = dataTransaksi.tabungan?.saldo ?? 0;
            const nominal = dataTransaksi?.nominal ?? 0;
            const trans_kode = dataTransaksi?.trans_kode;
            if (trans_kode == '31') {
                setDataTransaksi((prev) => ({ ...prev, saldo_akhir: saldo_awal + nominal }));
            }
            if (trans_kode == '32') {
                setDataTransaksi((prev) => ({ ...prev, saldo_akhir: saldo_awal - nominal }));
            }
        } else {
            setDataTransaksi((prev) => ({ ...prev, saldo_akhir: undefined }));
        }
    }, [dataTransaksi?.nominal, dataTransaksi.tabungan?.saldo, dataTransaksi?.trans_kode]);

    const saveTransaksi = async () => {
        console.log(dataTransaksi);
        const response = await saveTransaksiTabungan(dataTransaksi, token as string);
        const responseBody = await response.json();
        if (response.status == 200 || response.status == 201) {
            await alertSuccess('Transaksi Berhasil disimpan');
        } else {
            await alertError(responseBody.message);
        }
    };

    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 Tabungan</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 ?? ''}
                                        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 className="form-group 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={dataTransaksi?.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={dataTransaksi?.tabungan?.anggota?.nama_lengkap ?? ''}
                                    />
                                </div>
                            </div>
                            <div className="form-group 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={dataTransaksi?.tabungan?.anggota?.alamat ?? ''}
                                    />
                                </div>
                            </div>
                            <div className="row mb-2">
                                <label className="col-form-label col-md-3" />
                                <div className="col-md-3">
                                    <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"
                                            readOnly
                                            value={dataTransaksi?.tabungan?.anggota?.rt ?? ''}
                                        />
                                    </div>
                                </div>
                                <div className="col-md-3">
                                    <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"
                                            readOnly
                                            value={dataTransaksi?.tabungan?.anggota?.rw ?? ''}
                                        />
                                    </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">
                                    <Select
                                        placeholder="Pilih Jenis Transaksi"
                                        options={JENIS_TRANSAKSI_TABUNGAN.map((item) => ({ label: item.label, value: item.value }))}
                                        onChange={(newValue: unknown) => {
                                            const option = newValue as { label: string; value: string } | null;
                                            setDataTransaksi({ ...dataTransaksi, trans_kode: option?.value });
                                        }}
                                    />
                                </div>
                            </div>
                            <div className="form-group row mb-2">
                                <label className="col-form-label col-md-3">Saldo Awal</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"
                                            readOnly
                                            thousandSeparator="."
                                            decimalSeparator=","
                                            value={dataTransaksi?.tabungan?.saldo ?? '0'}
                                        />
                                    </div>
                                </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 bg-white border-end-0">Rp</span>
                                        <NumericFormat
                                            className="form-control border-start-0 text-end"
                                            thousandSeparator="."
                                            decimalSeparator=","
                                            value={dataTransaksi?.nominal ?? ''}
                                            placeholder="0"
                                            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">Saldo Akhir</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"
                                            readOnly
                                            thousandSeparator="."
                                            decimalSeparator=","
                                            value={dataTransaksi?.saldo_akhir ?? 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 ?? ''}
                                        onChange={(e) => {
                                            setDataTransaksi({ ...dataTransaksi, keterangan: e.target.value });
                                        }}
                                    />
                                </div>
                            </div>
                        </div>
                    </div>
                    <div className="card-footer justify-content-between d-flex">
                        <Link to={`/app/transaksi/tabungan`} className="btn btn-danger align-items-center d-flex gap-2">
                            <ArrowLeft size={18} />
                            Kembali
                        </Link>
                        <ButtonSubmit className="btn btn-success" icon={<Save size={18} />} onClick={async () => await saveTransaksi()}>
                            Simpan
                        </ButtonSubmit>
                    </div>
                </div>
            </div>

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