/* eslint-disable react/prop-types */
import { Icon } from "@iconify/react";
import { LocationOn, ExpandMore, InfoOutlined } from "@mui/icons-material";
import {
  Accordion,
  AccordionDetails,
  AccordionSummary,
  Alert,
  Autocomplete,
  Box,
  Button,
  Chip,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Divider,
  FormControl,
  FormControlLabel,
  FormHelperText,
  IconButton,
  InputAdornment,
  Switch,
  InputLabel,
  MenuItem,
  Select,
  Tab,
  Tabs,
  TextField,
  Typography,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import { TourTrigger } from "../../../tours/components/TourTrigger";
import { clienteFormSteps } from "../../../tours/definitions/clientesTour";
import { useQuery } from "@tanstack/react-query";
import { useEffect, useMemo, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { getListasEmpresa } from "../../../api";
import { getDirecciones } from "../../../api/clientes.service";
import { buscarPersonaPorRuc } from "../../../api/personas.service";
import { useDnitAutofillRHF } from "../../../hooks/useDnitAutofillRHF";
import { usePermission } from "../../../hooks/usePermission";
import { useCreateClienteMutation, useUpdateClienteMutation } from "../../../tanstack/ClientesStack";
import { useReferencialesQuery } from "../../../tanstack/ReferencialesStack";
import { FieldHint, MonedaInput, SwitchConAyuda } from "../../_standards";
import { getEmpresaMonedas } from "../../../api/monedas.service";
import { ClienteDireccionesPanel } from "./ClienteDireccionesPanel";

const TIPOS_CLIENTE = [
  { value: "minorista", label: "Minorista" },
  { value: "mayorista", label: "Mayorista" },
  { value: "distribuidor", label: "Distribuidor" },
];

export const ClienteFormDialog = ({ open, onClose, cliente }) => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("md"));
  const isEdit = !!cliente;
  const [activeTab, setActiveTab] = useState(0);

  const { data: referenciales } = useReferencialesQuery();
  const createMutation = useCreateClienteMutation();
  const updateMutation = useUpdateClienteMutation();
  const { can: canVentas } = usePermission("VENTAS");
  const canReadLP = canVentas("VEN_LISTA_VER");
  const canCreateLP = canVentas("VEN_LISTA_CREAR");

  const tiposDocumento = referenciales?.tipo_documento_identidad || [];
  const naturalezas = referenciales?.naturaleza_receptor || [];
  const tiposContribuyente = referenciales?.tipo_contribuyente || [];
  const tiposOperacion = referenciales?.tipo_operacion || [];

  const {
    control,
    handleSubmit,
    reset,
    watch,
    setValue,
    setError,
    formState: { errors },
  } = useForm({
    defaultValues: {
      tipo_documento_id: null,
      naturaleza_id: null,
      tipo_contribuyente_id: null,
      razon_social: "",
      ruc: "",
      dv: "",
      nro_documento: "",
      telefono: "",
      celular: "",
      email: "",
      otro_tipo_documento: "",
      tipo_operacion_id: "",
      nombre_fantasia: "",
      cod_cliente: "",
      tipo_cliente: "",
      lista_precios_id: "",
      zona: "",
      es_agente_retencion: false,
      // Cliente nuevo: vende a crédito sin tope. Poner un tope es una decisión
      // posterior, no un requisito para poder facturarle.
      credito_habilitado: true,
      limite_credito: 0,
      moneda_credito: "PYG",
      dias_mora_maximo: "",
      bloqueado_credito: false,
    },
  });

  // La moneda del límite define el formato del monto y qué crédito se compara
  // contra el total de la factura.
  const monedaCredito = watch("moneda_credito");
  // Apaga el tope, la moneda, la mora y el bloqueo: sin venta a crédito no hay
  // nada que configurar debajo.
  const creditoHabilitado = watch("credito_habilitado");
  const { data: monedasData } = useQuery({
    queryKey: ["empresaMonedas"],
    queryFn: getEmpresaMonedas,
  });
  const monedasEmpresa = Array.isArray(monedasData?.data) ? monedasData.data : Array.isArray(monedasData) ? monedasData : [];

  const { data: listasData } = useQuery({
    queryKey: ["listas-precios-select"],
    queryFn: () => getListasEmpresa(null, { activa: true }, 1, 100),
    enabled: canReadLP,
  });
  const listasPrecios = listasData?.data || [];

  const { data: direccionesData = [] } = useQuery({
    queryKey: ["cliente-direcciones", cliente?.id],
    queryFn: () => getDirecciones(cliente.id),
    enabled: isEdit && !!cliente?.id,
    staleTime: 30000,
  });
  const direccionPrincipal = direccionesData.find((d) => d.es_principal) || direccionesData[0] || null;

  const watchNaturaleza = watch("naturaleza_id");
  const watchTipoDocumento = watch("tipo_documento_id");
  const watchRuc = watch("ruc");

  const selectedNaturaleza = useMemo(() => naturalezas.find((n) => n.id === watchNaturaleza), [naturalezas, watchNaturaleza]);
  const selectedTipoDocumento = useMemo(() => tiposDocumento.find((t) => t.id === watchTipoDocumento), [tiposDocumento, watchTipoDocumento]);

  const isContribuyente = selectedNaturaleza?.codigo === 1;
  const isNoContribuyente = selectedNaturaleza?.codigo === 2;
  const isOtroTipoDocumento = selectedTipoDocumento?.codigo === 9;
  const isTarjetaDiplomatica = selectedTipoDocumento?.codigo === 6;

  // Detección de RUC ya registrado (como cliente y/o proveedor) para poder
  // autocompletar en vez de obligar a retipear todos los datos de la persona.
  const [rucMatch, setRucMatch] = useState(null);
  useEffect(() => {
    if (!open) setRucMatch(null);
  }, [open]);

  useEffect(() => {
    if (isEdit || !isContribuyente) {
      setRucMatch(null);
      return;
    }
    const rucNormalizado = String(watchRuc || "").replace(/\D/g, "");
    if (rucNormalizado.length < 3) {
      setRucMatch(null);
      return;
    }
    let cancelado = false;
    const timeout = setTimeout(async () => {
      try {
        const resultado = await buscarPersonaPorRuc(rucNormalizado);
        if (!cancelado) setRucMatch(resultado?.encontrado ? resultado : null);
      } catch {
        if (!cancelado) setRucMatch(null);
      }
    }, 500);
    return () => {
      cancelado = true;
      clearTimeout(timeout);
    };
  }, [watchRuc, isEdit, isContribuyente]);

  // ── Autocompletado DNIT (SIFEN/Padrón) automático — lógica compartida ──
  const { loadingDnit, dnitInfo } = useDnitAutofillRHF({ open, isEdit, watch, setValue, naturalezas, tiposDocumento });

  const aplicarDatosPersonaExistente = () => {
    const persona = rucMatch?.persona;
    if (!persona) return;
    setValue("tipo_documento_id", persona.tipo_documento_identidad?.id || null, { shouldDirty: true });
    setValue("naturaleza_id", persona.naturaleza_receptor?.id || null, { shouldDirty: true });
    setValue("tipo_contribuyente_id", persona.tipo_contribuyente?.id || null, { shouldDirty: true });
    setValue("razon_social", persona.razon_social || "", { shouldDirty: true });
    setValue("dv", persona.dv || "", { shouldDirty: true });
    setValue("nro_documento", persona.nro_documento || "", { shouldDirty: true });
    setValue("telefono", persona.telefono || "", { shouldDirty: true });
    setValue("celular", persona.celular || "", { shouldDirty: true });
    setValue("email", persona.email || "", { shouldDirty: true });
    setValue("otro_tipo_documento", persona.otro_tipo_documento || "", { shouldDirty: true });
    setRucMatch(null);
  };

  const tipoContribuyenteCalculado = useMemo(() => {
    if (!watchRuc || !isContribuyente) return null;
    const rucNum = parseInt(watchRuc, 10);
    if (isNaN(rucNum)) return null;
    const codigoBuscado = rucNum >= 80000000 ? 2 : 1;
    return tiposContribuyente.find((t) => t.codigo === codigoBuscado);
  }, [watchRuc, isContribuyente, tiposContribuyente]);

  const tiposOperacionFiltrados = useMemo(() => {
    if (isTarjetaDiplomatica) {
      return tiposOperacion.filter((t) => t.codigo === 4);
    }
    if (isContribuyente) {
      return tiposOperacion.filter((t) => t.codigo === 1 || t.codigo === 3);
    }
    if (isNoContribuyente) {
      return tiposOperacion.filter((t) => t.codigo === 2 || t.codigo === 4);
    }
    return tiposOperacion;
  }, [tiposOperacion, isContribuyente, isNoContribuyente, isTarjetaDiplomatica]);

  useEffect(() => {
    if (isTarjetaDiplomatica) {
      const tipoB2F = tiposOperacion.find((t) => t.codigo === 4);
      if (tipoB2F) setValue("tipo_operacion_id", tipoB2F.id);
    }
  }, [isTarjetaDiplomatica, referenciales, setValue]);

  useEffect(() => {
    if (isTarjetaDiplomatica) return;
    if (isContribuyente) {
      const b2b = tiposOperacion.find((t) => t.codigo === 1);
      if (b2b) setValue("tipo_operacion_id", b2b.id);
    } else if (isNoContribuyente) {
      const b2c = tiposOperacion.find((t) => t.codigo === 2);
      if (b2c) setValue("tipo_operacion_id", b2c.id);
    } else {
      setValue("tipo_operacion_id", "");
    }
  }, [isContribuyente, isNoContribuyente, isTarjetaDiplomatica, tiposOperacion, setValue]);

  useEffect(() => {
    if (cliente) {
      const persona = cliente.personas || {};
      reset({
        tipo_documento_id: persona.tipo_documento_identidad?.id || null,
        naturaleza_id: persona.naturaleza_receptor?.id || null,
        tipo_contribuyente_id: persona.tipo_contribuyente?.id || null,
        razon_social: persona.razon_social || "",
        ruc: persona.ruc || "",
        dv: persona.dv || "",
        nro_documento: persona.nro_documento || "",
        telefono: persona.telefono || "",
        celular: persona.celular || "",
        email: persona.email || "",
        otro_tipo_documento: persona.otro_tipo_documento || "",
        tipo_operacion_id: cliente.tipo_operacion?.id || "",
        nombre_fantasia: cliente.nombre_fantasia || "",
        cod_cliente: cliente.cod_cliente || "",
        tipo_cliente: cliente.tipo_cliente || "",
        lista_precios_id: cliente.lista_precios_id || cliente.lista_precios?.id || "",
        zona: cliente.zona || "",
        es_agente_retencion: !!cliente.es_agente_retencion,
        credito_habilitado: cliente.credito_habilitado !== false,
        limite_credito: Number(cliente.limite_credito) || 0,
        moneda_credito: cliente.moneda_credito || "PYG",
        dias_mora_maximo: cliente.dias_mora_maximo ?? "",
        bloqueado_credito: !!cliente.bloqueado_credito,
      });
    } else {
      // Arranca como NO CONTRIBUYENTE con Cédula preseleccionada: el usuario tipea el
      // Nro. de Documento primero y la consulta a la DNIT decide si es contribuyente.
      const noContribDefault = naturalezas.find((n) => Number(n.codigo) === 2);
      const cedulaDefault = tiposDocumento.find((td) => Number(td.codigo) === 1);
      reset({
        tipo_documento_id: cedulaDefault?.id || null,
        naturaleza_id: noContribDefault?.id || null,
        tipo_contribuyente_id: null,
        razon_social: "",
        ruc: "",
        dv: "",
        nro_documento: "",
        telefono: "",
        celular: "",
        email: "",
        otro_tipo_documento: "",
        tipo_operacion_id: "",
        nombre_fantasia: "",
        cod_cliente: "",
        tipo_cliente: "",
        lista_precios_id: "",
        zona: "",
        es_agente_retencion: false,
        // Cliente nuevo: vende a crédito sin tope. Poner un tope es una decisión
        // posterior, no un requisito para poder facturarle.
        credito_habilitado: true,
        limite_credito: 0,
        moneda_credito: "PYG",
        dias_mora_maximo: "",
        bloqueado_credito: false,
      });
    }
  }, [cliente, reset, referenciales]);

  const handleClose = () => {
    reset();
    setActiveTab(0);
    onClose();
  };

  const onSubmit = (data) => {
    const tipoContribuyenteId = tipoContribuyenteCalculado?.id || data.tipo_contribuyente_id;
    // Enviamos SOLO el documento que corresponde a la naturaleza final: contribuyente
    // usa RUC+DV (sin nro_documento/tipo_documento); no contribuyente usa
    // tipo_documento+nro_documento (sin RUC/DV). Evita datos cruzados si el usuario cambió de tipo.
    const esContrib = Number(naturalezas.find((n) => n.id === data.naturaleza_id)?.codigo) === 1;

    const payload = {
      tipo_documento_id: esContrib ? null : data.tipo_documento_id || null,
      naturaleza_id: data.naturaleza_id || null,
      tipo_contribuyente_id: tipoContribuyenteId || null,
      razon_social: data.razon_social,
      ruc: esContrib ? data.ruc || null : null,
      dv: esContrib && data.dv ? Number(data.dv) : null,
      nro_documento: !esContrib ? data.nro_documento || undefined : undefined,
      telefono: data.telefono || undefined,
      celular: data.celular || undefined,
      email: data.email || undefined,
      otro_tipo_documento: data.otro_tipo_documento || undefined,
      tipo_operacion_id: data.tipo_operacion_id,
      nombre_fantasia: data.nombre_fantasia || undefined,
      cod_cliente: data.cod_cliente || undefined,
      tipo_cliente: data.tipo_cliente || undefined,
      lista_precios_id: data.lista_precios_id || undefined,
      zona: data.zona || undefined,
      es_agente_retencion: !!data.es_agente_retencion,
      // Crédito: el flag decide si se le vende a crédito; el límite es el tope
      // y vacío significa sin tope. Los días de mora solo si se cargaron.
      credito_habilitado: !!data.credito_habilitado,
      limite_credito: Number(data.limite_credito) || undefined,
      moneda_credito: data.moneda_credito || undefined,
      dias_mora_maximo: data.dias_mora_maximo === "" || data.dias_mora_maximo === null ? undefined : Number(data.dias_mora_maximo),
      bloqueado_credito: !!data.bloqueado_credito,
    };

    const handleConflict = (error) => {
      const raw = error?.response?.data?.message;
      const msg = Array.isArray(raw) ? raw.join(" | ") : raw || "";
      const lower = msg.toLowerCase();
      if (lower.includes("ruc")) {
        setError("ruc", { type: "server", message: msg });
      } else if (lower.includes("documento")) {
        setError("nro_documento", { type: "server", message: msg });
      }
    };

    if (isEdit) {
      updateMutation.mutate({ id: cliente.id, data: payload }, { onSuccess: handleClose, onError: handleConflict });
    } else {
      createMutation.mutate(payload, { onSuccess: handleClose, onError: handleConflict });
    }
  };

  const isPending = createMutation.isPending || updateMutation.isPending;

  return (
    <Dialog open={open} onClose={handleClose} maxWidth="md" fullWidth fullScreen={isMobile} PaperProps={{ sx: { borderRadius: 2 } }}>
      <DialogTitle sx={{ display: "flex", alignItems: "center", gap: 1.25 }}>
        <Box
          sx={{
            width: "2.2rem", height: "2.2rem", borderRadius: "10px",
            bgcolor: "action.hover", display: "flex", alignItems: "center", justifyContent: "center",
            color: "primary.main", flexShrink: 0,
          }}
        >
          <Icon icon={isEdit ? "lucide:user-cog" : "lucide:user-plus"} width={20} />
        </Box>
        <Box sx={{ flex: 1, minWidth: 0 }}>
          <Typography variant="subtitle1" fontWeight={700} lineHeight={1.2}>
            {isEdit ? "Editar Cliente" : "Nuevo Cliente"}
          </Typography>
          <Typography variant="caption" color="text.secondary" noWrap>
            {isEdit ? cliente?.personas?.razon_social : "Registrá un nuevo cliente para facturar y gestionar cuentas"}
          </Typography>
        </Box>
        <TourTrigger steps={clienteFormSteps} tourKey="cliente-form" />
        <IconButton onClick={handleClose} size="small">
          <Icon icon="lucide:x" width={18} />
        </IconButton>
      </DialogTitle>

      <Tabs value={activeTab} onChange={(_, v) => setActiveTab(v)} sx={{ px: 3, borderBottom: 1, borderColor: "divider" }}>
        <Tab label="Datos" />
        <Tab label="Direcciones" disabled={!isEdit} />
      </Tabs>

      {activeTab === 0 && (
        <form onSubmit={handleSubmit(onSubmit)}>
          <DialogContent dividers>
            <Accordion sx={{ mb: 2, bgcolor: "info.lighter", "&:before": { display: "none" } }} elevation={0} variant="outlined">
              <AccordionSummary expandIcon={<ExpandMore />}>
                <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                  <InfoOutlined fontSize="small" color="info" />
                  <Typography variant="subtitle2">Consideraciones para registrar el cliente (validaciones SIFEN)</Typography>
                </Box>
              </AccordionSummary>
              <AccordionDetails>
                <Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
                  <Box>
                    <Typography variant="caption" color="text.secondary" fontWeight={700}>
                      Datos generales
                    </Typography>
                    <ul style={{ margin: "4px 0 0", paddingLeft: 18 }}>
                      <li>
                        <Typography variant="caption">Razón social: entre 4 y 255 caracteres.</Typography>
                      </li>
                      <li>
                        <Typography variant="caption">Dirección (si se informa): entre 4 y 255 caracteres.</Typography>
                      </li>
                      <li>
                        <Typography variant="caption">Celular: entre 10 y 20 caracteres. Teléfono: entre 6 y 20.</Typography>
                      </li>
                      <li>
                        <Typography variant="caption">Email: entre 3 y 80 caracteres y formato válido.</Typography>
                      </li>
                    </ul>
                  </Box>
                  <Box>
                    <Typography variant="caption" color="text.secondary" fontWeight={700}>
                      Si es Contribuyente
                    </Typography>
                    <ul style={{ margin: "4px 0 0", paddingLeft: 18 }}>
                      <li>
                        <Typography variant="caption">RUC: solo dígitos, entre 3 y 8 caracteres (sin DV).</Typography>
                      </li>
                      <li>
                        <Typography variant="caption">DV: un dígito numérico (0-9).</Typography>
                      </li>
                      <li>
                        <Typography variant="caption">Tipo de contribuyente: obligatorio.</Typography>
                      </li>
                      <li>
                        <Typography variant="caption">Tipo de operación permitido: B2B o B2F.</Typography>
                      </li>
                    </ul>
                  </Box>
                  <Box>
                    <Typography variant="caption" color="text.secondary" fontWeight={700}>
                      Si es No Contribuyente
                    </Typography>
                    <ul style={{ margin: "4px 0 0", paddingLeft: 18 }}>
                      <li>
                        <Typography variant="caption">Tipo de documento: obligatorio.</Typography>
                      </li>
                      <li>
                        <Typography variant="caption">Número de documento: entre 1 y 20 caracteres.</Typography>
                      </li>
                      <li>
                        <Typography variant="caption">Si tipo doc = "Otro": describir el documento (entre 9 y 41 caracteres).</Typography>
                      </li>
                      <li>
                        <Typography variant="caption">Si tipo doc = "Tarjeta Diplomática": dirección obligatoria y país distinto de Paraguay; tipo operación = B2F.</Typography>
                      </li>
                      <li>
                        <Typography variant="caption">Tipo de operación permitido: B2B o B2C.</Typography>
                      </li>
                    </ul>
                  </Box>
                </Box>
              </AccordionDetails>
            </Accordion>

            <Typography variant="subtitle2" color="primary" gutterBottom>
              Datos de la Persona
            </Typography>

            {rucMatch?.persona && rucMatch.es_cliente && (
              <Alert severity="warning" sx={{ mb: 2 }}>
                Este RUC ya es un <strong>Cliente activo</strong>: {rucMatch.persona.razon_social}. Buscalo en el
                listado de Clientes en vez de crear uno nuevo.
              </Alert>
            )}

            {rucMatch?.persona && !rucMatch.es_cliente && (
              <Alert
                severity="info"
                sx={{ mb: 2 }}
                action={
                  <Button color="inherit" size="small" onClick={aplicarDatosPersonaExistente}>
                    Usar estos datos
                  </Button>
                }
              >
                Este RUC ya existe{rucMatch.es_proveedor ? " como Proveedor" : ""}: <strong>{rucMatch.persona.razon_social}</strong>.
                Podés completar los datos automáticamente en vez de volver a cargarlos.
              </Alert>
            )}

            <Box sx={{ display: "flex", flexDirection: "column", gap: 2, mb: 3 }}>
              {/* Documento PRIMERO: al tipearlo se detecta solo si es contribuyente o no
                  y se completan naturaleza, nombre y demás datos (todo editable). */}
              {isContribuyente && (
                <>
                <Box sx={{ display: "flex", gap: 2 }}>
                  <Controller
                    name="ruc"
                    control={control}
                    rules={{ required: "RUC es obligatorio" }}
                    render={({ field }) => (
                      <TextField
                        {...field}
                        label="RUC *"
                        size="small"
                        fullWidth
                        autoFocus
                        inputProps={{ maxLength: 8 }}
                        error={!!errors.ruc}
                        helperText={errors.ruc?.message || (tipoContribuyenteCalculado ? `Tipo: ${tipoContribuyenteCalculado.descripcion}` : "Se completa automáticamente al reconocer el documento en la DNIT")}
                        InputProps={{
                          endAdornment: loadingDnit ? (
                            <InputAdornment position="end">
                              <CircularProgress size={18} />
                            </InputAdornment>
                          ) : undefined,
                        }}
                      />
                    )}
                  />
                  <Controller
                    name="dv"
                    control={control}
                    rules={{ required: "DV requerido" }}
                    render={({ field }) => <TextField {...field} label="DV *" size="small" sx={{ width: 100 }} inputProps={{ maxLength: 1 }} error={!!errors.dv} helperText={errors.dv?.message} />}
                  />
                </Box>
                {dnitInfo?.encontrado && (
                  <Alert severity="success" icon={<Icon icon="mdi:check-decagram" />} sx={{ py: 0.25 }}>
                    DNIT: <strong>{dnitInfo.razon_social}</strong>
                    {dnitInfo.estado ? ` · ${dnitInfo.estado}` : ""}
                    {dnitInfo.facturador_electronico === "S" ? " · Facturador electrónico" : ""}
                  </Alert>
                )}
                </>
              )}

              {isNoContribuyente && (
                <>
                  <Box sx={{ display: "flex", gap: 2 }}>
                    <Controller
                      name="tipo_documento_id"
                      control={control}
                      rules={{ required: "Tipo documento es requerido" }}
                      render={({ field }) => (
                        <FormControl size="small" sx={{ minWidth: 200 }} error={!!errors.tipo_documento_id}>
                          <InputLabel>Tipo Documento *</InputLabel>
                          <Select {...field} label="Tipo Documento *">
                            {tiposDocumento.map((t) => (
                              <MenuItem key={t.id} value={t.id}>
                                {t.descripcion}
                              </MenuItem>
                            ))}
                          </Select>
                        </FormControl>
                      )}
                    />
                    <Controller
                      name="nro_documento"
                      control={control}
                      rules={{ required: "Nro. documento es obligatorio" }}
                      render={({ field }) => (
                        <TextField
                          {...field}
                          label="Nro. Documento *"
                          size="small"
                          fullWidth
                          autoFocus
                          error={!!errors.nro_documento}
                          helperText={errors.nro_documento?.message || "Con cédula, se completa automáticamente el nombre desde el Padrón"}
                          InputProps={{
                            endAdornment: loadingDnit ? (
                              <InputAdornment position="end">
                                <CircularProgress size={18} />
                              </InputAdornment>
                            ) : undefined,
                          }}
                        />
                      )}
                    />
                  </Box>
                  {dnitInfo?.encontrado && (
                    <Alert severity="success" icon={<Icon icon="mdi:check-decagram" />} sx={{ py: 0.25, mt: 1 }}>
                      Padrón: <strong>{dnitInfo.razon_social}</strong>
                    </Alert>
                  )}

                  {isOtroTipoDocumento && (
                    <Controller
                      name="otro_tipo_documento"
                      control={control}
                      rules={{ required: "Descripción del tipo de documento es obligatoria" }}
                      render={({ field }) => (
                        <TextField {...field} label="Descripción Tipo Documento *" size="small" fullWidth error={!!errors.otro_tipo_documento} helperText={errors.otro_tipo_documento?.message} />
                      )}
                    />
                  )}
                </>
              )}

              {/* Naturaleza (auto-detectada por el documento; editable) y nombre/razón social */}
              <Controller
                name="naturaleza_id"
                control={control}
                rules={{ required: "Naturaleza es requerida" }}
                render={({ field }) => (
                  <FormControl size="small" fullWidth error={!!errors.naturaleza_id}>
                    <InputLabel id="cliente-naturaleza-label" shrink>Naturaleza *</InputLabel>
                    <Select
                      {...field}
                      value={field.value ?? ""}
                      labelId="cliente-naturaleza-label"
                      id="cliente-naturaleza-select"
                      label="Naturaleza *"
                      notched
                    >
                      {naturalezas.map((n) => (
                        <MenuItem key={n.id} value={n.id}>
                          {n.descripcion}
                        </MenuItem>
                      ))}
                    </Select>
                    {errors.naturaleza_id && <FormHelperText>{errors.naturaleza_id.message}</FormHelperText>}
                  </FormControl>
                )}
              />

              <Controller
                name="razon_social"
                control={control}
                rules={{ required: "Este campo es requerido", minLength: { value: 4, message: "Mínimo 4 caracteres" } }}
                render={({ field }) => (
                  <TextField
                    {...field}
                    label={isContribuyente ? "Razón Social *" : "Nombre y Apellido *"}
                    size="small"
                    fullWidth
                    error={!!errors.razon_social}
                    helperText={errors.razon_social?.message}
                  />
                )}
              />
            </Box>

            <Divider sx={{ my: 2 }} />
            <Typography variant="subtitle2" color="primary" gutterBottom>
              Contacto
            </Typography>

            <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr" }, gap: 2, mb: 3 }}>
              <Controller
                name="email"
                control={control}
                rules={{ pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: "Email inválido" } }}
                render={({ field }) => <TextField {...field} label="Email" size="small" fullWidth type="email" error={!!errors.email} helperText={errors.email?.message} />}
              />
              <Controller name="telefono" control={control} render={({ field }) => <TextField {...field} label="Teléfono" size="small" fullWidth />} />
              <Controller name="celular" control={control} render={({ field }) => <TextField {...field} label="Celular" size="small" fullWidth placeholder="595981..." />} />
            </Box>

            {isEdit && (
              <>
                <Divider sx={{ my: 2 }} />
                <Box display="flex" justifyContent="space-between" alignItems="center" mb={1}>
                  <Typography variant="subtitle2" color="primary">
                    Dirección Principal
                  </Typography>
                  <Button size="small" startIcon={<LocationOn fontSize="small" />} onClick={() => setActiveTab(1)}>
                    Gestionar direcciones ({direccionesData.length})
                  </Button>
                </Box>
                {direccionPrincipal ? (
                  <Box sx={{ p: 1.5, borderRadius: 1, border: "1px solid", borderColor: "divider", bgcolor: "action.hover" }}>
                    {direccionPrincipal.label && <Chip label={direccionPrincipal.label} size="small" sx={{ mb: 0.5, fontSize: "0.7rem" }} />}
                    <Typography variant="body2">
                      {[direccionPrincipal.direccion, direccionPrincipal.nro, direccionPrincipal.distritos?.descripcion, direccionPrincipal.ciudades?.descripcion].filter(Boolean).join(", ") ||
                        "Sin detalle"}
                    </Typography>
                    {direccionPrincipal.referencia && (
                      <Typography variant="caption" color="text.secondary">
                        {direccionPrincipal.referencia}
                      </Typography>
                    )}
                  </Box>
                ) : (
                  <Typography variant="body2" color="text.secondary" sx={{ fontStyle: "italic" }}>
                    Sin dirección registrada — usa la pestaña Direcciones para agregar una.
                  </Typography>
                )}
              </>
            )}

            <Divider sx={{ my: 2 }} />
            <Typography variant="subtitle2" color="primary" gutterBottom>
              Datos del Cliente
            </Typography>

            <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr" }, gap: 2 }}>
              <Controller
                name="tipo_operacion_id"
                control={control}
                rules={{ required: "Tipo operación es requerido" }}
                render={({ field }) => (
                  <FormControl size="small" fullWidth error={!!errors.tipo_operacion_id}>
                    <InputLabel>Tipo Operación *</InputLabel>
                    <Select {...field} label="Tipo Operación *">
                      {tiposOperacionFiltrados.map((t) => (
                        <MenuItem key={t.id} value={t.id}>
                          {t.descripcion}
                        </MenuItem>
                      ))}
                    </Select>
                    {errors.tipo_operacion_id && <FormHelperText>{errors.tipo_operacion_id.message}</FormHelperText>}
                  </FormControl>
                )}
              />

              <Controller name="cod_cliente" control={control} render={({ field }) => <TextField {...field} label="Código Cliente" size="small" fullWidth />} />

              <Controller name="nombre_fantasia" control={control} render={({ field }) => <TextField {...field} label="Nombre Fantasía" size="small" fullWidth />} />

              <Controller
                name="tipo_cliente"
                control={control}
                render={({ field }) => (
                  <FormControl size="small" fullWidth>
                    <InputLabel>Tipo Cliente</InputLabel>
                    <Select {...field} label="Tipo Cliente">
                      <MenuItem value="">Sin especificar</MenuItem>
                      {TIPOS_CLIENTE.map((t) => (
                        <MenuItem key={t.value} value={t.value}>
                          {t.label}
                        </MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                )}
              />

              {canReadLP && (
                <Controller
                  name="lista_precios_id"
                  control={control}
                  render={({ field: { onChange, value } }) => (
                    <Autocomplete
                      options={listasPrecios}
                      getOptionLabel={(opt) => (opt ? `${opt.nombre} (${opt.codigo})` : "")}
                      value={listasPrecios.find((lp) => lp.id === value) || null}
                      onChange={(_, newValue) => onChange(newValue?.id || "")}
                      isOptionEqualToValue={(opt, val) => opt.id === val?.id}
                      disabled={!canCreateLP}
                      size="small"
                      renderInput={(params) => <TextField {...params} label="Lista de Precios" helperText={!canCreateLP ? "Sin permiso para asignar" : ""} />}
                    />
                  )}
                />
              )}

              <Controller name="zona" control={control} render={({ field }) => <TextField {...field} label="Zona" size="small" fullWidth placeholder="Ej: Zona Centro, Zona Sur..." />} />

              <Controller
                name="es_agente_retencion"
                control={control}
                render={({ field: { value, onChange } }) => (
                  <FormControlLabel
                    control={<Switch checked={!!value} onChange={(e) => onChange(e.target.checked)} />}
                    label={
                      <Box>
                        <Typography variant="body2">Agente de retención</Typography>
                        <Typography variant="caption" color="text.secondary">
                          Si está activo, al cobrar se ofrecerán automáticamente los campos de retención IVA/Renta.
                        </Typography>
                      </Box>
                    }
                    sx={{ alignItems: "flex-start", m: 0 }}
                  />
                )}
              />
            </Box>

            <Divider sx={{ my: 2 }} />
            <Typography variant="subtitle2" color="primary" gutterBottom>
              Crédito
            </Typography>

            <Controller
              name="credito_habilitado"
              control={control}
              render={({ field: { value, onChange } }) => (
                <SwitchConAyuda
                  checked={!!value}
                  onChange={onChange}
                  label="Vende a crédito"
                  ayuda="Si está apagado, a este cliente solo se le factura al contado. El tope de abajo es opcional."
                  sx={{ ml: 0, mb: 2 }}
                />
              )}
            />

            <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", sm: "1fr 1fr" }, gap: 2 }}>
              <Controller
                name="limite_credito"
                control={control}
                render={({ field }) => (
                  <MonedaInput
                    label="Límite de crédito"
                    value={field.value}
                    onChange={field.onChange}
                    moneda={monedaCredito || "PYG"}
                    fullWidth
                    disabled={!creditoHabilitado}
                    helperText="En 0 no hay tope: el control queda en la mora y el bloqueo. Ej: 5.000.000"
                  />
                )}
              />

              <Controller
                name="moneda_credito"
                control={control}
                render={({ field }) => (
                  <FormControl size="small" fullWidth disabled={!creditoHabilitado}>
                    <InputLabel>Moneda del crédito</InputLabel>
                    <Select {...field} label="Moneda del crédito" disabled={!creditoHabilitado}>
                      {monedasEmpresa.map((m) => (
                        <MenuItem key={m.moneda?.codigo || m.codigo} value={m.moneda?.codigo || m.codigo}>
                          {m.moneda?.codigo || m.codigo} - {m.moneda?.descripcion || m.descripcion}
                        </MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                )}
              />

              <Controller
                name="dias_mora_maximo"
                control={control}
                render={({ field: { ref, ...field } }) => (
                  // FieldHint no usa forwardRef: el ref de RHF va por inputRef,
                  // que TextField sí entiende (si no, React avisa y el foco
                  // automático del formulario en este campo no funciona).
                  <FieldHint
                    {...field}
                    inputRef={ref}
                    label="Días de mora máximo"
                    type="number"
                    fullWidth
                    disabled={!creditoHabilitado}
                    inputProps={{ min: 0 }}
                    hint="Días de atraso tolerados. Vacío = sin control."
                  />
                )}
              />

              <Controller
                name="bloqueado_credito"
                control={control}
                render={({ field: { value, onChange } }) => (
                  <SwitchConAyuda
                    checked={!!value}
                    onChange={onChange}
                    disabled={!creditoHabilitado}
                    label="Crédito bloqueado"
                    ayuda="Freno temporal: bloquea la venta a crédito aunque tenga cupo disponible."
                    sx={{ ml: 0, alignSelf: "center" }}
                  />
                )}
              />
            </Box>
          </DialogContent>

          <DialogActions sx={{ px: 3, py: 2 }}>
            <Button onClick={handleClose}>Cancelar</Button>
            <Button type="submit" variant="contained" disabled={isPending} startIcon={isPending && <CircularProgress size={16} />}>
              {isPending ? "Guardando..." : isEdit ? "Guardar" : "Crear"}
            </Button>
          </DialogActions>
        </form>
      )}

      {activeTab === 1 && (
        <>
          <DialogContent dividers>
            <ClienteDireccionesPanel cliente={cliente} />
          </DialogContent>
          <DialogActions sx={{ px: 3, py: 2 }}>
            <Button onClick={handleClose}>Cerrar</Button>
          </DialogActions>
        </>
      )}
    </Dialog>
  );
};
