"use client"

import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import Swal from "sweetalert2";
import CreateAdminModal from "@/components/modal/CreateAdminModal"

interface AdminData {
    id: string;
    name: string;
    last_login: string;
    created_at: string;
    failed_log: number
}

export default function AdminTable() {
    const tableRef = useRef<HTMLTableElement>(null);
    const datatable = useRef<any>(null);
    const [modules, setUsers] = useState<AdminData[]>([]);
    const [loading, setLoading] = useState(true);
    const [showCreateAdmin, setShowCreateAdmin] = useState(false);

    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",
                {
                    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>;
    }

    const handleDelete = async (adminId: string) => {
        const result = await Swal.fire({
            title: "Delete Admin?",
            text: "Are you sure you want to delete this admin?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "Yes, delete it",
            cancelButtonText: "Cancel",
            reverseButtons: true,
        });

        if (!result.isConfirmed) {
            return;
        }

        Swal.fire({
            title: "Resolving Ticket...",
            text: "Please wait",
            allowOutsideClick: false,
            allowEscapeKey: false,
            didOpen: () => {
                Swal.showLoading();
            },
        });

        try {
            const response = await fetch(`/api/admin/${adminId}`,
                {
                    method: "DELETE",
                }
            );

            const data = await response.json();
            Swal.close();

            if (!response.ok) {
                await Swal.fire({
                    icon: "error",
                    title: "Failed",
                    text: data.msg || "Something went wrong",
                });

                return;
            }

            const success = await Swal.fire({
                icon: "success",
                title: "Success!",
                text: data.msg,
                confirmButtonText: "OK",
            });

            if (success.isConfirmed) {
                window.location.reload();
            }
        } catch (error) {
            console.log("Resolve ticket error:", error);
            Swal.close();
            Swal.fire({
                icon: "error",
                title: "Error",
                text: "Something went wrong",
            });
        }
    };
    
    return (
        <>
            <div className="card">
                <div className="card-header align-right">
                    <button className="btn btn-outline btn-primary ms-auto" onClick={() => setShowCreateAdmin(true)}>
                        <span>Create New Admin</span>
                    </button>
                </div>
                <div className="table-responsive">
                    <table ref={tableRef} className="table table-selectable card-table table-vcenter text-nowrap datatable">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Created At</th>
                                <th>Last Login At</th>
                                <th>Failed Login Attempt</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            {modules.map((data, i) => (
                                <tr key={data.id}>
                                    <td>{data.name}</td>
                                    <td>{data.created_at}</td>
                                    <td>{data.last_login}</td>
                                    <td>{data.failed_log}</td>
                                    <td>
                                        <div className="btn-list flex-nowrap">
                                            <button onClick={() => handleDelete(data.id)} className="btn btn-outline btn-danger btn-sm"> Delete </button>
                                        </div>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </div>
            {showCreateAdmin && (
                <CreateAdminModal onClose={() => setShowCreateAdmin(false)} />
            )}
        </>
    );
}