import { Settings } from "@mui/icons-material";
import {
  Box,
  Divider,
  FormControlLabel,
  Paper,
  Switch,
  Typography,
} from "@mui/material";
import { MonedaInput } from "../common/MonedaInput";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useRef, useState } from "react";
import { toast } from "sonner";
import { updateEmpresa } from "../../api/empresas.service";
import { useEmpresa } from "../../context/EmpresaContext";

export function OrdenesVentaConfigTab() {
  const { empresa, empresaId, refetch } = useEmpresa();
  const queryClient = useQueryClient();

  const [requiereAprobacion, setRequiereAprobacion] = useState(
    () => Boolean(empresa?.orden_requiere_aprobacion),
  );
  const [montoAprobacion, setMontoAprobacion] = useState(
    () => empresa?.orden_monto_aprobacion || 0,
  );
  const [facturarSinOv, setFacturarSinOv] = useState(
    () => Boolean(empresa?.presupuesto_facturar_sin_ov),
  );
  const [savingField, setSavingField] = useState(null);
  const lastSavedMonto = useRef(empresa?.orden_monto_aprobacion || 0);

  const mutation = useMutation({
    mutationFn: (data) => updateEmpresa(empresaId, data),
    onSuccess: () => {
      toast.success("Guardado");
      queryClient.invalidateQueries({ queryKey: ["empresa"] });
      refetch();
    },
    onError: (e) => {
      toast.error(e?.response?.data?.message || "Error al guardar");
    },
    onSettled: () => setSavingField(null),
  });

  const save = (field, patch) => {
    setSavingField(field);
    mutation.mutate(patch);
  };

  return (
    <Paper sx={{ p: { xs: 2, sm: 3 } }}>
      <Typography
        variant="h6"
        sx={{ display: "flex", alignItems: "center", gap: 1, mb: 0.5 }}
      >
        <Settings color="primary" />
        Órdenes de Venta — Configuración Global
      </Typography>
      <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
        Estos parámetros aplican a toda la empresa y controlan el comportamiento
        del módulo de Órdenes de Venta.
      </Typography>
      <Divider sx={{ mb: 3 }} />

      {/* Aprobación */}
      <Typography
        variant="h6"
        sx={{ display: "flex", alignItems: "center", gap: 1, mb: 1 }}
      >
        <Settings /> Control de Aprobación
      </Typography>
      <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
        Requiere aprobación de un supervisor antes de que una orden pueda pasar
        a estado "En Proceso".
      </Typography>

      <Paper variant="outlined" sx={{ p: 2 }}>
        <Box sx={{ display: "grid", gap: 2 }}>
          <Box
            sx={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 2 }}
          >
            <Box>
              <Typography variant="subtitle1" fontWeight={500}>
                Requiere aprobación
              </Typography>
              <Typography variant="body2" color="text.secondary">
                Las órdenes confirmadas esperan aprobación de un supervisor antes de procesarse.
              </Typography>
            </Box>
            <FormControlLabel
              control={
                <Switch
                  checked={requiereAprobacion}
                  onChange={(e) => {
                    setRequiereAprobacion(e.target.checked);
                    save("switch", { orden_requiere_aprobacion: e.target.checked });
                  }}
                  disabled={savingField === "switch"}
                />
              }
              label={requiereAprobacion ? "Activado" : "Desactivado"}
              labelPlacement="start"
            />
          </Box>

          {requiereAprobacion && (
            <Box
              sx={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 2, flexWrap: "wrap" }}
            >
              <Box sx={{ flex: 1, minWidth: 200 }}>
                <Typography variant="subtitle1" fontWeight={500}>
                  Monto mínimo para aprobación
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  Solo las órdenes que superen este monto requerirán aprobación. Ingrese 0 para requerir siempre.
                </Typography>
              </Box>
              <MonedaInput
                value={Number(montoAprobacion)}
                onChange={(v) => setMontoAprobacion(v)}
                onBlur={() => {
                  const v = Number(montoAprobacion);
                  if (v !== lastSavedMonto.current) {
                    lastSavedMonto.current = v;
                    save("monto", { orden_monto_aprobacion: v });
                  }
                }}
                moneda="PYG"
                label="Monto mínimo"
                sx={{ width: 200 }}
                disabled={savingField === "monto"}
              />
            </Box>
          )}
        </Box>
      </Paper>

      {/* Facturación de presupuestos */}
      <Typography
        variant="h6"
        sx={{ display: "flex", alignItems: "center", gap: 1, mt: 4, mb: 1 }}
      >
        <Settings /> Facturación de Presupuestos
      </Typography>
      <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
        Controla si un presupuesto aceptado debe pasar obligatoriamente por una
        Orden de Venta antes de facturarse.
      </Typography>

      <Paper variant="outlined" sx={{ p: 2 }}>
        <Box
          sx={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 2 }}
        >
          <Box>
            <Typography variant="subtitle1" fontWeight={500}>
              Facturar presupuesto sin Orden de Venta
            </Typography>
            <Typography variant="body2" color="text.secondary">
              Permite facturar un presupuesto aceptado directamente desde el POS.
              Desactivado, el presupuesto primero debe convertirse en Orden de Venta.
            </Typography>
          </Box>
          <FormControlLabel
            control={
              <Switch
                checked={facturarSinOv}
                onChange={(e) => {
                  setFacturarSinOv(e.target.checked);
                  save("facturarSinOv", { presupuesto_facturar_sin_ov: e.target.checked });
                }}
                disabled={savingField === "facturarSinOv"}
              />
            }
            label={facturarSinOv ? "Activado" : "Desactivado"}
            labelPlacement="start"
          />
        </Box>
      </Paper>
    </Paper>
  );
}
