"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_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 {
    CreatePaymentParams,
    PAYMENT_PROCCESS_DATE,
    paymentMethods,
} from "@core/Models/Payments.model";
import { AppointmentEventByClient } from "@core/Models/Appointments.model";
import { getAppointmentEvent } from "../../../Appointments.Service";
import AppointmentEventHeader from "@core/app/components/AppointmentEventHeader/AppointmentEventHeader";
import { createPayment } from "../AppointmentPayment.Service";

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

export default function ClientAccountMovementAdd() {
    const data = useParams<UrlData>();
    const id = data.oid;
    const clientId = data.clientId;
    const appointmentId = data.appointmentId;
    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 [appointment, setAppointment] = useState<AppointmentEventByClient | null>(null);

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

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

        location.add({
            url: "/admin/org/" + id + "/client/" + clientId + "/appointments/" + appointmentId,
            title: "Detalles del turno",
            icon: null,
        });

        location.add({
            url:
                "/admin/org/" +
                id +
                "/client/" +
                clientId +
                "/appointments/" +
                appointmentId +
                "/payments",
            title: "Pagos",
            icon: <AccountBalanceOutlinedIcon sx={{ mr: 0.5 }} fontSize="inherit" />,
        });

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

        loadAppointmentEvent();
    }, []);

    const loadAppointmentEvent = () => {
        if (!SessionInfo.userId) {
            return;
        }

        if (!appointmentId) {
            return;
        }

        eventHandler.setEventType(EVENT_TYPES.LOADING);

        getAppointmentEvent({
            appointmentId: appointmentId.toString(),
            sessionUser: SessionInfo.userId,
        })
            .then((data) => {
                setAppointment(data);
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.NEED_ADD);
            });
    };

    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<CLIENT_ACCOUNT_PAYMENT_METHODS>(
        CLIENT_ACCOUNT_PAYMENT_METHODS.CASH
    );

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

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

    const addPayment = () => {
        const data: CreatePaymentParams = {
            appointmentId: appointmentId,
            method: paymentMethodId,
            amount: Number(amount),
            description: description,
            status: CLIENT_ACCOUNT_MOVEMENT_STATUS.APPROVED,
            proccessDate: PAYMENT_PROCCESS_DATE.NOW,
            sessionUser: SessionInfo.userId,
        };

        eventHandler.setEventType(EVENT_TYPES.LOADING);

        createPayment(data)
            .then(() => {
                alert.showSuccess("Pago creado correctamente");
                goTo(
                    "/admin/org/" +
                        id +
                        "/client/" +
                        clientId +
                        "/appointments/" +
                        appointmentId +
                        "/payments"
                );
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.CLEAR);
            });
    };

    return (
        <>
            <Location />

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

            {appointment && (
                <div style={{ marginTop: "20px" }}>
                    <AppointmentEventHeader appointment={appointment} showPaymentInfo />
                </div>
            )}

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

            <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="Agregar"
                onClick={() => {
                    addPayment();
                }}
                color="primary"
                width="100%"
                style={{ marginTop: "15px" }}
            />

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