import { deleteTransaksiKas, validasiTransaksiKas } from '@/api/api_kas';
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 { useModalTransaksiKas } from '@/pages/transaksi/kas/modalTransaksiKas';
import { formatDate, formatDateTime, formatNumber } from '@/helper';
import { TransaksiKasModel, TransaksiPenempatanModel } from '@/types';
import { useTransaksiKas } from '@/useQuery/query';
import { Eye, Filter, PlusCircle } from 'lucide-react';
import { useEffect, useState } from 'react';
import 'react-data-grid/lib/styles.css';
import { usePage } from '@inertiajs/react';

export default function BrowseTransaksiKasPage() {
    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 transaksiKas = useTransaksiKas(filter);
    const modalTransaksi = useModalTransaksiKas({
        onSubmit: async () => {
            transaksiKas.refetch();
            return true;
        },
    });

    const column: Column<TransaksiKasModel | TransaksiPenempatanModel>[] = [
        {
            label: <center>Trans ID</center>,
            width: 150,
            align: 'center',
            value: (data: TransaksiKasModel | TransaksiPenempatanModel) => data.trans_id,
        },
        {
            label: <center>Sumber</center>,
            width: 100,
            align: 'center',
            value: (data: TransaksiKasModel | TransaksiPenempatanModel) => ('akun' in data && data.akun ? 'KAS' : 'BANK'),
        },
        {
            label: <center>Rekening</center>,
            width: 200,
            value: (data: TransaksiKasModel | TransaksiPenempatanModel) => ('akun' in data && data.akun ? data.kas.nama : data.penempatan.nama),
        },
        // {
        //     label: <center>Akun</center>,
        //     width: 120,
        //     align: 'center',
        //     value: (data: TransaksiKasModel | TransaksiPenempatanModel) =>
        //         data.akun?.kode_akun ?? (data.debet == 0 ? data.akun_debet : data.akun_kredit),
        // },
        {
            label: <center>Masuk</center>,
            width: 120,
            align: 'right',
            value: (data: TransaksiKasModel | TransaksiPenempatanModel) =>
                formatNumber('masuk' in data ? data.masuk : (data as TransaksiPenempatanModel).debet),
        },
        {
            label: <center>Keluar</center>,
            width: 120,
            align: 'right',
            value: (data: TransaksiKasModel | TransaksiPenempatanModel) => formatNumber(((data as TransaksiKasModel).keluar ?? (data as TransaksiPenempatanModel).kredit) ?? 0),
        },
        {
            label: 'Keterangan',
            value: (data: TransaksiKasModel | TransaksiPenempatanModel) => data.keterangan,
        },
        {
            label: <center>Trans Date</center>,
            width: 160,
            align: 'center',
            value: (data: TransaksiKasModel | TransaksiPenempatanModel) => formatDateTime(data.trans_date),
        },
        {
            label: <center>User</center>,
            width: 120,
            align: 'center',
            value: (data: TransaksiKasModel | TransaksiPenempatanModel) => data.user?.username,
        },
        {
            label: <center></center>,
            width: 80,
            align: 'center',
            value: (data: TransaksiKasModel | TransaksiPenempatanModel) => (
                <span className="c-pointer" onClick={() => modalJurnal.open(data)}>
                    <Eye size={18} />
                </span>
            ),
        },
    ];

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

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

    return (
        <>
            <div className="container">
                <PageHeader
                    title="Transaksi Kas"
                    breadcrumb={[
                        {
                            title: 'Transaksi',
                            path: '/app/transaksi',
                        },
                        {
                            title: 'Kas',
                            path: '/app/transaksi/kas',
                        },
                    ]}
                />
                <DataTable
                    data={transaksiKas.data ?? []}
                    column={column}
                    search
                    pagination
                    item_per_page={15}
                    loading={transaksiKas.isLoading || transaksiKas.isFetching}
                    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>
                            <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}
        </>
    );
}
