"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_TYPES,
    CLIENT_ACCOUNT_PAYMENT_METHODS,
} 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 { CreateCashFlowParams } from "@core/Models/CashFlow.model";
import dayjs from "dayjs";
import { createCashFlow } from "../../Cash.Service";
import { PAYMENT_PROCCESS_DATE } from "@core/Models/Payments.model";
import SecureByPlan, { SECURE_CONTENTS } from "@core/app/components/SecureByPlan/SecureByPlan";

type UrlData = {
    id: string;
    type: CLIENT_ACCOUNT_MOVEMENT_TYPES;
};

export default function CashFlowMovementAdd() {
    const data = useParams<UrlData>();
    const id = data.id;
    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>("");

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

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

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

        location.add({
            url: "/admin/org/profile/" + id + "/cash",
            title: "Caja",
            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 tipo de movieminto 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 currentDate = dayjs();
        const currentYeath = currentDate.year();
        const currentMonth = currentDate.month();
        const data: CreateCashFlowParams = {
            companyId: id,
            amount: Number(amount),
            month: currentMonth,
            year: currentYeath,
            paymentMethod: paymentMethodId as CLIENT_ACCOUNT_PAYMENT_METHODS,
            description: description,
            reference: "",
            type: type,
            proccessDate: PAYMENT_PROCCESS_DATE.NOW,
            sessionUser: SessionInfo.userId,
        };

        eventHandler.setEventType(EVENT_TYPES.LOADING);

        createCashFlow(data)
            .then(() => {
                alert.showSuccess("Movimiento agregado exitosamente");
                goTo("/admin/org/profile/" + id + "/cash");
            })
            .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="Tipo de movimiento"
                        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)}
                    />

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

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