import { useEffect, useState } from "react";
import { Drawer, Box, Typography, IconButton, Stack, Tooltip } from "@mui/material";
import { Icon } from "@iconify/react";
import { useLocation } from "react-router-dom";
import { pathToScreenKey } from "./screenKeyMap";
import { resolveScreen } from "../../utils/screenSubmoduloMap";
import { useSesionesAyuda, useCrearSesionAyuda } from "./useAyudaIa";
import AyudaIaChat from "./AyudaIaChat";

export default function AyudaIaDrawer({ open, onClose }) {
  const location = useLocation();
  const screenKey = pathToScreenKey(location.pathname);
  const pantalla = resolveScreen(location.pathname);
  const [sesionId, setSesionId] = useState(null);

  const { data: sesiones = [] } = useSesionesAyuda(open);
  const crearSesion = useCrearSesionAyuda();

  useEffect(() => {
    if (!open) return;
    if (sesionId) return;
    if (sesiones.length > 0) {
      setSesionId(sesiones[0].id);
    } else if (!crearSesion.isPending) {
      crearSesion.mutateAsync().then((s) => setSesionId(s.id)).catch(() => {});
    }
  }, [open, sesiones, sesionId]);

  const nuevaSesion = async () => {
    try {
      const s = await crearSesion.mutateAsync();
      setSesionId(s.id);
    } catch {
      // toast manejado en el chat
    }
  };

  return (
    <Drawer
      anchor="right"
      open={open}
      onClose={onClose}
      PaperProps={{
        sx: {
          width: { xs: "100%", sm: 420 },
          maxWidth: "100vw",
          bgcolor: "background.default",
        },
      }}
    >
      <Box sx={{ display: "flex", flexDirection: "column", height: "100%" }}>
        <Box
          sx={{
            px: 1.5,
            py: 1.25,
            borderBottom: 1,
            borderColor: "divider",
            background: "linear-gradient(135deg, #1e3a5f 0%, #2563eb 55%, #0ea5e9 100%)",
            color: "#fff",
            position: "relative",
            overflow: "hidden",
            "&::after": {
              content: '""',
              position: "absolute",
              inset: 0,
              background:
                "radial-gradient(circle at 80% -20%, rgba(255,255,255,0.25), transparent 55%)",
              pointerEvents: "none",
            },
          }}
        >
          <Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ position: "relative", zIndex: 1 }}>
            <Stack direction="row" spacing={1.25} alignItems="center">
              <Box
                sx={{
                  width: 32,
                  height: 32,
                  borderRadius: "50%",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  bgcolor: "rgba(255,255,255,0.2)",
                  backdropFilter: "blur(4px)",
                  border: "1px solid rgba(255,255,255,0.25)",
                }}
              >
                <Icon icon="mdi:auto-awesome" width={18} />
              </Box>
              <Box>
                <Typography sx={{ fontSize: 14.5, fontWeight: 800, lineHeight: 1.1, letterSpacing: 0.2 }}>
                  NovaIA
                </Typography>
                <Typography sx={{ fontSize: 10.5, opacity: 0.92 }}>
                  Tu Asistente ERP
                </Typography>
              </Box>
            </Stack>
            <Stack direction="row" spacing={0.25}>
              <Tooltip title="Nueva conversación" arrow>
                <IconButton size="small" onClick={nuevaSesion} sx={{ color: "inherit" }}>
                  <Icon icon="mdi:plus" width={18} />
                </IconButton>
              </Tooltip>
              <Tooltip title="Cerrar (Esc)" arrow>
                <IconButton size="small" onClick={onClose} sx={{ color: "inherit" }}>
                  <Icon icon="mdi:close" width={18} />
                </IconButton>
              </Tooltip>
            </Stack>
          </Stack>
        </Box>

        <Box sx={{ flex: 1, minHeight: 0 }}>
          {sesionId ? (
            <AyudaIaChat
              sesionId={sesionId}
              screenKey={screenKey}
              screenUrl={location.pathname}
              screenModulo={pantalla?.modulo ?? null}
              screenSubmodulo={pantalla?.submodulo ?? null}
              onClose={onClose}
            />
          ) : (
            <Stack alignItems="center" justifyContent="center" sx={{ height: "100%", p: 2 }}>
              <Typography sx={{ fontSize: 12, color: "text.secondary" }}>
                Preparando conversación…
              </Typography>
            </Stack>
          )}
        </Box>
      </Box>
    </Drawer>
  );
}
