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';

import ProtectedRoute from '@/components/ProtectedRoute';
import { logActivity } from '@/utils/activityLogger';

interface User {
    id: string;
    name: string;
    email: string;
    role: string;
    phone: string;
    birthday: string;
    birthday_notification: boolean;
    gender: string;
    is_google: string;
    is_woo: string;
    is_fb: string;
    isSubscribe: string;
    shipping: {
        name: string;
        phone: String;
        address: String;
        kecamatan: String;
        kelurahan: String;
        kota: String;
        provinsi: String;
        kodepos: String;
    };
    point: number;
    createdAt: string;
}

const SettingUser = () => {
    const dispatch = useDispatch();
    useEffect(() => {
        dispatch(setPageTitle('Users'));
    }, []);
    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<User[]>([]);
    const [totalRecords, setTotalRecords] = useState(0);
    const [search, setSearch] = useState('');
    const [roleFliter, setRoleFilter] = useState('');

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

    // 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/users/data?page=${page}&per_page=${pageSize}&role=${roleFliter}&q=${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();
            }
        }
    };

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

    async function handleDownloadExcel(data: any) {
        const XLSX = await import('xlsx');
        const workbook = XLSX.utils.book_new();
        const worksheet = XLSX.utils.json_to_sheet(data);

        XLSX.utils.book_append_sheet(workbook, worksheet, 'User');

        XLSX.writeFile(workbook, 'User.xlsx', { compression: true });
    }

    const fetchAllCustomer = async () => {
        const api_url = process.env.API_URL;
        const response = await fetch(`${api_url}api/users/data/all`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'include', // Include this option
        });
        return await response.json();
    };

    const handleDownload = async () => {
        setIsLoadingDownload(true);
        const allData = await fetchAllCustomer();

        if (allData.length > 0) {
            const mappingUser = allData.map((data: User) => ({
                email: data.email || '',
                name: data.name || '',
                phone: data.phone || '',
                role: data.role || '',
                is_subscribe: data.isSubscribe || '',
                login_google: data.is_google || '',
                login_woo: data.is_woo || '',
                registered_date: data.createdAt || '',
                birthday: data.birthday || '',
                birthday_notification: data.birthday_notification || '',
                gender: data.gender || '',
                address: data.shipping?.address || '',
                city: data.shipping?.kota || '',
                province: data.shipping?.provinsi || '',
                postal_code: data.shipping?.kodepos || '',
                kelurahan: data.shipping?.kelurahan || '',
                point: data.point || 0,
            }));
        
            handleDownloadExcel(mappingUser);
            await logActivity({
                location: 'Setting User',
                description: `User - Berhasil di download`,
            });
        }
        setIsLoadingDownload(false);
    };

    return (
        <>
            {isMounted && (
                    <>
                        <div className="mb-3">
                            <ul className="flex space-x-2 rtl:space-x-reverse">
                                <li>
                                    <span>Users</span>
                                </li>
                            </ul>
                        </div>

                        {/* table of users  */}
                        <div className="panel border-white-light px-0 dark:border-[#1b2e4b]">
                            <div className="user-table">
                                <div className="mb-4.5 flex flex-col gap-5 px-5 md:flex-row md:items-center">
                                    <div className="flex items-center gap-2">
                                        <Link href="/setting/users/add" className="btn btn-outline-primary gap-2">
                                            <svg className="h-5 w-5" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round">
                                                <line x1="12" y1="5" x2="12" y2="19"></line>
                                                <line x1="5" y1="12" x2="19" y2="12"></line>
                                            </svg>
                                            Add New User
                                        </Link>
                                    </div>
                                    <div className="flex w-full flex-col gap-4 sm:w-auto sm:flex-row sm:items-center sm:gap-3">
                                        <button className="btn btn-sm btn-outline-success flex items-center justify-center" onClick={handleDownload} disabled={isLoading}>
                                            {isLoadingDownload ? (
                                                <>
                                                    <div className="h-4 w-4 animate-spin rounded-full border-2 border-solid border-current border-r-transparent"></div>
                                                    <span className="ml-2">Downloading..</span>
                                                </>
                                            ) : (
                                                'Download User'
                                            )}
                                        </button>
                                    </div>
                                    <div className="flex ltr:ml-auto rtl:mr-auto">
                                        <select className=" form-select mr-2 text-white-dark" onChange={(e) => setRoleFilter(e.target.value)}>
                                            <option value="">All Role</option>
                                            <option value="customer">Customer</option>
                                            <option value="administrator">Administrator</option>
                                        </select>
                                        <input
                                            type="text"
                                            className="form-input w-auto"
                                            placeholder="Search User Name"
                                            value={search}
                                            onChange={(e) => setSearch(e.target.value)}
                                            onKeyDown={handleKeypress}
                                        />
                                    </div>
                                </div>
                                <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: ({ id, email }) => (
                                                        <Link href={`/setting/users/edit/${id}`}>
                                                            <div className="font-semibold 	 hover:no-underline">{email}</div>
                                                        </Link>
                                                    ),
                                                },

                                                {
                                                    accessor: 'name',
                                                },
                                                {
                                                    accessor: 'role',
                                                },
                                                {
                                                    accessor: 'is subscribe',
                                                    render: ({ isSubscribe }) => <div className="font-semibold 	">{isSubscribe ? 'subscribed' : ''}</div>,
                                                },
                                                {
                                                    accessor: 'social login',
                                                    render: ({ is_google, is_fb, is_woo }) => (
                                                        <div className="font-semibold 	">
                                                            {is_google && 'google'} {is_fb && 'fb'} {is_woo && 'woo'}
                                                        </div>
                                                    ),
                                                },
                                                {
                                                    accessor: 'phone',
                                                },
                                                {
                                                    accessor: 'registered date',
                                                    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
                                                    },
                                                },

                                                {
                                                    accessor: 'action',
                                                    title: 'Actions',
                                                    textAlign: 'center',
                                                    render: ({ id }) => (
                                                        <div className="mx-auto flex w-max items-center gap-4">
                                                            <Link href={`/setting/users/edit/${id}`} className="flex hover:text-info">
                                                                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" className="h-4.5 w-4.5">
                                                                    <path
                                                                        opacity="0.5"
                                                                        d="M22 10.5V12C22 16.714 22 19.0711 20.5355 20.5355C19.0711 22 16.714 22 12 22C7.28595 22 4.92893 22 3.46447 20.5355C2 19.0711 2 16.714 2 12C2 7.28595 2 4.92893 3.46447 3.46447C4.92893 2 7.28595 2 12 2H13.5"
                                                                        stroke="currentColor"
                                                                        strokeWidth="1.5"
                                                                        strokeLinecap="round"
                                                                    ></path>
                                                                    <path
                                                                        d="M17.3009 2.80624L16.652 3.45506L10.6872 9.41993C10.2832 9.82394 10.0812 10.0259 9.90743 10.2487C9.70249 10.5114 9.52679 10.7957 9.38344 11.0965C9.26191 11.3515 9.17157 11.6225 8.99089 12.1646L8.41242 13.9L8.03811 15.0229C7.9492 15.2897 8.01862 15.5837 8.21744 15.7826C8.41626 15.9814 8.71035 16.0508 8.97709 15.9619L10.1 15.5876L11.8354 15.0091C12.3775 14.8284 12.6485 14.7381 12.9035 14.6166C13.2043 14.4732 13.4886 14.2975 13.7513 14.0926C13.9741 13.9188 14.1761 13.7168 14.5801 13.3128L20.5449 7.34795L21.1938 6.69914C22.2687 5.62415 22.2687 3.88124 21.1938 2.80624C20.1188 1.73125 18.3759 1.73125 17.3009 2.80624Z"
                                                                        stroke="currentColor"
                                                                        strokeWidth="1.5"
                                                                    ></path>
                                                                    <path
                                                                        opacity="0.5"
                                                                        d="M16.6522 3.45508C16.6522 3.45508 16.7333 4.83381 17.9499 6.05034C19.1664 7.26687 20.5451 7.34797 20.5451 7.34797M10.1002 15.5876L8.4126 13.9"
                                                                        stroke="currentColor"
                                                                        strokeWidth="1.5"
                                                                    ></path>
                                                                </svg>
                                                            </Link>
                                                        </div>
                                                    ),
                                                },
                                            ]}
                                            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} users`}
                                        />
                                    )}
                                </div>
                            </div>
                        </div>
                    </>
                )}
        </>
    );
};

export default SettingUser;
