"use client";
import Location from "@components/Location/Location";
import { useLocationStore } from "@store/Location.Store";
import { useEventHandlerStore, EVENT_TYPES } from "@store/EventHandler.Store";
import AutoAwesomeIcon from "@mui/icons-material/AutoAwesome";
import RocketLaunchIcon from "@mui/icons-material/RocketLaunch";
import StorefrontOutlinedIcon from "@mui/icons-material/StorefrontOutlined";
import { useState, useEffect } from "react";
import { loadOrganizationsByUser } from "./Org.Service";
import { useSessionStore } from "@store/Sesion.Store";
import { MyOranizationsView } from "@core/Models/Company.model";
import style from "./org.module.css";
import Button from "@components/Button/Button";
import { useNavigation } from "@hooks/goto";
import { useAlert } from "@core/Store/Alert.Store";
import { blurElementsOnLoad } from "@core/helpers/blur";
import { useBottomToolbarStore } from "@core/Store/BottomToolbar.Store";

export default function Org() {
    const location = useLocationStore();
    const SessionInfo = useSessionStore();
    const eventHandler = useEventHandlerStore();
    const bottomToolbar = useBottomToolbarStore();
    const alert = useAlert();
    const [myOrganizations, setMyOrganizations] = useState<MyOranizationsView[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const { goTo } = useNavigation();

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

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

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

        bottomToolbar.set(<></>);
    }, []);

    useEffect(() => {
        eventHandler.setEventType(EVENT_TYPES.LOADING);
        loadOrganizationsByUser(SessionInfo.userId)
            .then((organizations) => {
                setMyOrganizations(organizations);
            })
            .catch((error) => {
                alert.showError(error.format());
            })
            .finally(() => {
                setIsLoading(false);
                eventHandler.setEventType(EVENT_TYPES.NEED_ADD);
            });
    }, []);

    const handleCreateNewOrg = () => {
        goTo("/admin/assistant?flow=onboarding-org&action=new-org");
    };

    const handleOrganizationClick = (organizationId: string) => {
        eventHandler.setEventType(EVENT_TYPES.SLEEP);

        goTo("/admin/org/profile/" + organizationId);
    };

    const OrganizationItem = ({ data }: { data: MyOranizationsView }) => {
        return (
            <>
                <div
                    className={style.organizationCard}
                    onClick={() => handleOrganizationClick(data.id)}
                >
                    <h1 style={{ textTransform: "capitalize" }}>{data.name}</h1>
                    <p>{data.description}</p>
                    {data.isOwner && (
                        <span className={style.organizationCardRolOwner}>Propietario</span>
                    )}
                    {!data.isOwner && (
                        <span className={style.organizationCardRolCollaborator}>Colaborador</span>
                    )}
                </div>
            </>
        );
    };

    return (
        <>
            <Location />
            {!isLoading && myOrganizations.length === 0 && (
                <div style={{ 
                    textAlign: 'center', 
                    margin: '60px auto', 
                    padding: '60px 40px', 
                    background: 'white', 
                    borderRadius: '24px', 
                    border: '1px solid rgba(0, 0, 0, 0.05)', 
                    boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.08)',
                    maxWidth: '750px',
                    position: 'relative',
                    overflow: 'hidden'
                }}>
                    <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: '4px', background: 'linear-gradient(90deg, #FF4B2B 0%, #FF416C 100%)' }}></div>
                    
                    <div style={{ width: '80px', height: '80px', background: 'linear-gradient(135deg, rgba(255, 75, 43, 0.1) 0%, rgba(255, 65, 108, 0.1) 100%)', borderRadius: '50%', margin: '0 auto 25px auto', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                        <RocketLaunchIcon style={{ fontSize: '40px', color: '#FF416C' }} />
                    </div>

                    <h2 style={{ color: '#111827', marginBottom: '15px', fontSize: '32px', fontWeight: '800', letterSpacing: '-0.5px' }}>¡Bienvenido a tu panel de control!</h2>
                    <p style={{ color: '#4B5563', marginBottom: '40px', fontSize: '17px', lineHeight: '1.6', maxWidth: '600px', margin: '0 auto 40px auto' }}>
                        Aún no tienes ninguna sucursal creada en el sistema. <br/>
                        No te preocupes por configuraciones complejas o formularios técnicos. 
                        Simplemente invoca a nuestro <strong>Asistente Virtual IA</strong> y él se encargará de guiarte paso a paso en segundos.
                    </p>
                    <button 
                        onClick={handleCreateNewOrg}
                        style={{
                            background: 'linear-gradient(135deg, #FF4B2B 0%, #FF416C 100%)',
                            color: 'white',
                            border: 'none',
                            padding: '12px 28px',
                            borderRadius: '50px',
                            fontSize: '16px',
                            fontWeight: 'bold',
                            cursor: 'pointer',
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: '10px',
                            boxShadow: '0 4px 15px rgba(255, 65, 108, 0.4)',
                            transition: 'all 0.3s ease'
                        }}
                        onMouseOver={(e) => {
                            e.currentTarget.style.transform = 'translateY(-2px)';
                            e.currentTarget.style.boxShadow = '0 6px 20px rgba(255, 65, 108, 0.6)';
                        }}
                        onMouseOut={(e) => {
                            e.currentTarget.style.transform = 'translateY(0)';
                            e.currentTarget.style.boxShadow = '0 4px 15px rgba(255, 65, 108, 0.4)';
                        }}
                    >
                        <AutoAwesomeIcon style={{ fontSize: '20px' }} />
                        Iniciar Asistente IA
                    </button>
                </div>
            )}
            {myOrganizations.map((organization) => (
                <OrganizationItem key={organization.id} data={organization} />
            ))}
        </>
    );
}
