import { Login, Person, Visibility, VisibilityOff } from "@mui/icons-material";
import { Box, Button, CircularProgress, Divider, IconButton, InputAdornment, Link, Paper, TextField, Typography, useTheme } from "@mui/material";
import { useMutation } from "@tanstack/react-query";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import styled from "styled-components";
import { ASSETS } from "../../config/assets";
import { useAuthStore } from "../../index";

export function LoginTemplate() {
  const navigate = useNavigate();
  const { login, isLoading } = useAuthStore();
  const [showPassword, setShowPassword] = useState(false);
  const muiTheme = useTheme();
  const isDark = muiTheme.palette.mode === "dark";

  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm({
    defaultValues: {
      usuario: "",
      password: "",
    },
  });

  // Mutation para login
  const { mutateAsync, isPending } = useMutation({
    mutationKey: ["login"],
    mutationFn: login,
  });

  // Login con usuario (RUC/username) y password
  const handleLogin = async (data) => {
    try {
      await mutateAsync({
        usuario: data.usuario?.trim(),
        password: data.password?.trim(),
      });
      toast.success("Sesión iniciada correctamente");
      // Entrada única para todos los perfiles: el inicio no depende de permisos,
      // así que no hay cadena de redirecciones. Los dashboards se abren desde el
      // menú, ya gateados por su propio permiso.
      navigate("/");
    } catch (error) {
      toast.error(error.message || "Error al iniciar sesión");
    }
  };

  const loading = isPending || isLoading;

  return (
    <PageWrapper>
      {/* Fondo completo */}
      <BgImage />
      <BgOverlay />

      {/* Contenido centrado */}
      <Content>
        <MobileLogoWrapper>
          <MobileLogo src={isDark ? ASSETS.logo.light : ASSETS.logo.loginDark} alt="Novasis" />
          <MobileSubtitle $isDark={isDark}></MobileSubtitle>
        </MobileLogoWrapper>
        <Paper
          elevation={0}
          sx={{
            width: "100%",
            maxWidth: { xs: "100%", sm: 420 },
            p: { xs: 3, sm: 4 },
            borderRadius: 3,
            backdropFilter: "blur(20px)",
            backgroundColor: isDark ? "rgba(15, 23, 42, 0.82)" : "rgba(255, 255, 255, 0.92)",
            border: isDark ? "1px solid rgba(100, 160, 255, 0.12)" : "1px solid rgba(0, 0, 0, 0.08)",
            boxShadow: isDark ? "0 8px 40px rgba(0, 0, 0, 0.45), 0 0 80px rgba(59, 130, 246, 0.08)" : "0 8px 40px rgba(0, 0, 0, 0.08), 0 1px 3px rgba(0, 0, 0, 0.06)",
          }}
        >
          <Typography variant="h5" fontWeight={600} textAlign="center" gutterBottom sx={{ color: isDark ? "#e2e8f0" : "#1e293b" }}>
            Iniciar Sesión
          </Typography>
          <Typography
            variant="body2"
            textAlign="center"
            sx={{
              mb: 4,
              color: isDark ? "rgba(148, 163, 184, 0.9)" : "#64748b",
            }}
          >
            Ingresa tus credenciales para acceder
          </Typography>

          <Box component="form" onSubmit={handleSubmit(handleLogin)} sx={{ display: "flex", flexDirection: "column", gap: 2.5 }}>
            <Controller
              name="usuario"
              control={control}
              rules={{ required: "Usuario es obligatorio" }}
              render={({ field }) => (
                <TextField
                  {...field}
                  inputRef={(input) => input && setTimeout(() => input.focus(), 100)}
                  label="Usuario"
                  placeholder="Ruc o username"
                  fullWidth
                  error={!!errors.usuario}
                  helperText={errors.usuario?.message}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <Person color="action" />
                      </InputAdornment>
                    ),
                  }}
                />
              )}
            />

            <Controller
              name="password"
              control={control}
              rules={{ required: "Contraseña es obligatoria" }}
              render={({ field }) => (
                <TextField
                  {...field}
                  label="Contraseña"
                  type={showPassword ? "text" : "password"}
                  placeholder="••••••"
                  fullWidth
                  error={!!errors.password}
                  helperText={errors.password?.message}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <Login color="action" />
                      </InputAdornment>
                    ),
                    endAdornment: (
                      <InputAdornment position="end">
                        <IconButton onClick={() => setShowPassword(!showPassword)} edge="end" size="small">
                          {showPassword ? <VisibilityOff /> : <Visibility />}
                        </IconButton>
                      </InputAdornment>
                    ),
                  }}
                />
              )}
            />

            <Button
              type="submit"
              variant="contained"
              size="large"
              fullWidth
              disabled={loading}
              sx={{
                py: 1.5,
                mt: 1,
                fontWeight: 600,
                fontSize: "1rem",
              }}
            >
              {loading ? <CircularProgress size={24} color="inherit" /> : "Ingresar"}
            </Button>
          </Box>

          <Divider sx={{ my: 3 }}>
            <Typography variant="body2" color="text.secondary">
              ¿Nuevo usuario?
            </Typography>
          </Divider>

          <Button variant="outlined" fullWidth onClick={() => navigate("/register")} sx={{ py: 1.2 }}>
            Crear una cuenta
          </Button>
        </Paper>

        {/* Footer */}
        <Typography variant="caption" color="text.secondary" sx={{ mt: 3, textAlign: "center", display: "block" }}>
          © 2026 Novasis. Todos los derechos reservados.
          <br />
          <Link href="#" underline="hover" color="inherit">
            Términos de uso
          </Link>
          {" · "}
          <Link href="#" underline="hover" color="inherit">
            Privacidad
          </Link>
        </Typography>
      </Content>
    </PageWrapper>
  );
}

/* ── Styled Components ── */
const PageWrapper = styled.div`
  min-height: 100vh;
  position: relative;
  overflow: hidden;
  background: ${({ theme }) => theme.bgtotal};
`;

const BgImage = styled.div`
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  background: url("${ASSETS.backgrounds.login}") center 20% / cover no-repeat;
  z-index: 0;

  @media (max-width: 600px) {
    display: none;
  }
`;

const BgOverlay = styled.div`
  position: absolute;
  inset: 0;
  z-index: 1;
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0.05) 0%, rgba(0, 0, 0, 0.1) 40%, rgba(15, 23, 42, 0.65) 70%, rgba(15, 23, 42, 0.92) 100%);

  @media (max-width: 600px) {
    display: none;
  }
`;

const Content = styled.div`
  position: relative;
  z-index: 2;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  padding: 20px 20px 24px;
  min-height: 100vh;
  box-sizing: border-box;
  gap: 16px;

  @media (max-width: 600px) {
    padding: 48px 16px 24px;
    justify-content: flex-start;
  }
`;

const MobileLogoWrapper = styled.div`
  display: none;
  flex-direction: column;
  align-items: center;
  margin-bottom: 32px;

  @media (max-width: 600px) {
    display: flex;
  }
`;

const MobileLogo = styled.img`
  width: 140px;
  height: auto;
  margin-bottom: 8px;
`;

const MobileSubtitle = styled.span`
  color: ${({ $isDark }) => ($isDark ? "rgba(148, 163, 184, 0.9)" : "#64748b")};
  font-size: 0.95rem;
  letter-spacing: 0.5px;
`;
