import { getLaporanNominatifTabungan } from '@/api/api_laporan';
import { ButtonSubmit } from '@/components/costum/button_submit';
import { Select } from '@/components/costum/Select';
import { SelectProdukTabungan } from '@/components/costum/SelectProdukTabungan';
import { formatDate, formatNumber, formatTanggal } from '@/helper';
import { Tabungan } from '@/types';
import { usePage } from '@inertiajs/react';
import { useCallback, useMemo, useState } from 'react';
import { Modal } from 'react-bootstrap';

const OPTION_STATUS_REKENING = [
    {
        label: '1 : Aktif',
        value: '1',
    },
    {
        label: '3 : Tutup',
        value: '3',
    },
];

export interface LaporanTabunganProps {
    status?: number;
    produk?: string;
}

export default function LaporanNominatifTabungan() {
    const { token } = usePage().props;
    const [laporan, setLaporan] = useState<LaporanTabunganProps>({});

    const modalLaporanRincian = useModalLaporanTabungan();

    const getLaporan = useCallback(async () => {
        const response = await getLaporanNominatifTabungan(laporan, token as string);
        const responseBody = await response.json();
        console.log(responseBody);
        modalLaporanRincian.open(responseBody, laporan);
    }, [laporan, modalLaporanRincian, token]);

    return (
        <>
            <div>
                <div className="container" style={{ width: 640 }}>
                    <div className="card rounded-4 shadow-lg">
                        <div className="card-header py-3 bg-transparent">
                            <h5 className="m-0">Laporan Tabungan</h5>
                        </div>
                        <div className="card-body">
                            <div className="row mb-2">
                                <label className="col-form-label col-md-4">Produk</label>
                                <div className="col-md-8">
                                    <SelectProdukTabungan
                                        value={laporan.produk ?? ''}
                                        onChange={(value: string) => {
                                            if (value) {
                                                setLaporan({ ...laporan, produk: value });
                                            } else {
                                                setLaporan({ ...laporan, produk: undefined });
                                            }
                                        }}
                                    />
                                </div>
                            </div>
                            <div className="row mb-2">
                                <label className="col-form-label col-md-4">Status</label>
                                <div className="col-md-8">
                                    <Select
                                        options={OPTION_STATUS_REKENING}
                                        placeholder="Pilih Status"
                                        value={OPTION_STATUS_REKENING.find((opt) => opt.value === String(laporan.status))}
                                        onChange={(value: unknown) => {
                                            if (value) {
                                                const option = value as { label: string; value: string };
                                                setLaporan({ ...laporan, status: Number(option.value) });
                                            } else {
                                                setLaporan({ ...laporan, status: undefined });
                                            }
                                        }}
                                    />
                                </div>
                            </div>
                        </div>
                        <div className="card-footer py-3 justify-content-end d-flex bg-transparent">
                            <ButtonSubmit className="btn btn-primary" onClick={async () => getLaporan()}>
                                Sumbit
                            </ButtonSubmit>
                        </div>
                    </div>
                </div>
            </div>
            {modalLaporanRincian.modal}
        </>
    );
}

const useModalLaporanTabungan = () => {
    const [show, setShow] = useState<boolean>(false);
    const [laporan, setLaporan] = useState<Tabungan[]>([]);
    const [filter, setFilter] = useState<LaporanTabunganProps>();

    const open = (data: Tabungan[], filter: LaporanTabunganProps) => {
        setFilter(filter);
        setLaporan(data);
        setShow(true);
    };
    const close = () => setShow(false);

    const modal = useMemo(() => {
        return (
            <Modal show={show} onHide={close} fullscreen>
                <Modal.Header closeButton>
                    <h6 className="m-0">Laporan Tabungan</h6>
                </Modal.Header>
                <Modal.Body className="bg-secondary">
                    <div className="bg-white p-3 container" style={{ width: 1024 }}>
                        <div className="text-center mb-3">
                            <h6 className="fw-bold">Laporan Nominatif Tabungan</h6>
                            <h6>Periode {formatTanggal((new Date().toDateString()))}</h6>
                        </div>
                        <table className="table-bordered table-sm table">
                            <thead>
                                <tr className="bg-light">
                                    <th className="text-center">Rekening</th>
                                    <th className="text-center">Produk</th>
                                    <th className="text-center">Anggota</th>
                                    <th className="text-center">Saldo</th>
                                    <th className="text-center">Tgl Buka</th>
                                </tr>
                            </thead>
                            <tbody>
                                {laporan?.map((item: Tabungan, idx: number) => (
                                    <tr key={item.rekening || idx}>
                                        <td width={120} className="text-center">
                                            {item.rekening}
                                        </td>
                                        <td width={200} className="text-center">{`${item.produk?.id} : ${item.produk?.nama}`}</td>
                                        <td>{item.anggota?.nama_lengkap}</td>
                                        <td width={120} className="text-end">
                                            {formatNumber(item.saldo)}
                                        </td>
                                        <td width={120} className="text-center">
                                            {formatDate(item.tgl_buka)}
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                            <tfoot>
                                <tr className="bg-light">
                                    <td colSpan={3} className='text-end fw-bold'>Total</td>
                                    <td className='text-end fw-bold'>{formatNumber(laporan.reduce((total, item) => total + (item.saldo ?? 0), 0))}</td>
                                    <td></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </Modal.Body>
                <Modal.Footer></Modal.Footer>
            </Modal>
        );
    }, [laporan, show]);

    return { modal, open, close };
};
