import { Person } from "@mui/icons-material";
import {
  Autocomplete,
  Box,
  Chip,
  CircularProgress,
  TextField,
  Typography,
} from "@mui/material";
import { useCallback, useEffect, useState } from "react";
import { searchProveedoresCompra } from "../../../api/compras.service";
import { searchProveedores } from "../../../api/proveedores.service";
import { useRubroStore } from "../../../store/RubroStore";

const getProveedorLabel = (proveedor) => {
  if (!proveedor) return "";
  return proveedor?.personas?.razon_social || proveedor?.razon_social || "Sin nombre";
};

export const ProveedorSelector = ({
  value = null,
  onChange,
  label = "Proveedor",
  required = false,
  disabled = false,
  size = "small",
  fullWidth = true,
  minWidth = 240,
  // "compra" (default) excluye ACREEDOR_VARIO. "gasto" o "todos" incluye todo.
  contexto = "compra",
  tipoEntidad = null,
  // Filtro por rubro. Por defecto sigue el rubro que el usuario tiene elegido en
  // el header; se pasa `false` para ignorarlo cuando la pantalla necesita ver
  // todos los proveedores. Ver docs/plan-rubros-multi-sucursal.md en el backend.
  filtrarPorRubro = true,
}) => {
  const rubroSeleccionado = useRubroStore((state) => state.rubroId);
  const rubroId = filtrarPorRubro ? rubroSeleccionado : null;
  const [options, setOptions] = useState([]);
  const [inputValue, setInputValue] = useState("");
  const [searchTerm, setSearchTerm] = useState("");
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    setInputValue(getProveedorLabel(value));
    if (value?.id) {
      setOptions((prev) =>
        prev.some((opt) => opt.id === value.id) ? prev : [value, ...prev],
      );
    }
  }, [value]);

  const runSearch = useCallback(async (term) => {
    if (disabled) return;
    try {
      setIsLoading(true);
      if (contexto === "compra") {
        const resp = await searchProveedoresCompra(term.trim(), 20, rubroId);
        setOptions(resp?.items || []);
      } else {
        const items = await searchProveedores(term.trim(), 20, tipoEntidad, rubroId);
        setOptions(items || []);
      }
    } catch {
      setOptions((prev) => prev);
    } finally {
      setIsLoading(false);
    }
  }, [disabled, contexto, tipoEntidad, rubroId]);

  useEffect(() => {
    if (disabled) return undefined;
    const timeout = setTimeout(() => runSearch(searchTerm), 320);
    return () => clearTimeout(timeout);
  }, [searchTerm, disabled, runSearch]);

  // Si cambia el rubro en el header, las opciones cargadas son del rubro anterior.
  useEffect(() => {
    setOptions((prev) => (value?.id ? prev.filter((o) => o.id === value.id) : []));
  }, [rubroId, value?.id]);

  const noOptionsText = "No se encontraron proveedores";

  return (
    <Autocomplete
      sx={{
        width: "100%",
        minWidth,
        "& .MuiAutocomplete-inputRoot": { minHeight: size === "small" ? 40 : 48 },
      }}
      value={value}
      onChange={(event, newValue) => onChange?.(newValue)}
      options={options}
      getOptionLabel={(option) => getProveedorLabel(option)}
      isOptionEqualToValue={(option, selected) => option?.id === selected?.id}
      loading={isLoading}
      disabled={disabled}
      size={size}
      fullWidth={fullWidth}
      filterOptions={(x) => x}
      inputValue={inputValue}
      onInputChange={(event, nextValue, reason) => {
        setInputValue(nextValue);
        if (reason === "input") {
          setSearchTerm(nextValue);
          onChange?.(null);
        }
        if (reason === "clear") {
          setSearchTerm("");
          onChange?.(null);
        }
      }}
      onOpen={() => {
        // Pre-cargar inmediatamente al abrir; si ya hay opciones no recarga.
        if (!options.length) runSearch(searchTerm);
      }}
      renderOption={(props, option) => {
        const tipoLabel =
          option?.tipo_entidad === "PROVEEDOR_EXTERIOR"
            ? { label: "Exterior", color: "info" }
            : option?.tipo_entidad === "ACREEDOR_VARIO"
              ? { label: "Acreedor", color: "warning" }
              : { label: "Local", color: "primary" };
        return (
          <Box component="li" {...props} key={option.id}>
            <Box sx={{ display: "flex", alignItems: "center", gap: 1, width: "100%" }}>
              <Person fontSize="small" color="action" />
              <Box sx={{ flex: 1, minWidth: 0 }}>
                <Typography
                  variant="body2"
                  sx={{ fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}
                >
                  {option?.personas?.razon_social || "Sin nombre"}
                </Typography>
                <Typography
                  variant="caption"
                  color="text.secondary"
                  sx={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", display: "block" }}
                >
                  {option?.personas?.ruc
                    ? `${option.personas.ruc}-${option.personas.dv || 0}`
                    : option?.personas?.nro_documento || "Sin documento"}
                </Typography>
              </Box>
              <Chip
                label={tipoLabel.label}
                color={tipoLabel.color}
                size="small"
                variant="outlined"
                sx={{ height: 20, fontSize: "0.65rem", flexShrink: 0 }}
              />
            </Box>
          </Box>
        );
      }}
      renderInput={(params) => (
        <TextField
          {...params}
          label={label}
          required={required}
          placeholder="Buscar por nombre, RUC o documento..."
          InputProps={{
            ...params.InputProps,
            startAdornment: (
              <>
                <Person
                  fontSize="small"
                  color="action"
                  sx={{ ml: 0.5, mr: 0.5 }}
                />
                {params.InputProps.startAdornment}
              </>
            ),
            endAdornment: (
              <>
                {isLoading ? <CircularProgress color="inherit" size={16} /> : null}
                {params.InputProps.endAdornment}
              </>
            ),
          }}
        />
      )}
      noOptionsText={noOptionsText}
      loadingText="Cargando..."
    />
  );
};

export default ProveedorSelector;
