import { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import 'mantine-datatable/styles.css';
import { DataTable } from '@/components/Shared/DataTable';

import { setPageTitle } from '../../store/themeConfigSlice';
import Link from 'next/link';


interface Log {
    user_id: {
        email: string;
        name: string;
    };
    point_amount: number;
    description: string;
    createdAt: Date;
}

const PointLog = () => {
    const dispatch = useDispatch();
    useEffect(() => {
        dispatch(setPageTitle('Point Logs'));
    }, []);

    const [isMounted, setIsMounted] = useState(false);
    useEffect(() => {
        setIsMounted(true);
    }, []);

    const [page, setPage] = useState(1);
    const PAGE_SIZES = [5, 10, 20, 30, 50, 100];
    const [pageSize, setPageSize] = useState(PAGE_SIZES[0]);
    const [records, setRecords] = useState<Log[]>([]);
    const [totalRecords, setTotalRecords] = useState(0);
    const [search, setSearch] = useState('');

    const [isLoading, setIsLoading] = useState(true); // Add isLoading state

    // Fetch data from API
    const fetchData = async () => {
        setIsLoading(true); // Set isLoading to true before fetching data
        try {
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/point/logs?page=${page}&per_page=${pageSize}&email=${search}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'include', // Include this option
            });
            const data = await response.json();

            setPage(data.currentPage);
            setTotalRecords(data.totalData);
            setRecords(data.data);

            setIsLoading(false); // Set isLoading to false after data is fetched
        } catch (error) {
            console.error('Error fetching data:', error);
            setIsLoading(false); // Set isLoading to false even if there's an error
        }
    };

    useEffect(() => {
        fetchData();
    }, [page, pageSize]);

    const handleKeypress = (event: React.KeyboardEvent<HTMLInputElement>) => {
        if (event.keyCode === 13) {
            if (page !== 1) {
                setPage(1);
            } else {
                fetchData();
            }
        }
    };

    return (
        <>
                {isMounted && (
                    <>
                        <div className="mb-3">
                            <ul className="flex space-x-2 rtl:space-x-reverse">
                                <li>
                                    <Link href="/points" className="text-primary hover:underline">
                                        Points
                                    </Link>
                                </li>
                                <li className="before:content-['/'] ltr:before:mr-2 rtl:before:ml-2">
                                    <span>logs</span>
                                </li>
                            </ul>
                        </div>
                        {/* table of users  */}

                        <div className="flex flex-wrap items-center justify-between gap-4">
                            <div className="flex w-full flex-col gap-4 sm:w-auto sm:flex-row sm:items-center sm:gap-3">
                                <div className="relative">
                                    <input
                                        type="text"
                                        placeholder="Search by email"
                                        className="peer form-input py-2 ltr:pr-11 rtl:pl-11"
                                        value={search}
                                        onChange={(e) => setSearch(e.target.value)}
                                        onKeyDown={handleKeypress}
                                    />
                                    <div className="absolute top-1/2 -translate-y-1/2 peer-focus:text-primary ltr:right-[11px] rtl:left-[11px]">
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <circle cx="11.5" cy="11.5" r="9.5" stroke="currentColor" strokeWidth="1.5" opacity="0.5"></circle>
                                            <path d="M18.5 18.5L22 22" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"></path>
                                        </svg>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="panel mt-5  overflow-hidden border-0 px-0 pt-0">
                            <div className="user-table">
                                <div className="datatables pagination-padding">
                                    {isLoading ? (
                                        // Show loading indicator here
                                        <div className="flex justify-center py-4 text-center">
                                            <svg
                                                viewBox="0 0 24 24"
                                                width="24"
                                                height="24"
                                                stroke="currentColor"
                                                strokeWidth="1.5"
                                                fill="none"
                                                strokeLinecap="round"
                                                strokeLinejoin="round"
                                                className="h-5 w-5 animate-spin text-white-dark"
                                            >
                                                <line x1="12" y1="2" x2="12" y2="6"></line>
                                                <line x1="12" y1="18" x2="12" y2="22"></line>
                                                <line x1="4.93" y1="4.93" x2="7.76" y2="7.76"></line>
                                                <line x1="16.24" y1="16.24" x2="19.07" y2="19.07"></line>
                                                <line x1="2" y1="12" x2="6" y2="12"></line>
                                                <line x1="18" y1="12" x2="22" y2="12"></line>
                                                <line x1="4.93" y1="19.07" x2="7.76" y2="16.24"></line>
                                                <line x1="16.24" y1="7.76" x2="19.07" y2="4.93"></line>
                                            </svg>
                                            <span className="ms-3">Please wait, we&apos;re still working to load the data...</span>
                                        </div>
                                    ) : (
                                        <DataTable
                                            className="table-hover whitespace-nowrap"
                                            records={records}
                                            minHeight={250}
                                            noRecordsText="No data found"
                                            columns={[
                                                {
                                                    accessor: 'email',
                                                    render: ({ user_id }) => <div className="font-semibold">{user_id?.email || '-'}</div>,
                                                },

                                                {
                                                    accessor: 'name',
                                                    render: ({ user_id }) => <div className="font-semibold">{user_id?.name || '-'}</div>,
                                                },
                                                {
                                                    accessor: 'point_amount',
                                                    render: ({ point_amount }) => <>{point_amount.toLocaleString('id-ID')}</>,
                                                },
                                                {
                                                    accessor: 'description',
                                                },
                                                {
                                                    accessor: 'activity',
                                                    render: ({ createdAt }) => {
                                                        const createdAtDate = new Date(createdAt);
                                                        const formattedDate = createdAtDate.toLocaleDateString('id-ID'); // Format the date
                                                        const formattedTime = createdAtDate.toLocaleTimeString('id-ID'); // Format the time
                                                        return (
                                                            <>
                                                                <div className="text-xs">
                                                                    <div>{formattedDate}</div>
                                                                    <div>{formattedTime}</div>
                                                                </div>
                                                            </>
                                                        ); // Render the formatted date and time
                                                    },
                                                },
                                            ]}
                                            highlightOnHover
                                            totalRecords={totalRecords}
                                            recordsPerPage={pageSize}
                                            page={page}
                                            onPageChange={(p) => setPage(p)}
                                            recordsPerPageOptions={PAGE_SIZES}
                                            onRecordsPerPageChange={setPageSize}
                                            paginationText={({ from, to, totalRecords }) => `Showing  ${from} to ${to} of ${totalRecords} logs`}
                                        />
                                    )}
                                </div>
                            </div>
                        </div>
                    </>
                )}
        </>
    );
};

export default PointLog;
