import { saveKas } from '@/api/api_kas';
import { alertError, alertSuccess } from '@/components/costum/alert';
import { ButtonSubmit } from '@/components/costum/button_submit';
import { useModalBrowseAkun } from '@/components/modal/modalBrowseAkun';
import { formatTanggal } from '@/helper';
import { Kas } from '@/types';
import { useDetailKas } 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 DetailKasPage() {
    const { token } = usePage().props;
    const { id } = useParams();

    const detailKas = useDetailKas(id);

    const modalAkun = useModalBrowseAkun({
        onSelected: ({ akun, selector }) => {
            if (selector == 'jurnal') {
                setDataKas({
                    ...dataKas,
                    jurnal: akun,
                    akun_kas: akun.kode_akun,
                });
            }
        },
    });

    const [dataKas, setDataKas] = useState<Kas>();

    const saveDataKas = async () => {
        console.log(dataKas);
        const response = await saveKas(dataKas!, token as string);
        const responseBody = await response.json();

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

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

    useEffect(() => {
        if (detailKas.data) {
            const data: Kas = detailKas.data;

            setDataKas(data);
        }
    }, [detailKas.data]);

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

    return (
        <>
            <div className="container" style={{ width: 1024 }}>
                <div className="card rounded-4 shadow-lg mx-auto">
                    <div className="card-header py-3 bg-transparent">
                        <h5 className="m-0">Data Kas</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">ID</label>
                                    <div className="col-md-5">
                                        <div className="input-group">
                                            <input className="form-control" placeholder="ID Penempatan Bank" readOnly value={dataKas?.id ?? ''} />
                                        </div>
                                    </div>
                                </div>
                                <div className="row mb-2">
                                    <label className="col-form-label col-md-3">Nama</label>
                                    <div className="col-md-9">
                                        <div className="input-group">
                                            <input
                                                className="form-control"
                                                placeholder="Nama"
                                                value={dataKas?.nama ?? ''}
                                                name="nama"
                                                onChange={handleChange}
                                            />
                                        </div>
                                    </div>
                                </div>
                                <hr />
                                <div>
                                    <div className="form-group row mb-2">
                                        <label className="col-form-label col-md-3">Saldo</label>
                                        <div className="col-md-5">
                                            <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={dataKas?.saldo ?? '0'}
                                                />
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <hr />
                                <div className="row mb-2">
                                    <label className="col-form-label col-md-3">Akun Jurnal</label>
                                    <div className="col-md-5">
                                        <div className="input-group">
                                            <input
                                                className="form-control border-end-0"
                                                placeholder="Rekening"
                                                readOnly
                                                value={dataKas?.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={dataKas?.jurnal?.nama ?? ''} />
                                    </div>
                                </div>
                                <div className="row mb-2">
                                    <label className="col-form-label col-md-3">Atur sebagai default</label>
                                    <div className="col-md-5 d-flex align-items-center">
                                        <div className="form-check form-switch">
                                            <input
                                                className="form-check-input"
                                                type="checkbox"
                                                role="switch"
                                                id="switchCheckChecked"
                                                checked={dataKas?.is_default ? true : false}
                                                onChange={() => setDataKas({ ...dataKas, is_default: !dataKas?.is_default == true ? 1 : 0 })}
                                            />
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div className="col-md-3">
                                <div className="d-flex">
                                    <Link to={`/app/master/kas/${id}/statement-transaksi`} className="btn btn-primary flex-grow-1">
                                        Statement Transaksi
                                    </Link>
                                </div>
                                <div className="form-label mt-3">
                                    <label className="form-label">Dibuat pada</label>
                                    <input className="form-control text-center" readOnly value={formatTanggal(dataKas?.created_at)} />
                                </div>
                            </div>
                        </div>
                    </div>
                    <div className="card-footer py-3 justify-content-between d-flex bg-transparent">
                        <Link to={`/app/master/kas/`} className="btn btn-danger">
                            Kembali
                        </Link>
                        <ButtonSubmit className="btn btn-success" icon={<Save size={18} />} onClick={async () => saveDataKas()}>
                            Simpan
                        </ButtonSubmit>
                    </div>
                </div>
            </div>
            {modalAkun.modal}
        </>
    );
}
