import { deleteTransaksiTabungan, validasiTransaksiTabungan } from '@/api/api_tabungan';
import { alertError, alertSuccess, passwordPrompt } from '@/components/costum/alert';
import { ButtonSubmit } from '@/components/costum/button_submit';
import DataTable, { Column } from '@/components/costum/DataTable';
import PageHeader from '@/components/costum/page_header';
import { useCostumModalJurnal } from '@/components/modal/modalJurnalCostum';
import { useModalTransaksiTabungan } from '@/components/modal/modalTransaksiTabungan';
import { formatDate, formatNumber } from '@/helper';
import { TransaksiTabunganModel } from '@/types';
import { useTransaksiTabungan } from '@/useQuery/query';
import { usePage } from '@inertiajs/react';
import { Eye, Filter, PlusCircle } from 'lucide-react';
import { useEffect, useState } from 'react';
import 'react-data-grid/lib/styles.css';

export default function BrowseTransaksiTabunganPage() {
    const { token } = usePage().props;
    const params = new URLSearchParams(window.location.search);
    const tglAwal = params.get('tgl_awal') || formatDate(new Date());
    const tglAkhir = params.get('tgl_akhir') || formatDate(new Date());

    const [filter, setFilter] = useState({
        tgl_awal: tglAwal,
        tgl_akhir: tglAkhir,
    });

    const [filterState, setFilterState] = useState(filter);

    const transaksiTabungan = useTransaksiTabungan(filter);
    const modalTransaksi = useModalTransaksiTabungan({
        onSubmit: async () => {
            transaksiTabungan.refetch();
            return true;
        },
    });

    const column: Column<TransaksiTabunganModel>[] = [
        {
            label: <center>Trans ID</center>,
            width: 150,
            align: 'center',
            value: (data: TransaksiTabunganModel) => data.trans_id,
        },
        {
            label: <center>Rekening</center>,
            width: 150,
            align: 'center',
            value: (data: TransaksiTabunganModel) => data.rekening,
        },
        {
            label: <center>Masuk</center>,
            width: 120,
            align: 'right',
            value: (data: TransaksiTabunganModel) => formatNumber(data.setor),
        },
        {
            label: <center>Keluar</center>,
            width: 120,
            align: 'right',
            value: (data: TransaksiTabunganModel) => formatNumber(data.tarik),
        },
        {
            label: 'Keterangan',
            value: (data: TransaksiTabunganModel) => data.keterangan,
        },
        {
            label: <center>Trans Date</center>,
            width: 120,
            align: 'center',
            value: (data: TransaksiTabunganModel) => formatDate(data.trans_date),
        },
        {
            label: <center>User</center>,
            width: 120,
            align: 'center',
            value: (data: TransaksiTabunganModel) => data.user?.username,
        },
        {
            label: <center></center>,
            width: 80,
            align: 'center',
            value: (data: TransaksiTabunganModel) => (
                <span className="c-pointer" onClick={() => modalJurnal.open(data)}>
                    <Eye size={18} />
                </span>
            ),
        },
    ];

    const modalJurnal = useCostumModalJurnal<TransaksiTabunganModel>({
        column: column,
        onDelete: async (transId) => {
            const { isConfirmed } = await passwordPrompt({
                message: 'Apa kamu yakin akan membatalkan transaksi ini?',
                callback: async () => {
                    try {
                        const response = await deleteTransaksiTabungan(transId!, token as string);
                        const responseBody = await response.json();
                        if (response.status == 200) {
                            await alertSuccess(responseBody.message || 'Transaksi berhasil dihapus');
                            return true;
                        }
                        alertError(responseBody.message || 'Gagal menghapus transaksi');
                        return false;
                    } catch (error) {
                        if (error instanceof Error) {
                            alertError(error.message);
                        } else {
                            alertError('Terjadi kesalahan saat menghapus transaksi');
                        }
                        return false;
                    } finally {
                        transaksiTabungan.refetch();
                    }
                },
            });
            return isConfirmed;
        },
        onValidate: async (transId) => {
            const { isConfirmed } = await passwordPrompt({
                message: 'Apa kamu yakin akan memvalidasi transaksi ini?',
                callback: async () => {
                    try {
                        const response = await validasiTransaksiTabungan(transId!, token as string);
                        const responseBody = await response.json();
                        if (response.status == 200) {
                            await alertSuccess(responseBody.message || 'Transaksi berhasil divalidasi');
                            return true;
                        }
                        alertError(responseBody.message || 'Gagal memvalidasi transaksi');
                        return false;
                    } catch (error) {
                        if (error instanceof Error) {
                            alertError(error.message);
                        } else {
                            alertError('Terjadi kesalahan saat memvalidasi transaksi');
                        }
                        return false;
                    } finally {
                        transaksiTabungan.refetch();
                    }
                },
            });
            return isConfirmed;
        },
    });

    useEffect(() => {
        transaksiTabungan.refetch();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [filter]);

    return (
        <>
            <div className="container">
                <PageHeader
                    title="Transaksi Tabungan"
                    breadcrumb={[
                        {
                            title: 'Transaksi',
                            path: '/app/transaksi',
                        },
                        {
                            title: 'Tabungan',
                            path: '/app/transaksi/tabungan',
                        },
                    ]}
                />
                <DataTable
                    data={transaksiTabungan.data ?? []}
                    column={column}
                    search
                    pagination
                    item_per_page={15}
                    loading={transaksiTabungan.isLoading}
                    buttons={
                        <div className="d-flex gap-2">
                            <div className="input-group">
                                <input
                                    className="form-control"
                                    type="date"
                                    value={filterState.tgl_awal ?? ''}
                                    onChange={(e) => setFilterState({ ...filterState, tgl_awal: e.target.value })}
                                />
                                <span className="input-group-text">{` sampai `}</span>
                                <input
                                    className="form-control"
                                    type="date"
                                    value={filterState.tgl_akhir ?? ''}
                                    onChange={(e) => setFilterState({ ...filterState, tgl_akhir: e.target.value })}
                                />
                                <ButtonSubmit
                                    className="btn-secondary"
                                    icon={<Filter size={18} />}
                                    onClick={() => {
                                        window.history.replaceState(
                                            {},
                                            '',
                                            `?tgl_awal=${encodeURIComponent(filterState.tgl_awal)}&tgl_akhir=${encodeURIComponent(filterState.tgl_akhir)}`,
                                        );
                                        setFilter(filterState);
                                    }}
                                >
                                    Filter
                                </ButtonSubmit>
                            </div>
                            {/* <Link
                                to={'/app/transaksi/tabungan/add'}
                                className="btn btn-primary d-flex gap-2 align-items-center justify-content-center"
                                style={{
                                    width: 230,
                                }}
                            >
                                <PlusCircle size={18} />
                                Tambah Transaksi
                            </Link> */}
                            <button
                                className="btn btn-primary d-flex gap-2 align-items-center justify-content-center"
                                style={{
                                    width: 230,
                                }}
                                onClick={() => modalTransaksi.open()}
                            >
                                <PlusCircle size={18} />
                                Tambah Transaksi
                            </button>
                        </div>
                    }
                />
            </div>
            {modalJurnal.modal}
            {modalTransaksi.modal}
        </>
    );
}
