import { saveDeposito } from '@/api/api_deposito';
import { alertError, alertSuccess } from '@/components/costum/alert';
import { ButtonSubmit } from '@/components/costum/button_submit';
import { SelectProdukDeposito } from '@/components/costum/SelectProdukDeposito';
import { useModalBrowseAnggota } from '@/components/modal/modalBrowseAnggota';
import { useModalBrowseRekeningTabungan } from '@/components/modal/modalBrowseRekeningTabungan';
import { formatDate, hitungJatuhTempo } from '@/helper';
import { Anggota, Deposito, ProdukDeposito, Tabungan } from '@/types';
import { useDetailDeposito, useProdukDeposito } from '@/useQuery/query';
import { ArrowLeft, Save } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Spinner } from 'react-bootstrap';
import { NumericFormat } from 'react-number-format';
import { useNavigate, useParams } from 'react-router';
import { useModalDetailAnggota } from '../anggota/modalDetailAnggota';
import { usePage } from '@inertiajs/react';

export default function DetailTabunganPage() {
    const { token } = usePage().props;
    const { id } = useParams();
    const [loadingData, setLoadingData] = useState(true);
    const navigate = useNavigate();
    const detailDeposito = useDetailDeposito(id);

    const modalAnggota = useModalBrowseAnggota({
        onSelected: (anggota: Anggota) => {
            setDataDeposito({
                ...dataDeposito,
                anggota: anggota,
            });
        },
    });

    const modalRekening = useModalBrowseRekeningTabungan({
        onSelected: (tab: Tabungan) => {
            setDataDeposito({
                ...dataDeposito,
                tabungan: tab,
                rekening_tabungan: tab.rekening,
            });
        },
    });

    const modalDetailAnggota = useModalDetailAnggota({
        onSubmit: async () => {
            await detailDeposito.refetch();
            return true;
        },
    });

    const produkDeposito = useProdukDeposito();

    const [dataDeposito, setDataDeposito] = useState<Deposito>({
        tgl_valuta: formatDate(new Date()),
    });

    const saveDataDeposito = async () => {
        const response = await saveDeposito(dataDeposito!, token as string);
        const responseBody = await response.json();

        if (response.status == 201 || response.status == 200) {
            const rekening = responseBody.rekening;
            setDataDeposito({
                ...dataDeposito,
                rekening: rekening,
            });
            detailDeposito.refetch();
            await alertSuccess('Data berhasil disimpan');
            return;
        } else {
            alertError(responseBody.message);
        }
    };

    useEffect(() => {
        if (detailDeposito.data) {
            setDataDeposito(detailDeposito.data);
        }
        setLoadingData(false);
    }, [detailDeposito.data]);

    useEffect(() => {
        if (dataDeposito.produk && dataDeposito.tgl_valuta) {
            const tgl_jatuh_tempo = hitungJatuhTempo(dataDeposito.tgl_valuta, dataDeposito.produk.jkw!);
            setDataDeposito((prev) => ({
                ...prev,
                tgl_jatuh_tempo: tgl_jatuh_tempo,
            }));
        }
    }, [dataDeposito.tgl_valuta, dataDeposito.produk]);

    if (loadingData || detailDeposito.isLoading) {
        return (
            <div className="p-3 text-center">
                <Spinner />
            </div>
        );
    }

    return (
        <>
            <div className="container" style={{ width: 1024 }}>
                <div className="card rounded-4 shadow-lg">
                    <div className="card-header py-3 bg-transparent">
                        <h5 className="mb-0">Data Deposito</h5>
                    </div>
                    <div className="card-body">
                        <div className="row">
                            <div className="col-md-9">
                                <div className="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={dataDeposito.rekening ?? ''} />
                                        </div>
                                    </div>
                                </div>
                                <div className="row mb-2">
                                    <label className="col-form-label col-md-3">Anggota</label>
                                    <div className="col-md-5">
                                        <div className="input-group">
                                            <input className="form-control" placeholder="Anggota" readOnly value={dataDeposito.anggota?.id ?? ''} />
                                            <button className="btn btn-primary" onClick={() => modalAnggota.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 Lengkap</label>
                                        <div className="col-md-9">
                                            <input
                                                className="form-control"
                                                placeholder="Nama Lengkap"
                                                readOnly
                                                value={dataDeposito.anggota?.nama_lengkap ?? ''}
                                            />
                                        </div>
                                    </div>
                                    <hr />
                                    <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={dataDeposito.anggota?.alamat ?? ''}
                                            />
                                        </div>
                                    </div>
                                    <div className="row mb-2">
                                        <label className="col-form-label col-md-3" />
                                        <div className="col-md-2">
                                            <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"
                                                    placeholder="______"
                                                    readOnly
                                                    value={dataDeposito.anggota?.rt ?? ''}
                                                />
                                            </div>
                                        </div>
                                        <div className="col-md-2">
                                            <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"
                                                    placeholder="______"
                                                    readOnly
                                                    value={dataDeposito.anggota?.rw ?? ''}
                                                />
                                            </div>
                                        </div>
                                        <div className="col-md-3">
                                            <div className="input-group">
                                                <span className="input-group-text bg-white border-end-0">Kode Pos</span>
                                                <input
                                                    className="form-control border-start-0 text-center"
                                                    placeholder="_________"
                                                    readOnly
                                                    value={dataDeposito.anggota?.kode_pos ?? ''}
                                                />
                                            </div>
                                        </div>
                                    </div>
                                    <div className="row mb-2">
                                        <label className="col-form-label col-md-3">Kelurahan</label>
                                        <div className="col-md-4">
                                            <input
                                                className="form-control"
                                                placeholder="Kelurahan"
                                                readOnly
                                                value={dataDeposito.anggota?.kelurahan ?? ''}
                                            />
                                        </div>
                                        <label className="col-form-label col-md-1">Kec.</label>
                                        <div className="col-md-4">
                                            <input
                                                className="form-control"
                                                placeholder="Kecamatan"
                                                readOnly
                                                value={dataDeposito.anggota?.kecamatan ?? ''}
                                            />
                                        </div>
                                    </div>
                                    <div className="row mb-2">
                                        <label className="col-form-label col-md-3">Kota/Kabupaten</label>
                                        <div className="col-md-4">
                                            <input
                                                className="form-control"
                                                placeholder="Kota/Kabupaten"
                                                readOnly
                                                value={dataDeposito.anggota?.kabupaten ?? ''}
                                            />
                                        </div>
                                        <label className="col-form-label col-md-1">Telp.</label>
                                        <div className="col-md-4">
                                            <input
                                                className="form-control"
                                                readOnly
                                                placeholder="Nomor Telp/HP"
                                                value={dataDeposito.anggota?.nomor_telp ?? ''}
                                            />
                                        </div>
                                    </div>
                                    <hr />
                                    <div className="row mb-2">
                                        <label className="col-form-label col-md-3">Nomor Bilyet</label>
                                        <div className="col-md-5">
                                            <input
                                                className="form-control"
                                                value={dataDeposito.nomor_bilyet ?? ''}
                                                onChange={(e) => setDataDeposito({ ...dataDeposito, nomor_bilyet: e.target.value })}
                                            />
                                        </div>
                                    </div>
                                    <div className="row mb-2">
                                        <label className="col-form-label col-md-3">Jangka Waktu</label>
                                        <div className="col-md-5">
                                            <SelectProdukDeposito
                                                value={dataDeposito.produk?.id?.toString() ?? ''}
                                                onChange={(value) => {
                                                    const produk = produkDeposito.data?.find((item: ProdukDeposito) => item.id?.toString() == value);
                                                    const data = { ...dataDeposito, produk: produk };
                                                    setDataDeposito(data);
                                                }}
                                            />
                                        </div>
                                    </div>
                                    <div className="row mb-2">
                                        <label className="col-form-label col-md-3">Tgl Valuta</label>
                                        <div className="col-md-3">
                                            <input
                                                className="form-control"
                                                type="date"
                                                value={dataDeposito.tgl_valuta ?? ''}
                                                onChange={(e) => setDataDeposito({ ...dataDeposito, tgl_valuta: e.target.value })}
                                            />
                                        </div>
                                        <label className="col-form-label col-md-3 text-end">Tgl Jatuh Tempo</label>
                                        <div className="col-md-3">
                                            <input className="form-control" readOnly type="date" value={dataDeposito.tgl_jatuh_tempo ?? ''} />
                                        </div>
                                    </div>
                                    <hr />
                                    <div className="form-group row mb-2">
                                        <label className="col-form-label col-md-3">Nilai Valuta</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={dataDeposito.nilai_valuta ?? ''}
                                                    onValueChange={(e) => {
                                                        setDataDeposito({ ...dataDeposito, nilai_valuta: parseInt(e.value) });
                                                    }}
                                                />
                                            </div>
                                        </div>
                                        <label className="col-form-label col-md-3 text-end">Bunga/Th</label>
                                        <div className="col-md-2">
                                            <div className="input-group">
                                                <input className="form-control border-end-0" readOnly value={dataDeposito.produk?.suku_bunga ?? ''} />
                                                <span className="input-group-text bg-white">%</span>
                                            </div>
                                        </div>
                                    </div>
                                    <hr />
                                    <div className="form-group row mb-2">
                                        <label className="col-form-label col-md-3">Penampungan Bunga</label>
                                        <div className="col-md-5">
                                            <div className="input-group">
                                                <input
                                                    className="form-control"
                                                    placeholder="Rekening"
                                                    readOnly
                                                    value={dataDeposito.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={dataDeposito.tabungan?.anggota?.nama_lengkap ?? ''}
                                                />
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div className="col-md-3">
                                <div className="row gap-2">
                                    <div className="col-md-12 gap-2 d-flex flex-column">
                                        <div className="d-flex">
                                            <button
                                                className="btn btn-primary flex-grow-1"
                                                disabled={!dataDeposito.rekening}
                                                onClick={() => {
                                                    modalDetailAnggota.open(dataDeposito.anggota?.id);
                                                }}
                                            >
                                                Data Anggota
                                            </button>
                                        </div>
                                        <hr className="my-1" />
                                        <div className="d-flex">
                                            <button
                                                disabled={!dataDeposito.rekening}
                                                className="btn btn-primary flex-grow-1"
                                                onClick={() => navigate(`/app/master/deposito/${dataDeposito.rekening}/statement-bunga`)}
                                            >
                                                Statement Bunga
                                            </button>
                                        </div>
                                        <div className="d-flex">
                                            <button
                                                disabled={!dataDeposito.rekening}
                                                className="btn btn-primary flex-grow-1"
                                            >
                                                Cetak Bilyet
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div className="card-footer justify-content-between d-flex py-3 bg-transparent">
                        <button className="btn btn-danger align-items-center d-flex gap-2" onClick={() => navigate(-1)}>
                            <ArrowLeft size={18} />
                            Kembali
                        </button>
                        <ButtonSubmit icon={<Save size={18} />} className="btn btn-success" onClick={async () => await saveDataDeposito()}>
                            Simpan
                        </ButtonSubmit>
                    </div>
                </div>
            </div>

            {modalAnggota.modal}
            {modalRekening.modal}
            {modalDetailAnggota.modal}
        </>
    );
}
