import Link from "next/link";
import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import LinkList from "../src/components/common/linklist/LinkList";
import { common } from "../src/helper/Common";
import svg from "../src/helper/svg";
import { setPageHeading } from "../src/redux/actions/commonAction";
import PlanAlert from "../src/components/common/PlanAlert";
import DatePicker from "react-datepicker";
import styles from '../styles/pages/Dashboard.module.css';
import { AlertMsg, getNameInitials } from "../src/helper/helper";
import RenameIcon from "../src/components/common/rename_icon/RenameIcon";
import linkstyles from '../src/components/common/linklist/LinkList.module.css';
import { Tooltip } from "@mui/material";

const Dashboard = () => {
    const preventTyping = (e) => {
        e.preventDefault();
    };
    const [data, setData] = useState(null)
    const [monthlyVisitor, setMonthlyVisitor] = useState(0)
    const [weeklyClicks, setWeeklyClicks] = useState(0)
    const [weeklyVisitor, setWeeklyVisitor] = useState(0)
    const [showAlertBar, setShowAlertBar] = useState(false);

    let dispatch = useDispatch();
    useEffect(() => {
        dispatch(setPageHeading({
            pageHeading: "PixaURL - Dashboard",
            title: "PixaURL - Dashboard",
        }));
    }, [dispatch]);
    const [linkCount, setLinkCount] = useState('0');

    const alertBarCloseHandler = () => {
        setShowAlertBar(false);
    }
    const getCurrentPlan = () => {
        common.getAPI({
            method: 'POST',
            url: 'user/getCurrentPlan',
            data: {}
        }, (resp) => {
            if (resp.status === "success") {
                if (resp.data?.adminPlanStatus) {
                    if (resp.data.isPlan && resp.data.isExpired) {
                        setShowAlertBar(true);
                    }
                }
            }
        })
    }
    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: 'user/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)
                }
            }
        );
    }
    useEffect(() => {
        getAnalytics()
    }, [limit, type, isApply])
    useEffect(() => {
        getCurrentPlan();
    }, [])
    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">
            <PlanAlert show={showAlertBar} onClose={alertBarCloseHandler} />
            <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>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="num">
                        {
                            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) => {
                    console.log(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 className={linkstyles.linklist_action}>
                            <Link href={'/edit/' + link._id}><a className={"pu_btn pu_btn_link " + styles.pu_btn}>Edit</a></Link>
                        </div>
                    </div>
                }
                )}
                {linkList.length == 0 ?
                    <div className="pu_noData">
                        <span>{svg.noData}</span>
                        <h3>No Records Found.</h3>
                    </div> : null
                }
            </div>
            <div className={styles.create_link_header}>
                <h3>Newly Created Links</h3>
                <Link href="/templates"><a className="pu_btn pu_btn_add">{svg.btn_add_icon} Create New Link</a></Link>
            </div>
            <LinkList setLinkCount={setLinkCount} />
        </div >
    );
}
export default Dashboard;
