import { savePenempatanBank } from '@/api/api_penempatan_bank';
import { alertError, alertSuccess } from '@/components/costum/alert';
import { ButtonSubmit } from '@/components/costum/button_submit';
import { SelectBank } from '@/components/costum/SelectBank';
import { useModalBrowseAkun } from '@/components/modal/modalBrowseAkun';
import { formatDate, formatTanggal } from '@/helper';
import { Bank, PenempatanBank } from '@/types';
import { useBank, useDetailPenempatan } from '@/useQuery/query';
import { usePage } from '@inertiajs/react';
import { Save } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Spinner } from 'react-bootstrap';
import { NumericFormat } from 'react-number-format';
import { Link, useParams } from 'react-router';

export default function DetailKasBankPage() {
    const { token } = usePage().props;
    const { id } = useParams();

    const [loadingData, setLoadingData] = useState(true);

    const banks = useBank();

    const modalAkun = useModalBrowseAkun({
        onSelected: ({ akun, selector }) => {
            if (selector == 'jurnal') {
                setDataPenempatanBank({
                    ...dataPenempatanBank,
                    jurnal: akun,
                    akun_penempatan: akun.kode_akun,
                });
            }
        },
    });

    const [dataPenempatanBank, setDataPenempatanBank] = useState<PenempatanBank>({
        tgl_penempatan: formatDate(new Date()),
    });

    const detailPenempatan = useDetailPenempatan(id);

    const savePenempatan = async () => {
        const response = await savePenempatanBank(dataPenempatanBank!, token as string);
        const responseBody = await response.json();

        if (response.status == 201 || response.status == 200) {
            const id = responseBody.id;
            setDataPenempatanBank({
                ...dataPenempatanBank,
                id: id,
            });
            detailPenempatan.refetch();
            await alertSuccess('Data berhasil disimpan');
            return;
        } else {
            alertError(responseBody.message);
        }
    };

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

    useEffect(() => {
        if (detailPenempatan.data) {
            const data: PenempatanBank = { ...detailPenempatan.data, tgl_penempatan: formatDate(detailPenempatan.data?.tgl_penempatan) };
            console.log(data);

            setDataPenempatanBank(data);
        }
        setLoadingData(false);
    }, [detailPenempatan.data]);

    if (loadingData || detailPenempatan.isLoading) {
        return (
            <div className="p-3 text-center">
                <Spinner />
            </div>
        );
    }
    return (
        <div className="container" style={{ width: 1024 }}>
            <div className="card shadow-lg rounded-4 mx-auto">
                <div className="card-header py-3 bg-transparent">
                    <h5 className="m-0">Data Kas Bank</h5>
                </div>
                <div className="card-body">
                    <div className="row">
                        <div className="col-md-9">
                            <div className="row">
                                <div className="">
                                    <div className="row mb-2">
                                        <label className="col-form-label col-md-3">ID</label>
                                        <div className="col-md-5">
                                            <div className="input-group">
                                                <input
                                                    className="form-control"
                                                    placeholder="ID Penempatan Bank"
                                                    readOnly
                                                    value={dataPenempatanBank.id ?? ''}
                                                />
                                            </div>
                                        </div>
                                    </div>
                                    <div className="row mb-2">
                                        <label className="col-form-label col-md-3">Rekening Bank</label>
                                        <div className="col-md-5">
                                            <div className="input-group">
                                                <input
                                                    className="form-control"
                                                    placeholder="Rekening Bank"
                                                    value={dataPenempatanBank.rekening ?? ''}
                                                    name="rekening"
                                                    onChange={handleChange}
                                                />
                                            </div>
                                        </div>
                                    </div>
                                    <div className="row mb-2">
                                        <label className="col-form-label col-md-3">Nama Rekening</label>
                                        <div className="col-md-9">
                                            <div className="input-group">
                                                <input
                                                    className="form-control"
                                                    placeholder="Nama Rekening"
                                                    value={dataPenempatanBank.nama ?? ''}
                                                    name="nama"
                                                    onChange={handleChange}
                                                />
                                            </div>
                                        </div>
                                    </div>
                                    <div className="row mb-2">
                                        <label className="col-form-label col-md-3">Bank</label>
                                        <div className="col-md-9">
                                            <SelectBank
                                                value={dataPenempatanBank.bank?.id ?? ''}
                                                onChange={(value: string) => {
                                                    const bank = banks.data?.find((item: Bank) => item.id?.toString() == value);
                                                    setDataPenempatanBank({
                                                        ...dataPenempatanBank,
                                                        bank: bank,
                                                        bank_id: bank.id,
                                                    });
                                                }}
                                            />
                                        </div>
                                    </div>
                                    <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={dataPenempatanBank.bank?.alamat ?? ''}
                                            />
                                        </div>
                                    </div>
                                    <div className="row mb-2">
                                        <label className="col-form-label col-md-3">No.Telp</label>
                                        <div className="col-md-4">
                                            <input className="form-control" readOnly value={dataPenempatanBank.bank?.nomor_telp ?? ''} />
                                        </div>
                                        <label className="col-form-label col-md-2 text-end">Tgl Buka</label>
                                        <div className="col-md-3">
                                            <input
                                                className="form-control"
                                                type="date"
                                                name="tgl_penempatan"
                                                value={dataPenempatanBank.tgl_penempatan ?? ''}
                                                onChange={handleChange}
                                            />
                                        </div>
                                    </div>
                                    <hr />
                                    <div className="form-group row mb-2">
                                        <label className="col-form-label col-md-3">Saldo</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={dataPenempatanBank.saldo ?? '0'}
                                                />
                                            </div>
                                        </div>
                                    </div>
                                    <div className="row mb-2">
                                        <label className="col-form-label col-md-3">Akun Jurnal</label>
                                        <div className="col-md-6">
                                            <div className="input-group">
                                                <input
                                                    className="form-control"
                                                    placeholder="Rekening"
                                                    readOnly
                                                    value={dataPenempatanBank.jurnal?.kode_akun ?? ''}
                                                />
                                                <button className="btn btn-primary" onClick={() => modalAkun.open('jurnal')}>
                                                    Browse
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    <div className="row mb-2">
                                        <label className="col-form-label col-md-3"></label>
                                        <div className="col-md-9">
                                            <input
                                                className="form-control"
                                                placeholder="Nama Akun"
                                                readOnly
                                                value={dataPenempatanBank.jurnal?.nama ?? ''}
                                            />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="col-md-3">
                            <div className="row gap-2">
                                <div className="d-flex">
                                    <Link to={`/app/master/penempatan/${id}/statement-transaksi`} className="btn btn-primary flex-grow-1">
                                        Statement Transaksi
                                    </Link>
                                </div>
                            </div>
                            <div className="form-label mt-3">
                                <label className="form-label">Tanggal Buka</label>
                                <input className="form-control text-center" readOnly value={formatTanggal(dataPenempatanBank.created_at)} />
                            </div>
                        </div>
                    </div>
                </div>
                <div className="card-footer d-flex justify-content-between py-3 bg-transparent">
                    <Link to={`/app/master/kas/`} className="btn btn-danger">
                        Kembali
                    </Link>
                    <ButtonSubmit className="btn btn-success" icon={<Save size={18} />} onClick={async () => await savePenempatan()}>
                        Simpan
                    </ButtonSubmit>
                </div>
            </div>
            {modalAkun.modal}
        </div>
    );
}
