"use client";
import React, { useState, useRef, useEffect } from "react";
import dayjs, { Dayjs } from "dayjs";
import { motion, AnimatePresence } from "motion/react";
import CalendarMonthIcon from "@mui/icons-material/CalendarMonth";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";

export interface TextRangeDateModernProps {
    label: string;
    dateFrom: Dayjs;
    dateTo: Dayjs;
    style?: React.CSSProperties;
    setDateFrom: (date: Dayjs) => void;
    setDateTo: (date: Dayjs) => void;
}

enum TEXT_RANGE_DATE_OPTIONS {
    TODAY = "Hoy",
    THIS_WEEK = "Esta Semana",
    THIS_MONTH = "Este Mes",
    THIS_YEAR = "Este Año",
    LAST_7_DAYS = "Ultimos 7 Días",
    LAST_30_DAYS = "Ultimos 30 Días",
    LAST_60_DAYS = "Ultimos 60 Días",
    LAST_90_DAYS = "Ultimos 90 Días",
    LAST_YEAR = "Ultimos 12 Meses",
}

const options = [
    { label: TEXT_RANGE_DATE_OPTIONS.TODAY, type: "current" },
    { label: TEXT_RANGE_DATE_OPTIONS.THIS_WEEK, type: "current" },
    { label: TEXT_RANGE_DATE_OPTIONS.THIS_MONTH, type: "current" },
    { label: TEXT_RANGE_DATE_OPTIONS.THIS_YEAR, type: "current" },
    { type: "divider" },
    { label: TEXT_RANGE_DATE_OPTIONS.LAST_7_DAYS, type: "past" },
    { label: TEXT_RANGE_DATE_OPTIONS.LAST_30_DAYS, type: "past" },
    { label: TEXT_RANGE_DATE_OPTIONS.LAST_60_DAYS, type: "past" },
    { label: TEXT_RANGE_DATE_OPTIONS.LAST_90_DAYS, type: "past" },
    { label: TEXT_RANGE_DATE_OPTIONS.LAST_YEAR, type: "past" },
];

export default function TextRangeDateModern(props: TextRangeDateModernProps): React.ReactElement {
    const { setDateFrom, setDateTo, style, label } = props;
    const [selectedOption, setSelectedOption] = useState<string>(TEXT_RANGE_DATE_OPTIONS.TODAY);
    const [open, setOpen] = useState(false);
    const menuRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
                setOpen(false);
            }
        };
        document.addEventListener("mousedown", handleClickOutside);
        return () => document.removeEventListener("mousedown", handleClickOutside);
    }, []);

    const handleSelect = (optionLabel: string) => {
        if (optionLabel === TEXT_RANGE_DATE_OPTIONS.TODAY) {
            setDateFrom(dayjs().startOf("day"));
            setDateTo(dayjs().endOf("day"));
        } else if (optionLabel === TEXT_RANGE_DATE_OPTIONS.THIS_WEEK) {
            setDateFrom(dayjs().startOf("week"));
            setDateTo(dayjs().endOf("week"));
        } else if (optionLabel === TEXT_RANGE_DATE_OPTIONS.THIS_MONTH) {
            setDateFrom(dayjs().startOf("month"));
            setDateTo(dayjs().endOf("month"));
        } else if (optionLabel === TEXT_RANGE_DATE_OPTIONS.THIS_YEAR) {
            setDateFrom(dayjs().startOf("year"));
            setDateTo(dayjs().endOf("year"));
        } else if (optionLabel === TEXT_RANGE_DATE_OPTIONS.LAST_7_DAYS) {
            setDateFrom(dayjs().subtract(7, "day").startOf("day"));
            setDateTo(dayjs().endOf("day"));
        } else if (optionLabel === TEXT_RANGE_DATE_OPTIONS.LAST_30_DAYS) {
            setDateFrom(dayjs().subtract(30, "day").startOf("day"));
            setDateTo(dayjs().endOf("day"));
        } else if (optionLabel === TEXT_RANGE_DATE_OPTIONS.LAST_60_DAYS) {
            setDateFrom(dayjs().subtract(60, "day").startOf("day"));
            setDateTo(dayjs().endOf("day"));
        } else if (optionLabel === TEXT_RANGE_DATE_OPTIONS.LAST_90_DAYS) {
            setDateFrom(dayjs().subtract(90, "day").startOf("day"));
            setDateTo(dayjs().endOf("day"));
        } else if (optionLabel === TEXT_RANGE_DATE_OPTIONS.LAST_YEAR) {
            setDateFrom(dayjs().subtract(1, "year").startOf("day"));
            setDateTo(dayjs().endOf("day"));
        }

        setSelectedOption(optionLabel);
        setOpen(false);
    };

    return (
        <div style={{ position: "relative", width: "100%", ...style }} ref={menuRef}>
            <motion.div
                whileHover={{ scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
                onClick={() => setOpen(!open)}
                style={{
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "space-between",
                    padding: "12px 20px",
                    background: open ? "#e0e0e0" : "#f1f3f5",
                    borderRadius: "15px",
                    cursor: "pointer",
                    boxShadow: open ? "inset 0 2px 4px rgba(0,0,0,0.05)" : "0 2px 8px rgba(0,0,0,0.05)",
                    transition: "background 0.3s ease",
                    color: "#333",
                    fontWeight: "bold",
                }}
            >
                <div style={{ display: "flex", alignItems: "center", gap: "10px" }}>
                    <CalendarMonthIcon sx={{ color: "var(--purple)", opacity: 0.8 }} />
                    <span style={{ fontSize: "15px" }}>{selectedOption}</span>
                </div>
                <motion.div animate={{ rotate: open ? 180 : 0 }}>
                    <KeyboardArrowDownIcon sx={{ color: "#888" }} />
                </motion.div>
            </motion.div>

            <AnimatePresence>
                {open && (
                    <motion.div
                        initial={{ opacity: 0, y: -10, scale: 0.95 }}
                        animate={{ opacity: 1, y: 0, scale: 1 }}
                        exit={{ opacity: 0, y: -10, scale: 0.95 }}
                        transition={{ duration: 0.2 }}
                        style={{
                            position: "absolute",
                            top: "calc(100% + 10px)",
                            left: 0,
                            right: 0,
                            background: "rgba(255, 255, 255, 0.9)",
                            backdropFilter: "blur(10px)",
                            WebkitBackdropFilter: "blur(10px)",
                            borderRadius: "15px",
                            boxShadow: "0 10px 40px rgba(0,0,0,0.15)",
                            zIndex: 1000,
                            overflow: "hidden",
                            border: "1px solid rgba(255,255,255,0.4)"
                        }}
                    >
                        <div style={{ padding: "15px", maxHeight: "400px", overflowY: "auto", display: "flex", flexDirection: "column", gap: "15px" }}>
                            <div>
                                <div style={{ fontSize: "12px", fontWeight: "bold", color: "#aaa", textTransform: "uppercase", letterSpacing: "1px", marginBottom: "8px", marginLeft: "5px" }}>Actual</div>
                                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "8px" }}>
                                    {options.filter(o => o.type === "current").map((opt, index) => {
                                        const isSelected = selectedOption === opt.label;
                                        return (
                                            <div
                                                key={index}
                                                onClick={() => handleSelect(opt.label!)}
                                                style={{
                                                    padding: "10px",
                                                    cursor: "pointer",
                                                    background: isSelected ? "rgba(108, 92, 231, 0.15)" : "#f4f5f7",
                                                    color: isSelected ? "var(--purple)" : "#444",
                                                    fontWeight: isSelected ? "bold" : "600",
                                                    fontSize: "13px",
                                                    borderRadius: "10px",
                                                    textAlign: "center",
                                                    transition: "all 0.2s ease",
                                                    boxShadow: "none"
                                                }}
                                                onMouseEnter={(e) => {
                                                    if (!isSelected) (e.currentTarget as HTMLElement).style.background = "#e9ecef";
                                                }}
                                                onMouseLeave={(e) => {
                                                    if (!isSelected) (e.currentTarget as HTMLElement).style.background = "#f4f5f7";
                                                }}
                                            >
                                                {opt.label}
                                            </div>
                                        );
                                    })}
                                </div>
                            </div>
                            
                            <div>
                                <div style={{ fontSize: "12px", fontWeight: "bold", color: "#aaa", textTransform: "uppercase", letterSpacing: "1px", marginBottom: "8px", marginLeft: "5px" }}>Histórico</div>
                                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "8px" }}>
                                    {options.filter(o => o.type === "past").map((opt, index) => {
                                        const isSelected = selectedOption === opt.label;
                                        return (
                                            <div
                                                key={index}
                                                onClick={() => handleSelect(opt.label!)}
                                                style={{
                                                    padding: "10px",
                                                    cursor: "pointer",
                                                    background: isSelected ? "rgba(108, 92, 231, 0.15)" : "#f4f5f7",
                                                    color: isSelected ? "var(--purple)" : "#444",
                                                    fontWeight: isSelected ? "bold" : "600",
                                                    fontSize: "13px",
                                                    borderRadius: "10px",
                                                    textAlign: "center",
                                                    transition: "all 0.2s ease",
                                                    boxShadow: "none"
                                                }}
                                                onMouseEnter={(e) => {
                                                    if (!isSelected) (e.currentTarget as HTMLElement).style.background = "#e9ecef";
                                                }}
                                                onMouseLeave={(e) => {
                                                    if (!isSelected) (e.currentTarget as HTMLElement).style.background = "#f4f5f7";
                                                }}
                                            >
                                                {opt.label}
                                            </div>
                                        );
                                    })}
                                </div>
                            </div>
                        </div>
                    </motion.div>
                )}
            </AnimatePresence>
        </div>
    );
}
