"use client";
import { useParams } from "next/navigation";
import Location from "@components/Location/Location";
import { useLocationStore } from "@store/Location.Store";
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
import StorefrontOutlinedIcon from "@mui/icons-material/StorefrontOutlined";
import { useState, useEffect } from "react";
import { loadServicesByCompany } from "./Services.Service";

import { CompanyServiceView } from "@core/Models/Service.model";
import style from "./service.module.css";
import { useNavigation } from "@hooks/goto";
import { useAlert } from "@core/Store/Alert.Store";
import currency from "currency.js";
import { getServiceImage } from "@core/helpers/getServiceImage";

import ShareOutlinedIcon from "@mui/icons-material/ShareOutlined";
import Dialog from "@mui/material/Dialog";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import CloseIcon from "@mui/icons-material/Close";
import IconButton from "@mui/material/IconButton";
import {
    FacebookShareButton,
    WhatsappShareButton,
    TwitterShareButton,
    EmailShareButton,
    TelegramShareButton,
    FacebookIcon,
    WhatsappIcon as WhatsAppShareIcon,
    TwitterIcon,
    EmailIcon,
    TelegramIcon
} from "react-share";

type UrlData = {
    id: string;
};

export default function Org() {
    const urlData = useParams<UrlData>();
    const id = urlData.id;
    const location = useLocationStore();

    const eventHandler = useEventHandlerStore();
    const alert = useAlert();
    const [myServices, setMyServices] = useState<CompanyServiceView[]>([]);
    const { goTo } = useNavigation();

    const [shareService, setShareService] = useState<CompanyServiceView | null>(null);

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

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

        location.add({
            url: "/admin/org",
            title: "Mis organizaciones",
            icon: null,
        });

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

        location.add({
            url: "/admin/org",
            title: "Mis servicios",
            icon: <StorefrontOutlinedIcon sx={{ fontSize: "32px", mr: "10px" }} />,
        });
    }, []);

    useEffect(() => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);
        loadServicesByCompany(id)
            .then((services) => {
                setMyServices(services);
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                eventHandler.setEventType(EVENT_TYPES.NEED_ADD);
            });
    }, []);

    const handleServiceClick = (serviceId: string) => {
        eventHandler.setEventType(EVENT_TYPES.SLEEP);
        goTo("/admin/org/profile/" + id + "/services/" + serviceId);
    };

    const formatPrice = (price: number) => {
        return currency(price, { symbol: "$", separator: ".", decimal: "," }).format();
    };

    const ServiceItem = ({ data }: { data: CompanyServiceView }) => {
        return (
            <div
                className={style.serviceCard}
                style={{
                    borderLeft: `6px solid ${data.color}`
                }}
                onClick={() => handleServiceClick(data.id)}
            >
                <div className={style.imageContainer}>
                    <img src={getServiceImage(data.image)} alt={data.name} />
                </div>
                <div className={style.serviceInfo}>
                    <h1>{data.name}</h1>
                    <p>{data.description}</p>
                </div>
                <div className={style.serviceActions}>
                    <span className={style.servicePrice}>{formatPrice(data.price)}</span>
                    <IconButton 
                        className={style.shareButton}
                        sx={{ position: "absolute", top: "15px", right: "15px" }}
                        onClick={(e) => {
                            e.stopPropagation();
                            setShareService(data);
                        }}
                        size="small"
                        title="Compartir servicio"
                    >
                        <ShareOutlinedIcon fontSize="small" />
                    </IconButton>
                </div>
            </div>
        );
    };

    return (
        <>
            <Location />
            <div className={style.servicesContainer}>
                {myServices.map((service) => (
                    <ServiceItem key={service.id} data={service} />
                ))}
            </div>
            <div style={{ marginBottom: "20px" }}>&nbsp;</div>

            {shareService && (
                <Dialog open={!!shareService} onClose={() => setShareService(null)} maxWidth="sm" fullWidth>
                    <DialogTitle sx={{ m: 0, p: 2, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                        <span style={{ fontWeight: "bold" }}>Compartir Servicio</span>
                        <IconButton
                            aria-label="close"
                            onClick={() => setShareService(null)}
                            sx={{ color: (theme) => theme.palette.grey[500] }}
                        >
                            <CloseIcon />
                        </IconButton>
                    </DialogTitle>
                    <DialogContent dividers>
                        <div style={{ textAlign: "center", marginBottom: "30px", fontSize: "16px", color: "var(--black-light)" }}>
                            Compartí tu servicio <strong>{shareService.name}</strong> para que tus clientes puedan reservarlo directamente.
                        </div>
                        <div style={{ display: "flex", justifyContent: "center", flexDirection: "row", alignItems: "center", gap: "20px", paddingBottom: "20px" }}>
                            <WhatsappShareButton title={"Reserva este servicio: " + shareService.name} separator=":: " url={window.location.origin + "/landing/service/" + shareService.id}>
                                <WhatsAppShareIcon size={54} round />
                            </WhatsappShareButton>
                            <FacebookShareButton title={"Reserva este servicio: " + shareService.name} url={window.location.origin + "/landing/service/" + shareService.id}>
                                <FacebookIcon size={54} round />
                            </FacebookShareButton>
                            <EmailShareButton title={"Reserva este servicio: " + shareService.name} separator=":: " url={window.location.origin + "/landing/service/" + shareService.id}>
                                <EmailIcon size={54} round />
                            </EmailShareButton>
                            <TelegramShareButton title={"Reserva este servicio: " + shareService.name} url={window.location.origin + "/landing/service/" + shareService.id}>
                                <TelegramIcon size={54} round />
                            </TelegramShareButton>
                            <TwitterShareButton title={"Reserva este servicio: " + shareService.name} url={window.location.origin + "/landing/service/" + shareService.id}>
                                <TwitterIcon size={54} round />
                            </TwitterShareButton>
                        </div>
                    </DialogContent>
                </Dialog>
            )}
        </>
    );
}
