import { deleteTransaksiDeposito, validasiTransaksiDeposito } from '@/api/api_deposito';
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 { formatDate, formatNumber } from '@/helper';
import { TransaksiDepositoModel } from '@/types';
import { useTransaksiDeposito } from '@/useQuery/query';
import { usePage } from '@inertiajs/react';
import { Eye, Filter, PlusCircle } from 'lucide-react';
import { useState } from 'react';
import 'react-data-grid/lib/styles.css';
import { useModalTransaksiDeposito } from './modalTransaksiDeposito';

export default function BrowseTransaksiDepositoPage() {
    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 { token } = usePage().props;

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

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

    const transaksiDeposito = useTransaksiDeposito(filter);

    const modalTransaksiDeposito = useModalTransaksiDeposito({
        onSubmit: async () => {
            await transaksiDeposito.refetch();
            return true;
        },
    });

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

    const modalJurnal = useCostumModalJurnal<TransaksiDepositoModel>({
        column: column,
        onDelete: async (transId) => {
            const { isConfirmed } = await passwordPrompt({
                message: 'Apa kamu yakin akan membatalkan transaksi ini?',
                callback: async () => {
                    try {
                        const response = await deleteTransaksiDeposito(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 {
                        transaksiDeposito.refetch();
                    }
                },
            });
            return isConfirmed;
        },
        onValidate: async (transId) => {
            const { isConfirmed } = await passwordPrompt({
                message: 'Apa kamu yakin akan memvalidasi transaksi ini?',
                callback: async () => {
                    try {
                        const response = await validasiTransaksiDeposito(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 {
                        transaksiDeposito.refetch();
                    }
                },
            });
            return isConfirmed;
        },
    });

    return (
        <>
            <div className="container">
                <PageHeader
                    title="Transaksi Deposito"
                    breadcrumb={[
                        {
                            title: 'Transaksi',
                            path: '/app/transaksi',
                        },
                        {
                            title: 'Deposito',
                            path: '/app/transaksi/deposito',
                        },
                    ]}
                />
                <DataTable
                    data={transaksiDeposito.data ?? []}
                    column={column}
                    search
                    pagination
                    item_per_page={15}
                    loading={transaksiDeposito.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/deposito/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={() => modalTransaksiDeposito.open()}
                            >
                                <PlusCircle size={18} />
                                Tambah Transaksi
                            </button>
                        </div>
                    }
                />
            </div>
            {modalJurnal.modal}
            {modalTransaksiDeposito.modal}
        </>
    );
}
