"use client"

import Link from "next/link";
import { useEffect, useRef, useState } from "react";

interface AdminSessionData {
    id: string;
    name: string;
    ip_address: string;
    user_agent: string;
    created_at: string
    expired_at: string
}

export default function AdminSessionTable() {
    const tableRef = useRef<HTMLTableElement>(null);
    const datatable = useRef<any>(null);
    const [modules, setUsers] = useState<AdminSessionData[]>([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        loadUsers();
        return () => {
            cleanupDataTable();
        };
    }, []);


    useEffect(() => {
        if (loading) return;
        if (!tableRef.current) return;

        async function initDataTable() {
            const { DataTable } = await import(
                "simple-datatables"
            );

            cleanupDataTable();
            datatable.current = new DataTable(
                tableRef.current!,
                {
                    searchable: true,
                    perPage: 20,
                    perPageSelect: [20, 50, 10],
                }
            );
        }
        initDataTable();
    }, [loading]);

    function cleanupDataTable() {
        try {
            datatable.current?.destroy();
            datatable.current = null;

            document
                .querySelectorAll(".dataTable-wrapper")
                .forEach((el) => {
                    el.remove();
                });

        } catch (err) {
            console.log("DATATABLE CLEANUP ERROR", err);
        }
    }

    async function loadUsers() {
        try {
            const res = await fetch("/api/admin/session",
                {
                    cache: "no-store"
                }
            );

            const data = await res.json();
            setUsers(data.data ?? []);
        } catch(err) {
            console.log("LOAD BANNED ERROR", err);
        } finally {
            setLoading(false);
        }
    }

    if (loading) {
        return <p>Loading...</p>;
    }
    
    return (
        <>
            <div className="card">
                <div className="card-header align-right">
                    <h3>List Admin Session</h3>
                </div>
                <div className="table-responsive">
                    <table ref={tableRef} className="table table-selectable card-table table-vcenter text-nowrap datatable">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Admin</th>
                                <th>Login Via</th>
                                <th>IP Address</th>
                                <th>Expired Session</th>
                            </tr>
                        </thead>
                        <tbody>
                            {modules.map((data, i) => (
                                <tr key={data.id}>
                                    <td>{data.created_at}</td>
                                    <td>{data.name}</td>
                                    <td>{data.user_agent}</td>
                                    <td>{data.ip_address}</td>
                                    <td>{data.expired_at}</td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </div>
        </>
    );
}