import { Icon } from "@iconify/react";
import { Box, Chip, Divider, Paper, Typography, useTheme } from "@mui/material";
import { useEffect } from "react";
import styled from "styled-components";
import { ScreenGuia } from "../components/_standards";
import { NOVEDADES } from "../data/novedades";
import { markNovedadesSeen } from "../utils/novedadesSeen";

export const Novedades = () => {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const logoSrc = isDark ? "/logos/logo-dark.png" : "/logos/logo-light.png";

  // Al abrir la pantalla, marcamos las novedades como leídas (limpia el badge del menú).
  useEffect(() => {
    markNovedadesSeen();
  }, []);

  return (
    <Container>
      <Box sx={{ maxWidth: 820, mx: "auto", py: 4 }}>
        {/* Encabezado con marca */}
        <Paper variant="outlined" sx={{ p: { xs: 3, sm: 4.5 }, mb: 3, textAlign: "center" }}>
          <Box
            component="img"
            src={logoSrc}
            alt="NOVASIS"
            sx={{ height: { xs: 72, sm: 88 }, width: "auto", display: "block", mx: "auto", mb: 2.5 }}
          />
          <Typography variant="overline" color="primary" sx={{ fontWeight: 700, letterSpacing: 1.5 }}>
            Novedades del sistema
          </Typography>
          <Typography variant="h4" fontWeight={700} sx={{ mt: 0.5, mb: 1.5, letterSpacing: "-0.02em" }}>
            Actualizaciones del sistema
          </Typography>
          <Typography variant="body1" color="text.secondary" sx={{ maxWidth: "58ch", mx: "auto" }}>
            Acá publicamos las mejoras y ajustes de cada actualización, de la más reciente a la
            más antigua. Cada punto incluye dónde verificarlo dentro del sistema, para que puedas
            confirmar que todo funciona como esperás.
          </Typography>
        </Paper>

        <Box sx={{ mb: 3 }}>
          <ScreenGuia
            titulo="¿Cómo leer esta pantalla?"
            intro="Cada bloque es una actualización con su fecha. Adentro, las mejoras están agrupadas por área. La etiqueta «Verificar» te indica dónde comprobar cada cambio con tus propios datos."
            pasos={[
              "Las actualizaciones más recientes aparecen arriba.",
              "El badge «Nuevo» marca funciones que antes no existían.",
              "Seguí la ruta de «Verificar» para confirmar cada mejora en el sistema.",
            ]}
          />
        </Box>

        {/* Línea de tiempo de releases */}
        {NOVEDADES.map((release, ri) => (
          <ReleaseBlock
            key={ri}
            $last={ri === NOVEDADES.length - 1}
            $border={theme.palette.divider}
          >
            <Dot $color={theme.palette.primary.main} $ring={theme.palette.background.default} />
            <Typography
              variant="caption"
              sx={{
                display: "block",
                textTransform: "uppercase",
                letterSpacing: 1,
                fontWeight: 700,
                color: "text.secondary",
                mb: 0.5,
              }}
            >
              {release.fecha}
            </Typography>
            {release.titulo && (
              <Typography variant="h6" fontWeight={700} sx={{ mb: 2, letterSpacing: "-0.01em" }}>
                {release.titulo}
              </Typography>
            )}

            {release.grupos.map((grupo, gi) => (
              <Box key={gi} sx={{ mb: gi === release.grupos.length - 1 ? 0 : 2.5 }}>
                <Box sx={{ display: "flex", alignItems: "center", gap: 1.5, mb: 1.25 }}>
                  <Typography
                    variant="caption"
                    sx={{
                      textTransform: "uppercase",
                      letterSpacing: 0.7,
                      fontWeight: 700,
                      color: "text.secondary",
                      whiteSpace: "nowrap",
                    }}
                  >
                    {grupo.area}
                  </Typography>
                  <Divider sx={{ flex: 1 }} />
                </Box>

                {grupo.items.map((item, ii) => (
                  <Paper key={ii} variant="outlined" sx={{ p: 2, mb: 1.25, borderRadius: 2 }}>
                    <Box sx={{ display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap" }}>
                      <Typography variant="subtitle1" fontWeight={650}>
                        {item.titulo}
                      </Typography>
                      {item.nuevo && (
                        <Chip
                          label="Nuevo"
                          size="small"
                          color="primary"
                          sx={{ height: 20, fontSize: "0.65rem", fontWeight: 700, letterSpacing: 0.5 }}
                        />
                      )}
                    </Box>
                    <Typography variant="body2" color="text.secondary" sx={{ mt: 0.5 }}>
                      {item.descripcion}
                    </Typography>
                    {item.verificar && (
                      <Box
                        sx={{
                          display: "flex",
                          alignItems: "center",
                          gap: 1,
                          mt: 1.25,
                          pt: 1.25,
                          borderTop: "1px dashed",
                          borderColor: "divider",
                        }}
                      >
                        <Chip
                          icon={<Icon icon="mdi:check-circle-outline" width={14} />}
                          label="Verificar"
                          size="small"
                          variant="outlined"
                          color="success"
                          sx={{ height: 22, fontSize: "0.65rem", fontWeight: 700, letterSpacing: 0.4 }}
                        />
                        <Typography variant="body2" color="text.secondary">
                          {item.verificar}
                        </Typography>
                      </Box>
                    )}
                  </Paper>
                ))}
              </Box>
            ))}
          </ReleaseBlock>
        ))}

        <Typography
          variant="body2"
          color="text.secondary"
          sx={{ textAlign: "center", mt: 4, pt: 3, borderTop: "1px solid", borderColor: "divider" }}
        >
          ¿Dudas o algo no coincide con lo que ves? Escribinos y lo revisamos juntos.
        </Typography>
      </Box>
    </Container>
  );
};

const Container = styled.div`
  min-height: calc(100vh - 80px);
  margin-top: 50px;
  padding: 15px;
`;

const ReleaseBlock = styled.div`
  position: relative;
  padding-left: 26px;
  padding-bottom: ${({ $last }) => ($last ? "0" : "36px")};
  border-left: 2px solid ${({ $border }) => $border || "rgba(0,0,0,0.12)"};
  margin-left: 6px;
`;

const Dot = styled.span`
  position: absolute;
  left: -8px;
  top: 3px;
  width: 14px;
  height: 14px;
  border-radius: 50%;
  background: ${({ $color }) => $color || "#2f6f5e"};
  box-shadow: 0 0 0 4px ${({ $ring }) => $ring || "#fff"};
`;
