import { useState } from "react";
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import LinkList from "../../src/components/admin/linklist/LinkList";
import { common } from "../../src/helper/Common";
import svg from "../../src/helper/svg";
import { setPageHeading } from "../../src/redux/actions/commonAction";
import DatePicker from "react-datepicker";
import linkstyles from '../../src/components/common/linklist/LinkList.module.css';
import { AlertMsg, getNameInitials } from "../../src/helper/helper";
import styles from '../../styles/pages/Dashboard.module.css';

import Link from "next/link";
import { Tooltip } from "@mui/material";
const Dashboard = () => {
    let dispatch = useDispatch();
    useEffect(() => {
        dispatch(setPageHeading({
            pageHeading: "Dashboard",
            title: "Dashboard",
        }));
    }, [dispatch]);
    const [monthlyVisitor, setMonthlyVisitor] = useState(0)
    const [weeklyClicks, setWeeklyClicks] = useState(0)
    const [weeklyVisitor, setWeeklyVisitor] = useState(0)
    const [linkCount, setLinkCount] = useState(0)
    const [startDate, setStartDate] = useState("");
    const [endDate, setEndDate] = useState("");
    const [limit, setLimit] = useState(5);
    const [type, setType] = useState("visits");
    const [isDatefilter, setIsDateFilter] = useState(false);
    const [isApply, setIsApply] = useState(false);
    const [linkList, setLinkList] = useState([]);
    const handleApply = () => {
        let start = new Date(startDate)
        let end = new Date(endDate)
        if (start > end) {
            AlertMsg('error', 'Oops!', 'End date must be greater then start date!');
        }
        setIsApply(!isApply)
    }
    const getAnalytics = async () => {
        let d = {
            limit,
            type
        }
        if (isDatefilter) {
            d.startDate = startDate;
            d.endDate = endDate
        }
        await common.getAPI(
            {
                method: "POST",
                url: 'admin/getDashboardAnalytics ',
                data: d
            },
            async (resp) => {
                if (resp.status === "success") {
                    setMonthlyVisitor(resp.data.totalMonthlyVisitor)
                    setWeeklyClicks(resp.data.totalWeeklyClicks)
                    setWeeklyVisitor(resp.data.totalWeeklyVisitor)
                    setLinkList(resp.data.topCampaigns)
                }
            }
        );
    }
    const preventTyping = (e) => {
        e.preventDefault();
    };
    useEffect(() => {
        getAnalytics()
    }, [limit, type, isApply])
    const filterOption = [
        { label: "Clicks", value: "clicks" },
        { label: "Visits", value: "visits" },
    ]
    const limitOption = [
        { label: "Limit 5", value: 5 },
        { label: "Limit 10", value: 10 },
    ]
    const copyURL = (url) => {
        navigator.clipboard.writeText(url);
        AlertMsg('success', 'Successfully!', 'Link Copied!');
    }

    return (
        <div className="pu_container">
            <div className="pu_pagetitle_wrapper">
                <h3>Overall Analytics</h3>
            </div>
            <div className="pu_analytics_white_box_list">
                <div className="pu_analytics_white_box">
                    <div className="pu_awb_icon">
                        {svg.analysis_click}
                    </div>
                    <div className="pu_awb_details">

                        <h3>{weeklyClicks}</h3>
                        <p>Weekly Clicks</p>
                    </div>
                </div>
                <div className="pu_analytics_white_box">
                    <div className="pu_awb_icon">
                        {svg.analysis_weekly_visitor}
                    </div>
                    <div className="pu_awb_details">
                        <h3>{weeklyVisitor}</h3>
                        <p>Weekly Visitor</p>
                    </div>
                </div>
                <div className="pu_analytics_white_box">
                    <div className="pu_awb_icon">
                        {svg.analysis_monthly_visitor}
                    </div>
                    <div className="pu_awb_details">
                        <h3>{monthlyVisitor}</h3>
                        <p>Monthly Visitor</p>
                    </div>
                </div>
                <div className="pu_analytics_white_box">
                    <div className="pu_awb_icon">
                        {svg.analysis_links}
                    </div>
                    <div className="pu_awb_details">
                        <h3>{linkCount}</h3>
                        <p>All Created Links</p>
                    </div>
                </div>
            </div>
            <div className={styles.create_link_header}>
                <h3>Top Links</h3>
                <div className="pu_analytics_filter">
                    <select required className='pu_custom_select' value={type} onChange={(e) => { setType(e.target.value) }} name="type" id="num">
                        {
                            filterOption.map((d, i) => {
                                return (
                                    <option key={i} value={d.value}>{d.label}</option>
                                )
                            })
                        }
                    </select>
                    <select required className='pu_custom_select' value={limit} onChange={(e) => { setLimit(e.target.value) }} name="type" id="num2">
                        {
                            limitOption.map((d, i) => {
                                return (
                                    <option key={i} value={d.value}>{d.label}</option>
                                )
                            })
                        }
                    </select>
                    <div className="">
                        <div className="pu_switch">

                            <input
                                type="checkbox"
                                id={'isDateFilter'}
                                defaultChecked={isDatefilter}
                                onChange={(e) => setIsDateFilter(prev => !prev)}
                            />
                            <label htmlFor={'isDateFilter'}>
                                <span className="pu_switch_text">Apply Date Filter</span>
                                <div className="pu_switch_icon"></div>
                            </label>
                        </div>
                    </div>
                    {
                        isDatefilter ? <>
                            <DatePicker
                                selected={startDate}
                                onChange={(date) => {
                                    const localDate = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
                                    const formattedDate = localDate.toISOString();
                                    setStartDate(formattedDate);
                                }}
                                dateFormat="dd/MM/yyyy"
                                placeholderText="Start date"
                                showYearDropdown
                                showMonthDropdown
                                dropdownMode="select"
                                onKeyDown={preventTyping}
                                onPaste={preventTyping}
                                className="pu_date_picker"
                            />
                            <DatePicker
                                selected={endDate}
                                onChange={(date) => {
                                    const localDate = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
                                    const formattedDate = localDate.toISOString();
                                    setEndDate(formattedDate);
                                }}
                                dateFormat="dd/MM/yyyy"
                                placeholderText="End date"
                                showYearDropdown
                                showMonthDropdown
                                dropdownMode="select"
                                onKeyDown={preventTyping}
                                onPaste={preventTyping}
                                className="pu_date_picker"
                            />
                            <button className="pu_btn" onClick={handleApply}>Apply</button>
                        </> : null
                    }
                </div>
            </div>
            <div className={linkstyles.linklist_wrapper}>
                {linkList.map((link) => {
                    return <div key={link._id} className={linkstyles.linklist_item}>
                        <div className={linkstyles.linklist_image}>
                            <span className={linkstyles.linklist_avatar_initials}>{getNameInitials(link.profile.name)}</span>
                        </div>
                        <div className={linkstyles.linklist_details}>
                            <h3>
                                {link.title}
                            </h3>
                            <p>
                                <a href={process.env.APP_URL + link.slug} target="_blank" rel="noreferrer">{process.env.APP_URL + link.slug}</a>
                                <Tooltip title="Copy URL" placement="top" arrow>
                                    <span className={styles.linklist_copylink} onClick={() => copyURL(process.env.APP_URL + link.slug)}>{svg.icon_duplicate}</span>
                                </Tooltip>
                            </p>
                            <div className={linkstyles.linklist_analytics}>
                                {
                                    type == "visits" ?
                                        <div className={linkstyles.linklist_analytics_item}>
                                            {svg.link_visitor} Visitor <span>({link.total ? link.total : 0})</span>
                                        </div> :
                                        <div className={linkstyles.linklist_analytics_item}>
                                            {svg.link_click} Clicks <span>({link.total ? link.total : 0})</span>
                                        </div>
                                }
                            </div>
                        </div>
                        <div className={linkstyles.link_action_toggle} onClick={() => actionToggle(link._id)}>
                            <span></span>
                            <span></span>
                            <span></span>
                        </div>
                    </div>
                }
                )}
                {linkList.length == 0 ?
                    <div className="pu_noData">
                        <span>{svg.noData}</span>
                        <h3>No Records Found.</h3>
                    </div> : null
                }
            </div>
            <div className="pu_pagetitle_wrapper">
                <h3>All Links ({linkCount})</h3>
            </div>
            <LinkList setLinkCount={setLinkCount} />

        </div>
    );
}
export default Dashboard;