"use client";
import React, { useEffect } from "react";
import style from "./AssistantHome.module.css";
import { useSessionStore } from "@core/Store/Sesion.Store";
import Avatar from "@components/Avatar/Avatar";
import AssistantButton from "../AssistantButton/AssistantButton";
import { useRouter } from "next/navigation";
import RocketLaunchIcon from '@mui/icons-material/RocketLaunch';
import EventBusyIcon from '@mui/icons-material/EventBusy';
import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';
import GroupAddIcon from '@mui/icons-material/GroupAdd';
import SearchIcon from "@mui/icons-material/Search";
import BlockIcon from "@mui/icons-material/Block";
import EventRepeatIcon from "@mui/icons-material/EventRepeat";
import CalendarMonthIcon from '@mui/icons-material/CalendarMonth';
import ColorLensIcon from '@mui/icons-material/ColorLens';
import PinDropIcon from '@mui/icons-material/PinDrop';
import API from "@services/Api.Service";


type FlowDefinition = {
    id: string;
    flowId: string;
    title: string;
    description: string;
    category: string;
    keywords: string[];
    icon: React.ElementType;
};

const AVAILABLE_FLOWS: FlowDefinition[] = [
    {
        id: "new-org",
        flowId: "onboarding-org&action=new-org",
        title: "Nuevo Negocio",
        description: "Crear una nueva sucursal u organización desde cero.",
        category: "Negocio",
        keywords: ["nuevo negocio", "sucursal", "crear organizacion", "nueva empresa", "onboarding"],
        icon: RocketLaunchIcon
    },
    {
        id: "edit-appearance",
        flowId: "onboarding-org&action=edit-appearance",
        title: "Editar Apariencia",
        description: "Modifica el logotipo y colores de tu negocio.",
        category: "Negocio",
        keywords: ["logo", "colores", "apariencia", "diseño", "marca", "foto", "imagen"],
        icon: ColorLensIcon
    },
    {
        id: "edit-location",
        flowId: "onboarding-org&action=edit-location",
        title: "Editar Ubicación",
        description: "Actualiza la dirección y posición en el mapa.",
        category: "Negocio",
        keywords: ["direccion", "mapa", "ubicacion", "calle", "ciudad", "gps"],
        icon: PinDropIcon
    },
    {
        id: "edit-contact",
        flowId: "onboarding-org&action=edit-contact",
        title: "Editar Contacto",
        description: "Actualiza el teléfono y la información de contacto.",
        category: "Negocio",
        keywords: ["telefono", "contacto", "email", "whatsapp", "redes", "celular"],
        icon: AddCircleOutlineIcon
    },
    {
        id: "new-service",
        flowId: "onboarding-service&action=new-service",
        title: "Agregar Servicio",
        description: "Crear un nuevo servicio que ofreces a tus clientes.",
        category: "Servicios",
        keywords: ["nuevo servicio", "prestacion", "ofrecer", "crear servicio", "precio", "duracion"],
        icon: AddCircleOutlineIcon
    },
    {
        id: "update-schedule",
        flowId: "update-schedule",
        title: "Modificar Horarios",
        description: "Ajustar la disponibilidad semanal de tu negocio.",
        category: "Horarios",
        keywords: ["horarios", "disponibilidad", "semana", "apertura", "cierre", "jornada"],
        icon: CalendarMonthIcon
    },
    {
        id: "override-schedule",
        flowId: "override-schedule",
        title: "Horario Especial",
        description: "Configurar un horario distinto para una fecha puntual.",
        category: "Horarios",
        keywords: ["excepcion", "horario distinto", "fecha puntual", "dia especial", "sobreescribir"],
        icon: EventRepeatIcon
    },
    {
        id: "disable-schedule",
        flowId: "disable-schedule",
        title: "Cerrar Agenda",
        description: "Inhabilitar turnos por feriados o vacaciones.",
        category: "Horarios",
        keywords: ["cerrar", "feriado", "vacaciones", "inhabilitar", "bloquear", "ausencia", "descanso", "no disponible"],
        icon: BlockIcon
    },
    {
        id: "new-collaborator",
        flowId: "new-collaborator",
        title: "Invitar Colaborador",
        description: "Invita a un profesional a unirse al equipo de tu organización.",
        category: "Colaboradores",
        keywords: ["invitar", "colaborador", "profesional", "empleado", "staff", "equipo"],
        icon: GroupAddIcon
    }
];

export default function AssistantHome() {
    const SessionInfo = useSessionStore();
    const router = useRouter();
    
    type IncompleteOrgData = {
        org: any;
        percent: number;
        currentStepName: string;
        flowToTrigger: string;
    };
    
    const [incompleteOrgs, setIncompleteOrgs] = React.useState<IncompleteOrgData[]>([]);
    const [incompleteCollaborators, setIncompleteCollaborators] = React.useState<any[]>([]);
    const [isLoadingFlow, setIsLoadingFlow] = React.useState(true);
    const [searchQuery, setSearchQuery] = React.useState("");

    useEffect(() => {
        const determineFlow = async () => {
            try {
                const response = await API.post<any[]>("companies/get-by-user", { sessionUser: SessionInfo.userId });
                const orgs = response || [];
                const newIncompleteOrgs: IncompleteOrgData[] = [];

                if (orgs.length > 0) {
                    for (const org of orgs) {
                        if (org.onboardingCompleted) continue;

                        const isNameMissing = !org.name || org.name.trim() === "";
                        const isLocationMissing = !org.street || org.street.trim() === "";
                        const isContactMissing = !org.phoneNumber || org.phoneNumber.trim() === "";
                        const isRulesMissing = !org.heatMapFraction;
                        const isServicesMissing = SessionInfo.metrics.servicesCount === 0;

                        let percent = 0;
                        let currentStepName = "Detalles del Negocio";
                        let flowToTrigger = "onboarding-org";
                        let isCompleteButFlagMissing = false;

                        if (isNameMissing) {
                            percent = 5;
                            currentStepName = "Nombre y Categoría";
                        } else if (isLocationMissing) {
                            percent = 25;
                            currentStepName = "Ubicación en el mapa";
                        } else if (isContactMissing) {
                            percent = 40;
                            currentStepName = "Medios de contacto";
                        } else if (isRulesMissing) {
                            percent = 60;
                            currentStepName = "Reglas de reserva";
                        } else if (isServicesMissing) {
                            percent = 75;
                            currentStepName = "Primer servicio";
                            flowToTrigger = "onboarding-service";
                        } else {
                            percent = 90;
                            currentStepName = "Horarios de atención";
                            flowToTrigger = "onboarding-schedule";
                            
                            try {
                                const employees = await API.post<any[]>("employees/get-by-company", { companyId: org.id || org._id });
                                if (employees && employees.length > 0) {
                                    const schedulesRes = await API.post<any>("schedules/get-all-by-collaborator", { 
                                        companyId: org.id || org._id, 
                                        employeeId: employees[0].id || employees[0]._id || employees[0].employeeId 
                                    });
                                    
                                    if (schedulesRes && schedulesRes.data && schedulesRes.data.length > 0) {
                                        isCompleteButFlagMissing = true;
                                    }
                                }
                            } catch (e) {
                                console.error("Error checking schedules", e);
                            }
                        }

                        if (!isCompleteButFlagMissing) {
                            newIncompleteOrgs.push({
                                org,
                                percent,
                                currentStepName,
                                flowToTrigger
                            });
                        }
                    }
                    
                    setIncompleteOrgs(newIncompleteOrgs);
                } else {
                    setIncompleteOrgs([{
                        org: null,
                        percent: 0,
                        currentStepName: "Detalles del Negocio",
                        flowToTrigger: "onboarding-org"
                    }]);
                }
            } catch (error) {
                console.error("Error fetching organizations:", error);
                setIncompleteOrgs([{
                    org: null,
                    percent: 0,
                    currentStepName: "Detalles del Negocio",
                    flowToTrigger: "onboarding-org"
                }]);
            }
            
            try {
                const collabResponse = await API.post<any[]>("employees/get-incomplete-setup", { sessionUser: SessionInfo.userId });
                if (collabResponse && Array.isArray(collabResponse)) {
                    setIncompleteCollaborators(collabResponse);
                }
            } catch (e) {
                console.error("Error fetching incomplete collaborators", e);
            } finally {
                setIsLoadingFlow(false);
            }
        };
        
        determineFlow();
    }, [SessionInfo.metrics, SessionInfo.userId, router]);

    const isSetupIncomplete = () => {
        return incompleteOrgs.length > 0 || incompleteCollaborators.length > 0;
    };

    const handleStartFlow = (flowId: string, companyId?: string) => {
        let route = `/admin/assistant?flow=${flowId}`;
        if (companyId) {
            route += `&companyId=${companyId}`;
        }
        router.push(route);
    };

    const handleDismissOnboarding = async (orgId: string) => {
        try {
            await API.post<any>("companies/update", {
                id: orgId,
                onboardingCompleted: true,
                sessionUser: SessionInfo.userId
            });
            setIncompleteOrgs(prev => prev.filter(item => item.org && (item.org.id || item.org._id) !== orgId));
        } catch (e) {
            console.error("Error al omitir el onboarding:", e);
        }
    };

    return (
        <div className={style.homeCard}>
            <div className={style.header}>
                <Avatar 
                    src={SessionInfo.avatar || ""} 
                    name={SessionInfo.userFullName} 
                    alt="Avatar" 
                    size="large"
                />
                <h2>Hola {SessionInfo.userFullName.split(" ")[0]}, ¿en qué te puedo ayudar hoy?</h2>
                <p className={style.subtitle}>Soy tu asistente virtual. Selecciona una acción y te guiaré paso a paso.</p>
            </div>

            <div className={style.actionsContainer}>
                {isSetupIncomplete() && (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
                        {incompleteOrgs.map((data, index) => {
                            const orgName = data.org && data.org.name ? data.org.name : "Nuevo Negocio";
                            const orgId = data.org ? (data.org.id || data.org._id) : null;
                            
                            return (
                                <div key={orgId || index} className={style.onboardingCard}>
                                    <div className={style.onboardingContent}>
                                        <div className={style.onboardingIcon}>
                                            <RocketLaunchIcon fontSize="large" style={{ color: "#fff" }} />
                                        </div>
                                        <div className={style.onboardingTexts} style={{ flex: 1 }}>
                                            <h3>Configuración de: <span style={{ color: 'rgba(255,255,255,0.9)' }}>{orgName}</span></h3>
                                            <p>Aún faltan algunos pasos para que tus clientes puedan reservar.</p>
                                            
                                            <div style={{ marginTop: '20px' }}>
                                                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '13px', color: 'rgba(255,255,255,0.85)', marginBottom: '8px' }}>
                                                    <span>Paso actual: <strong style={{ color: 'white' }}>{data.currentStepName}</strong></span>
                                                    <span style={{ fontWeight: 'bold' }}>{data.percent}%</span>
                                                </div>
                                                <div style={{ height: '8px', background: 'rgba(255,255,255,0.05)', borderRadius: '4px', overflow: 'hidden' }}>
                                                    <div style={{ 
                                                        height: '100%', 
                                                        width: `${data.percent}%`, 
                                                        background: 'linear-gradient(90deg, #e11d48 0%, #be123c 100%)', 
                                                        borderRadius: '4px', 
                                                        transition: 'width 0.8s cubic-bezier(0.4, 0, 0.2, 1)'
                                                    }}></div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <AssistantButton
                                        text={isLoadingFlow ? "Cargando..." : "Continuar Configuración"}
                                        onClick={() => {
                                            if (!isLoadingFlow) {
                                                handleStartFlow(data.flowToTrigger, orgId);
                                            }
                                        }}
                                        style={{ width: "100%", marginTop: "20px", height: "48px" }}
                                    />
                                    {orgId && (
                                        <div style={{ textAlign: 'center', marginTop: '30px' }}>
                                            <button 
                                                onClick={() => handleDismissOnboarding(orgId)}
                                                style={{ 
                                                    background: 'transparent', border: 'none', color: 'rgba(255,255,255,0.5)', 
                                                    fontSize: '13px', cursor: 'pointer', textDecoration: 'underline',
                                                    transition: 'color 0.2s'
                                                }}
                                                onMouseOver={(e) => e.currentTarget.style.color = 'rgba(255,255,255,0.8)'}
                                                onMouseOut={(e) => e.currentTarget.style.color = 'rgba(255,255,255,0.5)'}
                                            >
                                                Ya tengo mi negocio configurado y funcionando, ocultar esto
                                            </button>
                                        </div>
                                    )}
                                </div>
                            );
                        })}
                        {incompleteCollaborators.map((collab, index) => (
                            <div key={`collab-${index}`} className={style.onboardingCard}>
                                <div className={style.onboardingContent}>
                                    <div className={style.onboardingIcon}>
                                        <GroupAddIcon fontSize="large" style={{ color: "#fff" }} />
                                    </div>
                                    <div className={style.onboardingTexts} style={{ flex: 1 }}>
                                        <h3>Configuración de Colaborador en <span style={{ color: 'rgba(255,255,255,0.9)' }}>{collab.companyName}</span></h3>
                                        <p>
                                            El colaborador <strong>{collab.name}</strong> aún no tiene 
                                            {collab.missingServices && collab.missingSchedules ? " servicios ni horarios" : (collab.missingServices ? " servicios" : " horarios")} asignados.
                                        </p>
                                    </div>
                                </div>
                                <AssistantButton
                                    text={isLoadingFlow ? "Cargando..." : "Configurar Colaborador"}
                                    onClick={() => {
                                        if (!isLoadingFlow) {
                                            router.push(`/admin/assistant?flow=setup-collaborator&companyId=${collab.companyId}&employeeId=${collab.employeeId}`);
                                        }
                                    }}
                                    style={{ width: "100%", marginTop: "20px", height: "48px" }}
                                />
                            </div>
                        ))}
                    </div>
                )}

                
                {/* Siempre mostrar flujos secundarios */}
                    <>
                        {/* Buscador */}

                <div style={{ position: 'relative', marginBottom: '30px', maxWidth: '600px', margin: '0 auto 30px auto' }}>
                    <SearchIcon style={{ position: 'absolute', left: '15px', top: '50%', transform: 'translateY(-50%)', color: 'rgba(255,255,255,0.5)' }} />
                    <input 
                        type="text" 
                        placeholder="Buscar acciones o configuraciones..." 
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        className={style.searchInput}
                    />
                </div>

                {/* Categories */}
                <div style={{ display: 'flex', flexDirection: 'column', gap: '40px' }}>
                    {Array.from(new Set(AVAILABLE_FLOWS.map(f => f.category))).map(category => {
                        const filteredFlows = AVAILABLE_FLOWS.filter(flow => {
                            if (flow.category !== category) return false;
                            if (!searchQuery) return true;
                            
                            const query = searchQuery.toLowerCase();
                            const inTitle = flow.title.toLowerCase().includes(query);
                            const inDesc = flow.description.toLowerCase().includes(query);
                            const inKeywords = flow.keywords.some(kw => kw.toLowerCase().includes(query));
                            return inTitle || inDesc || inKeywords;
                        });

                        if (filteredFlows.length === 0) return null;

                        return (
                            <div key={category} style={{ display: 'flex', flexDirection: 'column', gap: '15px' }}>
                                <h3 style={{ margin: 0, paddingBottom: '10px', borderBottom: '1px solid rgba(255,255,255,0.1)', color: 'rgba(255,255,255,0.8)' }}>
                                    {category}
                                </h3>
                                <div className={style.quickActionsGrid}>
                                    {filteredFlows.map(flow => (
                                        <div 
                                            key={flow.id} 
                                            className={`${style.quickActionCard} ${flow.id === "new-org" ? style.premiumCard : ""}`} 
                                            onClick={() => handleStartFlow(flow.flowId)}
                                        >
                                            <flow.icon className={style.actionIcon} />
                                            <h4>{flow.title}</h4>
                                            <p>{flow.description}</p>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        );
                    })}
                    
                    {AVAILABLE_FLOWS.filter(flow => {
                        if (!searchQuery) return true;
                        const query = searchQuery.toLowerCase();
                        const inTitle = flow.title.toLowerCase().includes(query);
                        const inDesc = flow.description.toLowerCase().includes(query);
                        const inKeywords = flow.keywords.some(kw => kw.toLowerCase().includes(query));
                        return inTitle || inDesc || inKeywords;
                    }).length === 0 && (
                        <div style={{ textAlign: 'center', color: 'rgba(255,255,255,0.5)', marginTop: '20px' }}>
                            <p>No se encontraron resultados para "{searchQuery}"</p>
                        </div>
                    )}
                </div>
                    </>

            </div>
        </div>
    );
}
