import React, { useState, useEffect } from "react";
import PlayCircleIcon from '@mui/icons-material/PlayCircle';
import PreviewIcon from '@mui/icons-material/Preview';
import { getvisitorData, getNonce, isPro, } from '../../Helpers';
import orderStatus from '../../../assets/order-status.gif'
import { DataGrid } from '@mui/x-data-grid';
import Box from '@mui/material/Box';
import { format } from 'date-fns';
import Tippy from '@tippy.js/react';
import 'tippy.js/dist/tippy.css'
import NoticeModal from '../NoticeModal/NoticeModal';
import "./traffic.scss";

const Traffic = () => {
    const [modalOpen, setModalOpen] = useState(false);
    const [credentials, setCredentials] = useState([]);
    const [user, setUser] = useState(getvisitorData());
    const [selectedIds, setSelectedIds] = useState([]);
    const [searchTerm, setSearchTerm] = useState('');
    const [refreshData, setRefreshData] = useState(false);

    const proData = isPro();
    const allConditionsMet = proData;


    // Extract the last part of the URL as the site identifier
    const pathParts = window.location.pathname.split("/").filter(Boolean);
    const indexOfAdmin = pathParts.indexOf('wp-admin');
    const siteIdentifier = indexOfAdmin !== -1 ? pathParts.slice(indexOfAdmin - 1, indexOfAdmin).pop() : pathParts.slice(-1).pop();
    // Use the site identifier to create a unique localStorage key
    const localStorageKey = `wpnts_traffic_settings_${siteIdentifier}`;
    //END ------------------

    const [modalConfig, setModalConfig] = useState({
        isOpen: false,
        type: 'confirmation',
        title: '',
        message: '',
        onConfirm: () => { },
        confirmText: 'Confirm',
        declineText: 'Cancel'
    });

    const closeModal = () => {
        setModalConfig(prev => ({ ...prev, isOpen: false }));
    };

    /**
     * Leads table header column
     */
    const userColumns = [
        {
            field: "id",
            headerName: "ID",
            flex: 0.5,
            renderCell: (params) => {
                return (params.id);
            },
        },
        {
            field: "ip",
            headerName: "IP",
            flex: 1,
            renderCell: (params) => {
                return (params.ip);
            },
        },
        {
            field: "country",
            headerName: "Country",
            flex: 1,
            renderCell: (params) => {
                return (params.country);
            },
        },
        {
            field: "city",
            headerName: "City",
            flex: 1,
            renderCell: (params) => {
                return (params.city);
            },
        },

        {
            field: "visiting_time",
            headerName: "Visiting time",
            flex: 1,
            renderCell: (params) => {
                try {
                    // Check if visiting_time exists and is valid
                    if (!params?.value) {
                        // console.warn("visiting_time is undefined or null", params);
                        return "Invalid Date";
                    }

                    const date = new Date(params.value);
                    if (isNaN(date)) {
                        // console.warn("visiting_time is not a valid date", params.value);
                        return "Invalid Date";
                    }

                    return format(date, 'MMMM d, yyyy h:mm:ss a');
                } catch (error) {
                    // console.error("Error formatting visiting_time:", error);
                    return "Error";
                }
            },
        },
        {
            field: "count",
            headerName: "Visit count",
            flex: 1,
            renderCell: (params) => {
                return (params.count);
            },
        },
    ];

    /**
     * Action column
     */
    const actionColumns = [
        {
            field: "action",
            headerName: "ACTION",
            flex: 0.5,
            renderCell: (params) => (
                <div className="wpx_cellAction">
                    <div
                        className="wpx_deleteButton"
                        onClick={(event) => handleDeleteClick(params.id, event)}
                    >
                        Delete
                    </div>
                </div>
            ),
        },
    ];


    const userDummyColumns = [
        {
            field: "id",
            headerName: "ID",
            flex: 0.5,

        },
        {
            field: "ip",
            headerName: "IP",
            flex: 1,

        },
        {
            field: "country",
            headerName: "Country",
            flex: 1,

        },
        {
            field: "city",
            headerName: "City",
            flex: 1,

        },
        {
            field: "visiting_time",
            headerName: "Visiting time",
            flex: 1,

        },
        {
            field: "count",
            headerName: "Visit count",
            flex: 1,

        },

        {
            field: 'action',
            headerName: 'ACTION',
            flex: 1,
            renderCell: (params) => (
                <div className='wpx_cellAction'>
                    <div className="wpx_deleteButton" >
                        Delete
                    </div>
                </div>
            ),
        }
    ];

    const dummyData = [
        { id: '1', ip: '107.244.89.166', country: 'United States', city: 'Los Ang', visiting_time: '2024-03-14 22:42:57', count: '1', action: 'Action' },
        { id: '2', ip: '207.244.89.166', country: 'United States', city: 'Piermont', visiting_time: '5/1/2024, 5:43:23 PM', count: '2', action: 'Action' },
        { id: '3', ip: '307.244.89.166', country: 'United States', city: 'Los Ang', visiting_time: '5/1/2024, 5:43:23 PM', count: '1', action: 'Action' },
    ];


    /**
     * 
     * @param {Delete} id 
     * @param {*} event 
     */
    const handleDeleteClick = (id, event) => {
        event.stopPropagation();

        setModalConfig({
            isOpen: true,
            type: 'confirmation',
            title: 'Confirm delete!',
            message: 'Are you sure you want to delete this visitor?',
            onConfirm: () => {
                wp.ajax.send('wpnts_visitor_data_delete_leads', {
                    data: {
                        nonce: getNonce(),
                        id: id
                    },
                    success(response) {
                        setRefreshData(true);
                        setModalConfig({
                            isOpen: true,
                            type: 'toast',
                            title: 'Confirmation!',
                            message: 'visitor has been deleted.',
                            position: 'top-right'
                        });

                        // Auto close the toast after 3 seconds
                        setTimeout(closeModal, 3000);
                    },
                    error(error) {
                        setModalConfig({
                            isOpen: true,
                            type: 'toast',
                            title: 'Error!',
                            message: 'Failed to delete the visitor.',
                            position: 'top-right'
                        });

                        // Auto close the toast after 3 seconds
                        setTimeout(closeModal, 3000);
                    },
                });

                // Close the confirmation modal immediately
                closeModal();
            },
            confirmText: 'Yes, delete!',
            declineText: 'Cancel'
        });


    };

    /**
     * Bulk delete
     */
    const handleBulkDeleteClick = () => {

        setModalConfig({
            isOpen: true,
            type: 'confirmation',
            title: 'Confirm bulk delete!',
            message: 'Are you sure you want to delete all selected visitor?',
            onConfirm: () => {
                wp.ajax.send('wpnts_visitor_data_bulk_delete_leads', {
                    data: {
                        nonce: getNonce(),
                        id: selectedIds
                    },
                    success(response) {
                        setRefreshData(true);
                        setModalConfig({
                            isOpen: true,
                            type: 'toast',
                            title: 'Confirmation!',
                            message: 'visitor has been deleted.',
                            position: 'top-right'
                        });

                        // Auto close the toast after 3 seconds
                        setTimeout(closeModal, 3000);
                    },
                    error(error) {
                        setModalConfig({
                            isOpen: true,
                            type: 'toast',
                            title: 'Error!',
                            message: 'Failed to delete the visitor.',
                            position: 'top-right'
                        });

                        // Auto close the toast after 3 seconds
                        setTimeout(closeModal, 3000);
                    },
                });

                // Close the confirmation modal immediately
                closeModal();
            },
            confirmText: 'Yes, delete!',
            declineText: 'Cancel'
        });

    };

    /**
     * Realtime new leads collect
     */
    useEffect(() => {
        getUsers();
    }, [refreshData]);
    // user => makes a all time loads so removed it 
    function getUsers() {
        wp.ajax.send('wpnts_get_visitor_data', {
            data: {
                nonce: getNonce()
            },
            success(response) {
                setUser(response.visitor_data.visitor_details);
                setRefreshData(false);
            },
            error(error) {
                console.log(error)
            },
        });
    }


    useEffect(() => {
        getWebhook();
    }, []);
    function getWebhook() {
        const wpx_authors_settings = {
            webhook: "",
        };
        const formData = JSON.parse(localStorage.getItem(localStorageKey) || JSON.stringify(wpx_authors_settings));
        setCredentials(formData);
    }

    const [wpxwebhook, setWebhook] = useState({
        webhook: credentials.webhook,
    });

    useEffect(() => {
        setWebhook({
            webhook: credentials.webhook,
        });
    }, [credentials]);


    /**
     * 
     * @param {Bulk selection id} selection 
     */
    const handleCheckboxSelection = (selection) => {
        setSelectedIds(selection);
    };



    /**
     * 
     * @param {Search} event 
     */
    const handleSearchChange = (event) => {
        setSearchTerm(event.target.value);
    };

    /**
     * Filter rows based on the search term
     */
    const filteredRows = Array.isArray(user)
        ? user.filter((row) => {
            return (
                row.ip.toLowerCase().includes(searchTerm.toLowerCase()) ||
                row.country.toLowerCase().includes(searchTerm.toLowerCase()) ||
                row.city.toLowerCase().includes(searchTerm.toLowerCase()) ||
                row.visiting_time.toLowerCase().includes(searchTerm.toLowerCase())
            );
        })
        : [];

    const getPro = async (e) => {
        setModalConfig({
            isOpen: true,
            type: 'premium',
            title: '🚀 Oops! This is a Premium Feature',
            message: 'Evaluate the features and select a bundle based on your needs.',
            onConfirm: () => {
                window.open('https://functiondeck.com/pricing/', '_blank');
                closeModal();
            },
            confirmText: 'Upgrade Now',
            declineText: 'Maybe Later'
        });
    }

    return (
        <div className="acb_traffic" id='acb_traffic'>
            {/* <div className="acb_author" id='acb_author' style={{ height: '500px' }}> */}
            <div className="acb_left">
                <h3 className="review-case-title">Visitor traffic list
                    {/* <a href="https://youtu.be/c-xsCV_2iBc" target="_blank"><PreviewIcon className='PlayCircleIcon' /></a> */}
                </h3>
                <br />

                {/* Search input */}
                <input
                    type="text"
                    placeholder="Search..."
                    value={searchTerm}
                    onChange={handleSearchChange}
                    className="wpx-search-leads"
                />


                {/* Bulk Delete button */}
                {selectedIds.length > 0 && (
                    <button className="wpx-buld-delete" onClick={handleBulkDeleteClick}>Bulk Delete</button>
                )}

                <div className="subs-list">
                    <Box sx={{ height: 400, width: '100%' }}>
                        <DataGrid
                            // rows={filteredRows}
                            // columns={userColumns.concat(actionColumns)}
                            rows={allConditionsMet ? filteredRows : dummyData}
                            columns={allConditionsMet ? userColumns.concat(actionColumns) : userDummyColumns}

                            initialState={{
                                pagination: {
                                    paginationModel: {
                                        pageSize: 5,
                                    },
                                },
                            }}
                            pageSizeOptions={[5]}
                            checkboxSelection
                            onSelectionModelChange={handleCheckboxSelection}

                        />
                    </Box>
                </div>

            </div>
            {!allConditionsMet && (
                <div className="inactive-overlay">
                    <div className="action-btns">
                        <div className="install-btn">
                            <h3 className="inactive-text">🔍 Discover Who's Visiting Your Website!</h3>
                            <h4 className="inactive-text">📈 Real-time visitor tracking & advanced analytics</h4>
                            <button className="install-action" onClick={getPro}>Get Pro</button>
                        </div>
                    </div>
                </div>
            )}
            {modalOpen && <><div className="wcs_popup_overlay"></div> <Modal setOpenModal={setModalOpen} /> </>}
            <NoticeModal
                isOpen={modalConfig.isOpen}
                onClose={closeModal}
                onConfirm={modalConfig.onConfirm}
                onDecline={closeModal}
                type={modalConfig.type}
                title={modalConfig.title}
                message={modalConfig.message}
                confirmText={modalConfig.confirmText}
                declineText={modalConfig.declineText}
                position={modalConfig.position || 'center'}
                autoClose={modalConfig.type === 'toast'}
                autoCloseTime={3000}
            />
        </div>
    )
}

export default Traffic
