import { saveAkun } from '@/api/api_akun';
import { Akun } from '@/types';
import { useAkun } from '@/useQuery/query';
import { usePage } from '@inertiajs/react';
import { Delete } from 'lucide-react';
import { useCallback, useMemo, useState } from 'react';
import { Modal } from 'react-bootstrap';
import { alertError, alertSuccess } from '../costum/alert';
import { useModalAkun } from './modalAkun';

export const useModalBrowseAkun = ({ onSelected }: { onSelected?: ({ akun, selector }: { akun: Akun; selector?: string }) => void }) => {
    const [showModal, setShowModal] = useState(false);
    const [target, setTarget] = useState<string>();
    const [query, setQuery] = useState<string>('');
    const { token } = usePage().props;

    const daftar_akun = useAkun();

    const modalAkun = useModalAkun({
        onSubmit: async (akun: Akun) => {
            const response = await saveAkun(akun, token as string);
            const data = await response.json();
            if (response.status == 200 || response.status == 201) {
                daftar_akun.refetch();
                await alertSuccess('Akun berhasil disimpan');
                return true;
            } else {
                await alertError(data.message);
                return false;
            }
        },
    });

    const open = (selector?: string) => {
        setShowModal(true);
        setTarget(selector);
    };

    const close = () => {
        setShowModal(false);
    };

    const filterData = useCallback(() => {
        const data = daftar_akun.data ?? [];
        if (query.trim() !== '') {
            let filteredData = data;
            // filter by kode akun
            filteredData = data.filter((item: Akun) => item.kode_akun?.toString().toLowerCase().includes(query.toLowerCase()));
            // // if no result, filter by nama akun
            if (filteredData.length === 0) {
                filteredData = data.filter((item: Akun) => item.nama?.toLowerCase().includes(query.toLowerCase()));
            }
            return filteredData;
        }
        return data;
    }, [daftar_akun, query]);

    const modal = useMemo(() => {
        return (
            <>
                <Modal show={showModal} onHide={close} size="xl" scrollable className="modal-browse-akun" onExited={() => setQuery('')}>
                    <Modal.Header closeButton>
                        <h5 className="m-0">Daftar Akun</h5>
                    </Modal.Header>
                    <Modal.Body className="p-0">
                        <table className="table-bordered mb-0 table-sm table-hover table">
                            <thead>
                                <tr className="fixed">
                                    <th className="text-center">Kode Akun</th>
                                    <th>Nama Akun</th>
                                    <th className="text-center">Kategori</th>
                                    <th className="text-center">Jurnal</th>
                                    <th className="text-center">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                {filterData().map((item: Akun) => {
                                    return (
                                        <tr key={item.id}>
                                            <td className="text-center" width={100}>
                                                {item.kode_akun}
                                            </td>
                                            <td>
                                                <div
                                                    style={{
                                                        paddingLeft: (item.level ?? 0) * 10,
                                                    }}
                                                >
                                                    {item.nama}
                                                </div>
                                            </td>
                                            <td className="text-center" width={120}>
                                                {item.kategori}
                                            </td>
                                            <td className="text-center" width={100}>
                                                {item.jurnal}
                                            </td>
                                            <td width={100} className="text-center">
                                                <div className="d-flex justify-content-center gap-2">
                                                    <div
                                                        className="badge text-bg-primary"
                                                        style={{ cursor: 'pointer' }}
                                                        onClick={() => {
                                                            close();
                                                            onSelected?.({
                                                                akun: item,
                                                                selector: target,
                                                            });
                                                        }}
                                                    >
                                                        Pilih
                                                    </div>
                                                    <div
                                                        className="badge text-bg-warning"
                                                        style={{ cursor: 'pointer' }}
                                                        onClick={() => {
                                                            modalAkun.open(item);
                                                        }}
                                                    >
                                                        Edit
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                    );
                                })}
                            </tbody>
                        </table>
                    </Modal.Body>
                    <Modal.Footer className="justify-content-between">
                        <div className="row">
                            <div className="d-flex gap-2">
                                <div>
                                    <div className="input-group">
                                        <input className="form-control border-end-0" onChange={(e) => setQuery(e.target.value)}
                                            value={query}
                                            placeholder='Cari'
                                        />
                                        <span className="input-group-text bg-white">
                                            {query.length > 0 && <Delete size={18} className='c-pointer' onClick={() => setQuery('')} />}
                                        </span>
                                    </div>
                                </div>
                                <div>
                                    <button className="btn btn-primary" onClick={() => modalAkun.open()}>
                                        Buat Akun Baru
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div>
                            <button className="btn btn-primary" onClick={close}>
                                Tutup
                            </button>
                        </div>
                    </Modal.Footer>
                </Modal>
                {modalAkun.modal}
            </>
        );
    }, [filterData, modalAkun, onSelected, query, showModal, target]);

    return { modal, open, close };
};
