import { getLaporanLabaRugi, getLaporanNeraca } from '@/api/api_laporan';
import { alertError } from '@/components/costum/alert';
import { ButtonSubmit } from '@/components/costum/button_submit';
import { Select } from '@/components/costum/Select';
import { formatDate, formatNumber, formatTanggal } from '@/helper';
import { Filter, Neraca } from '@/types';
import { usePage } from '@inertiajs/react';
import { useCallback, useMemo, useState } from 'react';
import { Modal } from 'react-bootstrap';

const OPTION_JENIS_LAPORAN = [
    {
        label: '1 : Neraca',
        value: '1',
    },
    {
        label: '2 : Laba Rugi',
        value: '2',
    },
];

export interface LaporanNeracaProps {
    jenis?: string;
    tanggal?: string;
}

export default function LaporanNeraca() {
    const { token } = usePage().props;
    const [laporan, setLaporan] = useState<Filter>({
        tanggal: formatDate(new Date()),
    });

    const modalLaporanNeraca = useModalLaporanNeraca();
    const modalLaporanLabaRugi = useModalLaporanLabaRugi();

    const getLaporan = useCallback(async () => {
        if (laporan.jenis == '1') {
            const response = await getLaporanNeraca(laporan, token as string);
            const responseBody = await response.json();
            if (response.status == 200) {
                console.log(responseBody);
                modalLaporanNeraca.open(responseBody, laporan);
            } else {
                alertError(responseBody.message);
            }
        }
        if (laporan.jenis == '2') {
            const response = await getLaporanLabaRugi(laporan, token as string);
            const responseBody = await response.json();
            if (response.status == 200) {
                console.log(responseBody);
                modalLaporanLabaRugi.open(responseBody, laporan);
            } else {
                alertError(responseBody.message);
            }
        }
    }, [laporan, modalLaporanLabaRugi, modalLaporanNeraca, 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 Akuntansi</h5>
                        </div>
                        <div className="card-body">
                            <div className="row mb-2">
                                <label className="col-form-label col-md-4">Jenis Laporan</label>
                                <div className="col-md-8">
                                    <Select
                                        options={OPTION_JENIS_LAPORAN}
                                        placeholder="Pilih Jenis Laporan"
                                        value={OPTION_JENIS_LAPORAN.find((opt) => opt.value == String(laporan.jenis))}
                                        onChange={(value: unknown) => {
                                            if (value) {
                                                const option = value as { label: string; value: string };
                                                setLaporan({ ...laporan, jenis: option.value });
                                            } else {
                                                setLaporan({ ...laporan, jenis: undefined });
                                            }
                                        }}
                                    />
                                </div>
                            </div>
                            <div className="row">
                                <label className="col-form-label col-md-4">Periode</label>
                                <div className="col-md-5">
                                    <div className="input-group">
                                        <input
                                            className="form-control text-center"
                                            type="date"
                                            value={laporan.tanggal ?? ''}
                                            onChange={(e) => {
                                                setLaporan({ ...laporan, tanggal: e.target.value });
                                            }}
                                        />
                                    </div>
                                </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>
            {modalLaporanNeraca.modal}
            {modalLaporanLabaRugi.modal}
        </>
    );
}

const useModalLaporanNeraca = () => {
    const [show, setShow] = useState<boolean>(false);
    const [neraca, setNeraca] = useState<Neraca>({ aktiva: [], pasiva: [] });
    const [filter, setFilter] = useState<Filter>();

    const open = (data: Neraca[], filter: Filter) => {
        setFilter(filter);
        setNeraca(data);
        setShow(true);
    };
    const close = () => setShow(false);

    const renderTableNeraca = useCallback(() => {
        const length = neraca.aktiva!.length > neraca.pasiva!.length ? neraca.aktiva!.length : neraca.pasiva!.length;

        return Array.from({ length }, (_, idx: number) => {
            return (
                <tr>
                    <td className="text-center">{neraca.aktiva![idx]?.kode_akun}</td>
                    <td
                        style={{
                            paddingLeft: (neraca.aktiva![idx]?.level ?? 0) * 10,
                        }}
                    >
                        {neraca.aktiva![idx]?.nama?.toUpperCase()}
                    </td>
                    <td className="text-end">{formatNumber(neraca.aktiva![idx]?.saldo ?? 0)}</td>
                    <td className="text-center">{neraca.pasiva![idx]?.kode_akun}</td>
                    <td
                        style={{
                            paddingLeft: (neraca.pasiva![idx]?.level ?? 0) * 10,
                        }}
                    >
                        {neraca.pasiva![idx]?.nama?.toUpperCase()}
                    </td>
                    <td className="text-end">{formatNumber(neraca.pasiva![idx]?.saldo ?? 0)}</td>
                </tr>
            );
        });
    }, [neraca]);

    const modal = useMemo(() => {
        return (
            <Modal show={show} onHide={close} fullscreen>
                <Modal.Header closeButton>
                    <h6 className="m-0">Laporan Neraca</h6>
                </Modal.Header>
                <Modal.Body className="bg-secondary">
                    <div className="p-3 bg-white container" style={{ width: 1200 }}>
                        <div className="text-center">
                            <h6 className="fw-bold">LAPORAN NERACA</h6>
                            <p>Periode : {formatTanggal(filter?.tanggal)}</p>
                        </div>

                        <table className="table-bordered table-neraca table-sm table">
                            <thead>
                                <tr style={{ backgroundColor: '#D2D0CA' }}>
                                    <th className="text-center" style={{ width: '5%' }}>
                                        KODE
                                    </th>
                                    <th className="text-center" style={{ width: '35%' }}>
                                        AKTIVA
                                    </th>
                                    <th className="text-center" style={{ width: '10%' }}>
                                        SALDO
                                    </th>
                                    <th className="text-center" style={{ width: '5%' }}>
                                        KODE
                                    </th>
                                    <th className="text-center" style={{ width: '35%' }}>
                                        PASIVA
                                    </th>
                                    <th className="text-center" style={{ width: '10%' }}>
                                        SALDO
                                    </th>
                                </tr>
                            </thead>
                            <tbody>{renderTableNeraca()}</tbody>
                            <tfoot>
                                <tr style={{ backgroundColor: '#D2D0CA' }}>
                                    <td colSpan={2} className="fw-bold text-center">
                                        TOTAL AKTIVA
                                    </td>
                                    <td className="text-end">0</td>
                                    <td colSpan={2} className="fw-bold text-center">
                                        TOTAL PASIVA
                                    </td>
                                    <td className="text-end">0</td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </Modal.Body>
                <Modal.Footer></Modal.Footer>
            </Modal>
        );
    }, [filter?.tanggal, renderTableNeraca, show]);

    return { modal, open, close };
};

const useModalLaporanLabaRugi = () => {
    const [show, setShow] = useState<boolean>(false);
    const [neraca, setNeraca] = useState<Neraca>({ aktiva: [], pasiva: [] });
    const [filter, setFilter] = useState<Filter>();

    const open = (data: Neraca[], filter: Filter) => {
        setFilter(filter);
        setNeraca(data);
        setShow(true);
    };
    const close = () => setShow(false);

    const renderTableNeraca = useCallback(() => {
        const length = neraca.laba?.length > neraca.rugi?.length ? neraca.laba?.length : neraca.rugi?.length;

        return Array.from({ length }, (_, idx: number) => {
            return (
                <tr>
                    <td className="text-center">{neraca.laba![idx]?.kode_akun}</td>
                    <td
                        style={{
                            paddingLeft: (neraca.laba![idx]?.level ?? 0) * 10,
                        }}
                    >
                        {neraca.laba![idx]?.nama?.toUpperCase()}
                    </td>
                    <td className="text-end">{formatNumber(neraca.laba![idx]?.saldo ?? 0)}</td>
                    <td className="text-center">{neraca.rugi![idx]?.kode_akun}</td>
                    <td
                        style={{
                            paddingLeft: (neraca.rugi![idx]?.level ?? 0) * 10,
                        }}
                    >
                        {neraca.rugi![idx]?.nama?.toUpperCase()}
                    </td>
                    <td className="text-end">{formatNumber(neraca.rugi![idx]?.saldo ?? 0)}</td>
                </tr>
            );
        });
    }, [neraca]);

    const modal = useMemo(() => {
        return (
            <Modal show={show} onHide={close} fullscreen>
                <Modal.Header closeButton>
                    <h6 className="m-0">Laporan Laba Rugi</h6>
                </Modal.Header>
                <Modal.Body className="bg-secondary">
                    <div className="p-3 bg-white container" style={{ width: 1200 }}>
                        <div className="text-center">
                            <h6 className="fw-bold">LAPORAN LABA RUGI</h6>
                            <p>Periode : {formatTanggal(filter?.tanggal)}</p>
                        </div>

                        <table className="table-bordered table-neraca table-sm table">
                            <thead>
                                <tr style={{ backgroundColor: '#D2D0CA' }}>
                                    <th className="text-center" style={{ width: '5%' }}>
                                        KODE
                                    </th>
                                    <th className="text-center" style={{ width: '35%' }}>
                                        PENDAPATAN
                                    </th>
                                    <th className="text-center" style={{ width: '10%' }}>
                                        SALDO
                                    </th>
                                    <th className="text-center" style={{ width: '5%' }}>
                                        KODE
                                    </th>
                                    <th className="text-center" style={{ width: '35%' }}>
                                        BIAYA
                                    </th>
                                    <th className="text-center" style={{ width: '10%' }}>
                                        SALDO
                                    </th>
                                </tr>
                            </thead>
                            <tbody>{renderTableNeraca()}</tbody>
                            <tfoot>
                                <tr style={{ backgroundColor: '#D2D0CA' }}>
                                    <td colSpan={2} className="fw-bold text-center">
                                        TOTAL PENDAPATAN
                                    </td>
                                    <td className="text-end">0</td>
                                    <td colSpan={2} className="fw-bold text-center">
                                        TOTAL BIAYA
                                    </td>
                                    <td className="text-end">0</td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </Modal.Body>
                <Modal.Footer></Modal.Footer>
            </Modal>
        );
    }, [filter?.tanggal, renderTableNeraca, show]);

    return { modal, open, close };
};
