import {
    ArrowBack,
    Business,
    CheckCircle,
    Email,
    Lock,
    Phone,
    Visibility,
    VisibilityOff,
} from "@mui/icons-material";
import {
    Box,
    Button,
    CircularProgress,
    Divider,
    IconButton,
    InputAdornment,
    LinearProgress,
    Link,
    Paper,
    Step,
    StepLabel,
    Stepper,
    TextField,
    Typography,
} 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, { useTheme } from "styled-components";
import { ASSETS } from "../../config/assets";
import { useAuthStore } from "../../index";

export function RegisterTemplate() {
  const navigate = useNavigate();
  const {
    register: registerEmpresa,
    enviarCodigo,
    verificarCodigo,
  } = useAuthStore();
  const theme = useTheme();
  const isLight = theme.body === "#ffffff";
  const registerLogo = isLight ? ASSETS.logo.light : ASSETS.logo.dark;

  // Estados del flujo de registro
  const [step, setStep] = useState(1);
  const [celularVerificado, setCelularVerificado] = useState("");
  const [codigoExpiracion, setCodigoExpiracion] = useState("");

  const {
    control,
    handleSubmit,
    formState: { errors },
    reset,
    watch,
  } = useForm({
    defaultValues: {
      celular: "",
      codigo: "",
      ruc: "",
      dv: "",
      razon_social: "",
      nombre_fantasia: "",
      email: "",
      password: "",
      confirmar_password: "",
    },
  });
  const password = watch("password");

  // Mutation para enviar código
  const { mutate: mutateEnviarCodigo, isPending: isPendingCodigo } =
    useMutation({
      mutationKey: ["enviar-codigo"],
      mutationFn: enviarCodigo,
      onSuccess: (data) => {
        toast.success("Código enviado a tu celular");
        setCodigoExpiracion(data.expiracion);
        setStep(2);
      },
      onError: (error) => {
        toast.error(error.message);
      },
    });

  // Mutation para verificar código
  const { mutate: mutateVerificarCodigo, isPending: isPendingVerificar } =
    useMutation({
      mutationKey: ["verificar-codigo"],
      mutationFn: verificarCodigo,
      onSuccess: () => {
        toast.success("Celular verificado correctamente");
        reset(); // Limpiar formulario para paso 3
        setStep(3);
      },
      onError: (error) => {
        toast.error(error.message);
      },
    });

  // Mutation para registro
  const { mutate: mutateRegistro, isPending: isPendingRegistro } = useMutation({
    mutationKey: ["registro-empresa"],
    mutationFn: registerEmpresa,
    onSuccess: () => {
      toast.success("Empresa registrada exitosamente");
      setStep(4);
      setTimeout(() => {
        navigate("/login");
      }, 2000);
    },
    onError: (error) => {
      toast.error(error.message);
    },
  });

  // Paso 1: Enviar código al celular (con prefijo 595)
  const handleEnviarCodigo = (data) => {
    // Remover cualquier caracter no numérico
    let celular = data.celular.replace(/\D/g, "");
    // Agregar prefijo 595 si no lo tiene
    if (!celular.startsWith("595")) {
      celular = "595" + celular;
    }
    setCelularVerificado(celular);
    mutateEnviarCodigo({
      tipo: "celular",
      celular: celular,
    });
  };

  // Paso 2: Verificar código
  const handleVerificarCodigo = (data) => {
    mutateVerificarCodigo({
      tipo: "celular",
      celular: celularVerificado,
      codigo: data.codigo,
    });
  };

  // Paso 3: Registrar empresa
  const handleRegistrarEmpresa = (data) => {
    // Auto-calcular tipo_contribuyente: RUC >= 80000000 = Persona Jurídica (2), sino Persona Física (1)
    const rucNumero = parseInt(data.ruc);
    const tipoContribuyente = rucNumero >= 80000000 ? 2 : 1;

    const registroData = {
      ruc: data.ruc,
      dv: data.dv,
      razon_social: data.razon_social,
      nombre_fantasia: data.nombre_fantasia || null,
      tipo_contribuyente: tipoContribuyente,
      celular: celularVerificado,
      email: data.email,
      usuario: data.ruc, // Usar RUC como usuario por defecto
      password: data.password,
    };
    mutateRegistro(registroData);
  };

  // Reenviar código (sin prefijo 595)
  const handleReenviarCodigo = () => {
    mutateEnviarCodigo({
      tipo: "celular",
      celular: celularVerificado,
    });
  };

  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  const steps = ["Verificar Celular", "Código", "Datos Empresa"];

  return (
    <Container>
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          width: "100%",
          maxWidth: { xs: "100%", sm: 480 },
          px: { xs: 1, sm: 2 },
        }}
      >
        {/* Logo */}
        <Box
          sx={{
            display: "flex",
            justifyContent: "center",
            width: "100%",
            mb: 3,
          }}
        >
          <img
            src={registerLogo}
            alt="Logo"
            style={{
              width: "100%",
              maxWidth: 300,
              height: "auto",
              objectFit: "contain",
            }}
          />
        </Box>

        {/* Stepper */}
        {step < 4 && (
          <Stepper activeStep={step - 1} sx={{ width: "100%", mb: 3 }}>
            {steps.map((label) => (
              <Step key={label}>
                <StepLabel>{label}</StepLabel>
              </Step>
            ))}
          </Stepper>
        )}

        {/* Card */}
        <Paper
          elevation={0}
          sx={{
            width: "100%",
            p: 4,
            borderRadius: 3,
          }}
        >
          {/* Paso 1: Ingresar celular */}
          {step === 1 && (
            <>
              <Typography
                variant="h5"
                fontWeight={600}
                textAlign="center"
                gutterBottom
              >
                Verificar tu número
              </Typography>
              <Typography
                variant="body2"
                color="text.secondary"
                textAlign="center"
                sx={{ mb: 3 }}
              >
                Ingresa tu número de celular para verificar tu identidad
              </Typography>

              <Box
                component="form"
                onSubmit={handleSubmit(handleEnviarCodigo)}
                sx={{ display: "flex", flexDirection: "column", gap: 2.5 }}
              >
                <Controller
                  name="celular"
                  control={control}
                  rules={{
                    required: "Celular es obligatorio",
                    pattern: {
                      value: /^9\d{8}$/,
                      message: "Ingrese 9 dígitos (ej: 981123000)",
                    },
                  }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="Celular"
                      placeholder="981123000"
                      fullWidth
                      autoFocus
                      error={!!errors.celular}
                      helperText={errors.celular?.message}
                      inputProps={{ maxLength: 9 }}
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <Phone color="action" />
                            <Typography sx={{ ml: 0.5, fontWeight: 600 }}>
                              +595
                            </Typography>
                          </InputAdornment>
                        ),
                      }}
                    />
                  )}
                />

                <Button
                  type="submit"
                  variant="contained"
                  size="large"
                  fullWidth
                  disabled={isPendingCodigo}
                  sx={{ py: 1.5, fontWeight: 600 }}
                >
                  {isPendingCodigo ? (
                    <CircularProgress size={24} color="inherit" />
                  ) : (
                    "Enviar Código"
                  )}
                </Button>
              </Box>

              <Divider sx={{ my: 3 }} />

              <Button
                variant="text"
                fullWidth
                onClick={() => navigate("/login")}
              >
                ¿Ya tienes cuenta? Inicia sesión
              </Button>
            </>
          )}

          {/* Paso 2: Verificar código */}
          {step === 2 && (
            <>
              <Button
                startIcon={<ArrowBack />}
                onClick={() => setStep(1)}
                sx={{ mb: 2, alignSelf: "flex-start" }}
              >
                Volver
              </Button>

              <Typography
                variant="h5"
                fontWeight={600}
                textAlign="center"
                gutterBottom
              >
                Verificar Código
              </Typography>
              <Typography
                variant="body2"
                color="text.secondary"
                textAlign="center"
                sx={{ mb: 1 }}
              >
                Enviamos un código de 6 dígitos al número:
              </Typography>
              <Typography
                variant="body1"
                fontWeight={600}
                textAlign="center"
                sx={{ mb: 2 }}
              >
                +{celularVerificado}
              </Typography>
              {codigoExpiracion && (
                <Typography
                  variant="caption"
                  color="text.secondary"
                  textAlign="center"
                  display="block"
                  sx={{ mb: 2 }}
                >
                  Expira: {codigoExpiracion}
                </Typography>
              )}

              <Box
                component="form"
                onSubmit={handleSubmit(handleVerificarCodigo)}
                sx={{ display: "flex", flexDirection: "column", gap: 2.5 }}
              >
                <Controller
                  name="codigo"
                  control={control}
                  rules={{
                    required: "Código es obligatorio",
                    minLength: {
                      value: 6,
                      message: "El código debe tener 6 dígitos",
                    },
                  }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="Código de verificación"
                      placeholder="123456"
                      fullWidth
                      autoFocus
                      error={!!errors.codigo}
                      helperText={errors.codigo?.message}
                      inputProps={{
                        maxLength: 6,
                        style: {
                          textAlign: "center",
                          letterSpacing: 8,
                          fontSize: 20,
                        },
                      }}
                    />
                  )}
                />

                <Button
                  type="submit"
                  variant="contained"
                  size="large"
                  fullWidth
                  disabled={isPendingVerificar}
                  sx={{ py: 1.5, fontWeight: 600 }}
                >
                  {isPendingVerificar ? (
                    <CircularProgress size={24} color="inherit" />
                  ) : (
                    "Verificar"
                  )}
                </Button>
              </Box>

              <Button
                variant="text"
                fullWidth
                onClick={handleReenviarCodigo}
                disabled={isPendingCodigo}
                sx={{ mt: 2 }}
              >
                {isPendingCodigo ? "Enviando..." : "Reenviar código"}
              </Button>
            </>
          )}

          {/* Paso 3: Datos de empresa */}
          {step === 3 && (
            <>
              <Button
                startIcon={<ArrowBack />}
                onClick={() => setStep(2)}
                sx={{ mb: 2, alignSelf: "flex-start" }}
              >
                Volver
              </Button>

              <Typography
                variant="h5"
                fontWeight={600}
                textAlign="center"
                gutterBottom
              >
                Datos de tu Empresa
              </Typography>
              <Typography
                variant="body2"
                color="text.secondary"
                textAlign="center"
                sx={{ mb: 3 }}
              >
                Celular verificado: <strong>+{celularVerificado}</strong>
              </Typography>

              <Box
                component="form"
                onSubmit={handleSubmit(handleRegistrarEmpresa)}
                sx={{ display: "flex", flexDirection: "column", gap: 2 }}
              >
                <Box sx={{ display: "flex", gap: 2 }}>
                  <Controller
                    name="ruc"
                    control={control}
                    rules={{
                      required: "RUC es obligatorio",
                      minLength: { value: 3, message: "Mínimo 3 dígitos" },
                    }}
                    render={({ field }) => (
                      <TextField
                        {...field}
                        label="RUC"
                        placeholder="12345678"
                        fullWidth
                        autoFocus
                        error={!!errors.ruc}
                        helperText={errors.ruc?.message}
                        inputProps={{ maxLength: 8 }}
                        InputProps={{
                          startAdornment: (
                            <InputAdornment position="start">
                              <Business color="action" />
                            </InputAdornment>
                          ),
                        }}
                      />
                    )}
                  />
                  <Controller
                    name="dv"
                    control={control}
                    rules={{ required: "DV requerido" }}
                    render={({ field }) => (
                      <TextField
                        {...field}
                        label="DV"
                        placeholder="1"
                        sx={{ width: 80 }}
                        error={!!errors.dv}
                        inputProps={{ maxLength: 1 }}
                      />
                    )}
                  />
                </Box>

                <Controller
                  name="razon_social"
                  control={control}
                  rules={{
                    required: "Razón social es obligatoria",
                    minLength: { value: 4, message: "Mínimo 4 caracteres" },
                  }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="Razón Social"
                      placeholder="Mi Empresa S.A."
                      fullWidth
                      error={!!errors.razon_social}
                      helperText={errors.razon_social?.message}
                    />
                  )}
                />

                <Controller
                  name="nombre_fantasia"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="Nombre Fantasía (opcional)"
                      placeholder="Mi Tienda"
                      fullWidth
                    />
                  )}
                />

                <Controller
                  name="email"
                  control={control}
                  rules={{
                    required: "Email es obligatorio",
                    pattern: {
                      value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
                      message: "Email inválido",
                    },
                  }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="Email"
                      type="email"
                      placeholder="email@ejemplo.com"
                      fullWidth
                      error={!!errors.email}
                      helperText={errors.email?.message}
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <Email color="action" />
                          </InputAdornment>
                        ),
                      }}
                    />
                  )}
                />

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

                <Controller
                  name="confirmar_password"
                  control={control}
                  rules={{
                    required: "Confirme su contraseña",
                    validate: (value) =>
                      value === password || "Las contraseñas no coinciden",
                  }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="Confirmar Contraseña"
                      type={showConfirmPassword ? "text" : "password"}
                      fullWidth
                      error={!!errors.confirmar_password}
                      helperText={errors.confirmar_password?.message}
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <Lock color="action" />
                          </InputAdornment>
                        ),
                        endAdornment: (
                          <InputAdornment position="end">
                            <IconButton
                              onClick={() =>
                                setShowConfirmPassword(!showConfirmPassword)
                              }
                              edge="end"
                              size="small"
                            >
                              {showConfirmPassword ? (
                                <VisibilityOff />
                              ) : (
                                <Visibility />
                              )}
                            </IconButton>
                          </InputAdornment>
                        ),
                      }}
                    />
                  )}
                />

                <Button
                  type="submit"
                  variant="contained"
                  size="large"
                  fullWidth
                  disabled={isPendingRegistro}
                  sx={{ py: 1.5, mt: 1, fontWeight: 600 }}
                >
                  {isPendingRegistro ? (
                    <CircularProgress size={24} color="inherit" />
                  ) : (
                    "Registrar Empresa"
                  )}
                </Button>
              </Box>
            </>
          )}

          {/* Paso 4: Completado */}
          {step === 4 && (
            <Box sx={{ textAlign: "center", py: 4 }}>
              <Box
                sx={{
                  width: 80,
                  height: 80,
                  borderRadius: "50%",
                  bgcolor: "success.main",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  mx: "auto",
                  mb: 3,
                }}
              >
                <CheckCircle sx={{ fontSize: 48, color: "white" }} />
              </Box>
              <Typography variant="h5" fontWeight={600} gutterBottom>
                ¡Registro Exitoso!
              </Typography>
              <Typography variant="body2" color="text.secondary">
                Tu empresa ha sido registrada correctamente.
              </Typography>
              <LinearProgress sx={{ mt: 3 }} />
              <Typography
                variant="caption"
                color="text.secondary"
                sx={{ mt: 1, display: "block" }}
              >
                Redirigiendo al login...
              </Typography>
            </Box>
          )}
        </Paper>

        {/* Footer */}
        <Typography
          variant="caption"
          color="text.secondary"
          sx={{ mt: 4, textAlign: "center" }}
        >
          © 2024 Smart POS. 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>
      </Box>
    </Container>
  );
}

const Container = styled.div`
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: ${({ theme }) => theme.bgtotal};
  padding: 20px;
`;
