"use client";
import { useState, useEffect } from "react";
import { useParams } from "next/navigation";
import { useSessionStore } from "@store/Sesion.Store";
import Location from "@components/Location/Location";
import { useLocationStore } from "@store/Location.Store";
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
import ClientsIcon from "@mui/icons-material/AccountBoxOutlined";
import AccountBalanceOutlinedIcon from "@mui/icons-material/AccountBalanceOutlined";
import { useAlert } from "@store/Alert.Store";
import { useNavigation } from "@hooks/goto";
import { getClientAccountView } from "../Client.Service";
import { IconButton } from "@mui/material";
import RetirarIcon from "@mui/icons-material/CallMadeOutlined";
import DepositarIcon from "@mui/icons-material/SouthWestOutlined";
import MovimientosIcon from "@mui/icons-material/Reorder";
import UnfoldLessIcon from "@mui/icons-material/UnfoldLess";
import UnfoldMoreIcon from "@mui/icons-material/UnfoldMore";
import { ClientAccountView } from "@core/Models/ClientAccounts.model";
import { formatPrice } from "@core/app/helpers/Numbers";
import dayjs from "dayjs";
import { CLIENT_ACCOUNT_MOVEMENT_TYPES } from "@core/Models/ClientAccountMovements.model";
import { getPaymentIcon } from "@core/app/components/PaymentIcons/PaymentIcons";
import SecureByPlan, { SECURE_CONTENTS } from "@core/app/components/SecureByPlan/SecureByPlan";
import { motion } from "motion/react";

type UrlData = {
    oid: string;
    clientId: string;
};

export default function ClientAccount() {
    const data = useParams<UrlData>();
    const id = data.oid;
    const clientId = data.clientId;
    const alert = useAlert();
    const SessionInfo = useSessionStore();
    const location = useLocationStore();
    const eventHandler = useEventHandlerStore();
    const { goTo } = useNavigation();

    const [view, setView] = useState<ClientAccountView | null>(null);
    const [isScrolled, setIsScrolled] = useState(false);
    const [forceMinimized, setForceMinimized] = useState(false);
    
    const isMinimized = forceMinimized || isScrolled;

    useEffect(() => {
        const handleScroll = (e: Event) => {
            const target = e.target as HTMLElement;
            if (target.scrollTop > 20) {
                setIsScrolled(true);
            } else {
                setIsScrolled(false);
            }
        };
        const container = document.querySelector('[class*="clientProfileOptionsContainer"]');
        if (container) {
            container.addEventListener("scroll", handleScroll);
            return () => container.removeEventListener("scroll", handleScroll);
        }
    }, []);

    useEffect(() => {
        eventHandler.setEventType(EVENT_TYPES.SLEEP);
    }, []);

    useEffect(() => {
        location.clear();

        location.add({
            url: "/admin/org/profile/" + id + "/clients",
            title: "Clientes",
            icon: null,
        });

        location.add({
            url: "/admin/org/" + id + "/client/" + clientId + "/profile",
            title: "Perfil",
            icon: <ClientsIcon sx={{ mr: 0.5 }} fontSize="inherit" />,
        });

        location.add({
            url: "",
            title: "Cuenta Corriente",
            icon: <AccountBalanceOutlinedIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });
    }, []);

    useEffect(() => {
        cargarDatos();
    }, [SessionInfo.userId, clientId]);

    const cargarDatos = async () => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);

        if (!SessionInfo.userId) {
            return;
        }

        if (!clientId) {
            return;
        }

        getClientAccountView({
            clientId: clientId,
            sessionUser: SessionInfo.userId,
        })
            .then((data) => {
                setView(data);
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.CLEAR);
            });
    };

    const add = (type: CLIENT_ACCOUNT_MOVEMENT_TYPES) => {
        goTo("/admin/org/" + id + "/client/" + clientId + "/account/add/" + type);
    };

    return (
        <>
            <Location />

            <SecureByPlan content={SECURE_CONTENTS.PAYMENTS} companyId={id}>
                <div style={{ maxWidth: "800px", margin: "0 auto", paddingBottom: "100px" }}>
                    
                    {/* Top Status Card */}
                    <div style={{ position: "sticky", top: "70px", zIndex: 100, display: "flex", flexDirection: "column", background: "white", paddingBottom: "20px", paddingTop: "5px", margin: "0 -10px 30px -10px", paddingLeft: "10px", paddingRight: "10px" }}>
                    {view && (
                        <motion.div
                            layout
                            initial={{ opacity: 0, y: -20 }}
                            animate={{ 
                                opacity: 1, 
                                y: 0,
                                padding: isMinimized ? "25px 50px" : "40px 20px",
                                borderRadius: isMinimized ? "15px" : "20px"
                            }}
                            style={{
                                display: "flex",
                                flexDirection: isMinimized ? "row" : "column",
                                alignItems: "center",
                                justifyContent: isMinimized ? "space-between" : "center",
                                background: view.amount >= 0 
                                    ? "linear-gradient(135deg, #1d976c 0%, #93f9b9 100%)" 
                                    : "linear-gradient(135deg, #cb2d3e 0%, #ef473a 100%)",
                                color: "white",
                                boxShadow: isMinimized ? "0 4px 15px rgba(0,0,0,0.3)" : "0 10px 30px rgba(0,0,0,0.15)",
                                position: "relative",
                                overflow: "hidden",
                                transition: "box-shadow 0.3s ease"
                            }}
                        >
                            <IconButton
                                onClick={() => setForceMinimized(!forceMinimized)}
                                style={{ position: "absolute", top: "10px", left: "10px", color: "rgba(255,255,255,0.7)", zIndex: 10 }}
                                size="small"
                                title={forceMinimized ? "Maximizar" : "Minimizar"}
                            >
                                {forceMinimized ? <UnfoldMoreIcon /> : <UnfoldLessIcon />}
                            </IconButton>
                            
                            {/* Decorative background circles */}
                            <div style={{ position: "absolute", top: "-50px", right: "-50px", width: "150px", height: "150px", borderRadius: "50%", background: "rgba(255,255,255,0.1)" }}></div>
                            <div style={{ position: "absolute", bottom: "-30px", left: "-30px", width: "100px", height: "100px", borderRadius: "50%", background: "rgba(255,255,255,0.1)" }}></div>

                            <motion.div 
                                animate={{ 
                                    fontSize: isMinimized ? "14px" : "16px",
                                    marginBottom: isMinimized ? "0px" : "0px",
                                    marginLeft: isMinimized ? "30px" : "0px"
                                }}
                                style={{ fontWeight: "bold", opacity: 0.9, textTransform: "uppercase", letterSpacing: "1px" }}
                            >
                                Saldo Actual
                            </motion.div>
                            <motion.div 
                                animate={{ 
                                    fontSize: isMinimized ? "24px" : "56px",
                                    margin: isMinimized ? "0px" : "10px 0 30px 0"
                                }}
                                style={{ fontWeight: "900", textShadow: "0 2px 10px rgba(0,0,0,0.1)" }}
                            >
                                {formatPrice(view.amount)}
                            </motion.div>
                            
                            
                            {!isMinimized && (
                                <motion.div 
                                    initial={{ opacity: 0 }}
                                    animate={{ opacity: 1 }}
                                    exit={{ opacity: 0 }}
                                    style={{ display: "flex", gap: "15px", flexDirection: "row", zIndex: 1 }}
                                >
                                    <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
                                        <IconButton
                                            sx={{
                                                backgroundColor: "rgba(255,255,255,0.2)",
                                                color: "white",
                                                display: "flex",
                                                alignItems: "center",
                                                flexDirection: "column",
                                                width: "110px",
                                                height: "90px",
                                                borderRadius: "15px",
                                                "&:hover": { backgroundColor: "rgba(255,255,255,0.3)" }
                                            }}
                                            onClick={() => add(CLIENT_ACCOUNT_MOVEMENT_TYPES.DEPOSIT)}
                                        >
                                            <DepositarIcon sx={{ fontSize: "32px", marginBottom: "5px" }} />
                                            <span style={{ fontSize: "14px", fontWeight: "bold" }}>Ingresar</span>
                                        </IconButton>
                                    </motion.div>

                                    <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
                                        <IconButton
                                            sx={{
                                                backgroundColor: "rgba(255,255,255,0.2)",
                                                color: "white",
                                                display: "flex",
                                                alignItems: "center",
                                                flexDirection: "column",
                                                width: "110px",
                                                height: "90px",
                                                borderRadius: "15px",
                                                "&:hover": { backgroundColor: "rgba(255,255,255,0.3)" }
                                            }}
                                            onClick={() => add(CLIENT_ACCOUNT_MOVEMENT_TYPES.WITHDRAWAL)}
                                        >
                                            <RetirarIcon sx={{ fontSize: "32px", marginBottom: "5px" }} />
                                            <span style={{ fontSize: "14px", fontWeight: "bold" }}>Retirar</span>
                                        </IconButton>
                                    </motion.div>

                                    <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
                                        <IconButton
                                            sx={{
                                                backgroundColor: "white",
                                                color: view.amount >= 0 ? "#1d976c" : "#cb2d3e",
                                                display: "flex",
                                                alignItems: "center",
                                                flexDirection: "column",
                                                width: "110px",
                                                height: "90px",
                                                borderRadius: "15px",
                                                boxShadow: "0 4px 15px rgba(0,0,0,0.1)",
                                                "&:hover": { backgroundColor: "#f8f9fa" }
                                            }}
                                            onClick={() => goTo("/admin/org/" + id + "/client/" + clientId + "/account/movements")}
                                        >
                                            <MovimientosIcon sx={{ fontSize: "32px", marginBottom: "5px" }} />
                                            <span style={{ fontSize: "14px", fontWeight: "bold" }}>Historial</span>
                                        </IconButton>
                                    </motion.div>
                                </motion.div>
                            )}
                        </motion.div>
                    )}
                    </div>
                    
                    <div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
                        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "15px", padding: "0 10px" }}>
                            <div style={{ fontSize: "20px", fontWeight: "bold", color: "var(--black-light)" }}>
                                Últimos Movimientos
                            </div>
                            <div 
                                style={{ fontSize: "14px", color: "var(--wine-dark)", cursor: "pointer", fontWeight: "bold" }}
                                onClick={() => goTo("/admin/org/" + id + "/client/" + clientId + "/account/movements")}
                            >
                                Ver todos
                            </div>
                        </div>

                        {view && view.lastMovements.length > 0 ? (
                            <div style={{ display: "flex", flexDirection: "column", gap: "12px" }}>
                                {view.lastMovements.map((movement, index) => (
                                    <motion.div
                                        initial={{ opacity: 0, x: -20 }}
                                        animate={{ opacity: 1, x: 0 }}
                                        transition={{ delay: index * 0.05 }}
                                        key={"movement" + index}
                                        style={{
                                            display: "flex",
                                            flexDirection: "row",
                                            alignItems: "center",
                                            justifyContent: "space-between",
                                            backgroundColor: "#fff",
                                            borderRadius: "15px",
                                            padding: "15px 20px",
                                            boxShadow: "0 2px 8px rgba(0,0,0,0.05)",
                                        }}
                                    >
                                        <div style={{ display: "flex", alignItems: "center", gap: "15px" }}>
                                            <div style={{ 
                                                width: "45px", 
                                                height: "45px", 
                                                borderRadius: "12px", 
                                                backgroundColor: movement.amount > 0 ? "rgba(40, 167, 69, 0.1)" : "rgba(220, 53, 69, 0.1)", 
                                                display: "flex", 
                                                alignItems: "center", 
                                                justifyContent: "center",
                                                color: movement.amount > 0 ? "#28a745" : "#dc3545"
                                            }}>
                                                {getPaymentIcon(movement.paymentMethod)}
                                            </div>
                                            <div>
                                                <div style={{ fontSize: "16px", fontWeight: "bold", color: "#333", marginBottom: "3px" }}>
                                                    {movement.description}
                                                </div>
                                                <div style={{ fontSize: "13px", color: "#888" }}>
                                                    {dayjs(movement.createdAt).format("DD MMMM YYYY • HH:mm")}
                                                </div>
                                            </div>
                                        </div>
                                        <div style={{
                                            fontSize: "18px",
                                            fontWeight: "900",
                                            color: movement.amount > 0 ? "#28a745" : "#dc3545",
                                        }}>
                                            {movement.amount > 0 ? "+" : ""}{formatPrice(movement.amount)}
                                        </div>
                                    </motion.div>
                                ))}
                            </div>
                        ) : (
                            <div style={{ textAlign: "center", padding: "40px", backgroundColor: "#fff", borderRadius: "15px", color: "#888", border: "1px dashed #ccc" }}>
                                <AccountBalanceOutlinedIcon sx={{ fontSize: "48px", color: "#ddd", marginBottom: "10px" }} />
                                <div style={{ fontSize: "16px", fontWeight: "bold", color: "#666" }}>
                                    Aún no hay movimientos
                                </div>
                                <div style={{ fontSize: "14px" }}>
                                    Ingresa dinero para ver tu historial aquí.
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </SecureByPlan>
        </>
    );
}
