"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 AccountBalanceOutlinedIcon from "@mui/icons-material/AccountBalanceOutlined";
import Textbox from "@components/Textbox/Textbox";
import { useAlert } from "@store/Alert.Store";
import { useNavigation } from "@hooks/goto";
import AccountMovementsIcon from "@mui/icons-material/CurrencyExchangeOutlined";
import {
    CLIENT_ACCOUNT_MOVEMENT_STATUS,
    CLIENT_ACCOUNT_MOVEMENT_TYPES,
    CLIENT_ACCOUNT_PAYMENT_METHODS,
    CreateClientAccountMovementParams,
} from "@core/Models/ClientAccountMovements.model";
import Button from "@core/app/components/Button/Button";
import { TextObjectModalContent } from "@core/Store/TextObjectModal.Store";
import { TextObjectFilterResult } from "@core/Models/TextObjectFilter.model";
import TextObjectFilterItem from "@core/app/components/TextObjectFilterItem/TextObjectFilterItem";
import TextObjectFilter from "@core/app/components/TextObjectFilter/TextObjectFilter";
import { addClientAccountMovement } from "../../../Client.Service";
import Switch from "@core/app/components/Switch/Switch";
import SecureByPlan, { SECURE_CONTENTS } from "@core/app/components/SecureByPlan/SecureByPlan";

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

export default function ClientAccountMovementAdd() {
    const data = useParams<UrlData>();
    const id = data.oid;
    const clientId = data.clientId;
    const type = data.type;
    const alert = useAlert();

    const SessionInfo = useSessionStore();
    const location = useLocationStore();
    const eventHandler = useEventHandlerStore();
    const { goTo } = useNavigation();

    const [amount, setAmount] = useState<string>("");
    const [description, setDescription] = useState<string>("");
    const [notification, setNotification] = useState<boolean>(false);

    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 + "/account",
            title: "Cuenta Corriente",
            icon: <AccountBalanceOutlinedIcon sx={{ mr: 0.5 }} fontSize="inherit" />,
        });

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

    const getActionName = () => {
        if (type === CLIENT_ACCOUNT_MOVEMENT_TYPES.DEPOSIT) {
            return "Depositar";
        }
        return "Retirar";
    };

    const [paymentMethodFilterContent] = useState<TextObjectModalContent>({
        header: (
            <div>
                <div
                    style={{
                        fontWeight: "700",
                        fontSize: "14px",
                        paddingTop: "7px",
                    }}
                >
                    Seleccionar Método de pago:
                </div>
                <p
                    style={{
                        fontWeight: "500",
                        fontSize: "13px",
                        paddingTop: "2px",
                    }}
                >
                    Ingrese el nombre del método de pago para buscarlo.
                </p>
            </div>
        ),
        bottom: <div>&nbsp;</div>,
        renderResult: (result: TextObjectFilterResult, index: number) => (
            <TextObjectFilterItem key={index} data={result} />
        ),
    });

    const [paymentMethhodFilterData, setPaymentMethodFilterData] = useState<
        TextObjectFilterResult[]
    >([]);
    const [paymentMethodId, setPaymentMethodId] = useState<string>("");

    useEffect(() => {
        loadPaymentMethods();
    }, []);

    const loadPaymentMethods = () => {
        const methods = [
            {
                id: CLIENT_ACCOUNT_PAYMENT_METHODS.CASH,
                name: "Efectivo",
                description: "Efectivo",
            },
            {
                id: CLIENT_ACCOUNT_PAYMENT_METHODS.BANK_TRANSFER,
                name: "Transferencia",
                description: "Transferencia",
            },
            {
                id: CLIENT_ACCOUNT_PAYMENT_METHODS.CREDIT_CARD,
                name: "Tarjeta de crédito",
                description: "Tarjeta de crédito",
            },
            {
                id: CLIENT_ACCOUNT_PAYMENT_METHODS.DEBIT_CARD,
                name: "Tarjeta de débito",
                description: "Tarjeta de débito",
            },
            {
                id: CLIENT_ACCOUNT_PAYMENT_METHODS.OTHER,
                name: "Otro",
                description: "Otro",
            },
        ];

        setPaymentMethodFilterData(
            methods.map((category) => ({
                id: category.id.toString(),
                name: category.name,
                description: category.description,
            }))
        );
    };

    const addMovement = () => {
        const data: CreateClientAccountMovementParams = {
            clientId: clientId,
            amount: Number(amount),
            paymentMethod: paymentMethodId as CLIENT_ACCOUNT_PAYMENT_METHODS,
            description: description,
            reference: "",
            type: type,
            status: CLIENT_ACCOUNT_MOVEMENT_STATUS.APPROVED,
            notification: notification,
            sessionUser: SessionInfo.userId,
        };

        eventHandler.setEventType(EVENT_TYPES.LOADING);

        addClientAccountMovement(data)
            .then(() => {
                alert.showSuccess("Movimiento agregado exitosamente");
                goTo("/admin/org/" + id + "/client/" + clientId + "/account");
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.CLEAR);
            });
    };

    return (
        <>
            <Location />

            <SecureByPlan content={SECURE_CONTENTS.PAYMENTS} companyId={id}>
                <>
                    <div style={{ marginTop: "15px" }}></div>

                    <TextObjectFilter
                        placeholder="Método de pago"
                        content={paymentMethodFilterContent}
                        data={paymentMethhodFilterData}
                        onChange={(id) => {
                            setPaymentMethodId(id);
                        }}
                    />

                    <Textbox
                        placeholder="Monto"
                        value={amount}
                        type="number"
                        width="100%"
                        onChange={(e) => setAmount(e.target.value)}
                    />

                    <Textbox
                        placeholder="Descripción"
                        value={description}
                        type="comments"
                        width="100%"
                        style={{ height: "100px" }}
                        limitSize={100}
                        onChange={(e) => setDescription(e.target.value)}
                    />

                    <div style={{ paddingTop: "10px", textAlign: "center" }}>
                        <Switch
                            checked={notification}
                            onChange={(checked) => {
                                setNotification(checked);
                            }}
                        />
                        <span
                            style={{
                                fontSize: "16px",
                                fontWeight: "600",
                                color: "var(--black)",
                            }}
                        >
                            Enviar notificación?
                        </span>
                    </div>

                    <Button
                        text={getActionName()}
                        onClick={() => {
                            addMovement();
                        }}
                        color="primary"
                        width="100%"
                        style={{ marginTop: "15px" }}
                    />

                    <div style={{ marginTop: "15px" }}></div>
                </>
            </SecureByPlan>
        </>
    );
}
