import { Icon } from "@iconify/react";
import { Alert, IconButton, Tooltip, Typography } from "@mui/material";
import { useEffect, useMemo, useState } from "react";
import styled from "styled-components";
import { toast } from "sonner";
import {
  actualizarParametro,
  crearParametro,
  eliminarParametro,
  getParametros,
  sembrarRrhhDefaults,
} from "../../api/rrhh.service";
import { useConfirmDialog } from "../../hooks/useConfirmDialog";
import { RRHHGuia } from "./_shared/RRHHGuia";
import { RRHHEmptyState } from "./_shared/RRHHEmptyState";
import { useRRHHContext } from "./_shared/RRHHContext";
import { hoyISO } from "../../utils/fecha";
import {
  Badge,
  Container,
  EmptyState,
  Field,
  FieldsGrid,
  FormHead,
  FormPanel,
  Footer,
  FooterActionButton,
  GhostButton,
  ListBody,
  ListPanel,
  RowActions,
  SectionTitle,
  TableWrap,
  ToolBar,
} from "../ui/FormShell";

const TIPOS_DATO = [
  { value: "NUMERO", label: "Número" },
  { value: "PORCENTAJE", label: "Porcentaje (decimal)" },
  { value: "TEXTO", label: "Texto" },
  { value: "BOOLEANO", label: "Booleano" },
];

const CATEGORIAS = ["IPS", "SMLV", "SUBSIDIO", "LIMITE", "TIEMPO", "CONTROL", "PRESENTISMO", "OTRO"];
const CATEGORIAS_MONETARIAS = new Set(["SMLV", "SUBSIDIO"]);
const HINTS_MONETARIOS = [
  "SMLV",
  "SALARIO",
  "SUELDO",
  "JORNAL",
  "MONTO",
  "REMUNERACION",
  "REMUNERACIÓN",
  "AGUINALDO",
  "BONIFICACION",
  "BONIFICACIÓN",
  "SUBSIDIO",
];

const MoneyInputBox = styled.div`
  min-height: 42px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 12px;
  border: 1px solid ${({ theme }) => theme.color2 || theme.bg4};
  border-radius: 8px;
  background: ${({ theme }) => theme.bg3};
  color: inherit;
  transition: border-color 0.2s, box-shadow 0.2s;

  &:focus-within {
    border-color: ${({ theme }) => theme.primary || "#5b7fff"};
    box-shadow: 0 0 0 3px rgba(125, 211, 168, 0.1);
  }

  span {
    flex: 0 0 auto;
    color: ${({ theme }) => theme.textSecondary || theme.text};
    font-size: 0.86rem;
    font-weight: 700;
  }

  input {
    min-width: 0;
    width: 100%;
    height: 40px;
    border: 0;
    outline: 0;
    background: transparent;
    color: inherit;
    font: inherit;
    font-size: 0.9rem;
    text-align: right;
  }

  input::placeholder {
    color: ${({ theme }) => theme.textSecondary || theme.text};
  }
`;

const todayYmd = () => hoyISO();

const EMPTY = {
  clave: "",
  nombre: "",
  valor: "",
  tipo_dato: "NUMERO",
  categoria: "OTRO",
  editable: true,
  vigencia_desde: todayYmd(),
  vigencia_hasta: "",
};

const stripAccents = (value) => String(value || "").normalize("NFD").replace(/[\u0300-\u036f]/g, "");

const isMoneyParam = (p) => {
  if (String(p.tipo_dato || "").toUpperCase() !== "NUMERO") return false;
  if (CATEGORIAS_MONETARIAS.has(p.categoria)) return true;
  const text = stripAccents(`${p.clave || ""} ${p.nombre || ""}`).toUpperCase();
  return HINTS_MONETARIOS.some((hint) => text.includes(stripAccents(hint).toUpperCase()));
};

const isNumberParam = (p) => String(p.tipo_dato || "").toUpperCase() === "NUMERO";

const moneyRawValue = (value) => {
  const normalized = String(value ?? "").replace(/[^\d.,]/g, "");
  if (!normalized) return "";
  if (normalized.includes(",")) return normalized.split(",")[0].replace(/\D/g, "");
  if (/^\d+\.0{1,2}$/.test(normalized)) return normalized.split(".")[0].replace(/\D/g, "");
  return normalized.replace(/\D/g, "");
};

const formatMoneyInput = (value) => {
  const raw = moneyRawValue(value);
  return raw.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
};

const formatValor = (p) => {
  if (p.tipo_dato === "PORCENTAJE") {
    const n = Number(p.valor);
    if (Number.isFinite(n)) return `${(n * 100).toFixed(2)}%`;
  }
  if (p.tipo_dato === "NUMERO") {
    const n = Number(p.valor);
    if (Number.isFinite(n)) {
      const value = n.toLocaleString("es-PY");
      return isMoneyParam(p) ? `Gs. ${value}` : value;
    }
  }
  if (p.tipo_dato === "BOOLEANO") {
    return p.valor === "true" ? "Sí" : "No";
  }
  return p.valor;
};

const fmtDate = (value) => {
  if (!value) return "—";
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return "—";
  return d.toLocaleDateString("es-PY");
};

// Estado de una versión de parámetro según su ventana de vigencia:
// - PROGRAMADA: empieza en el futuro (aún no rige)
// - HISTORICO: ya expiró (vigencia_hasta pasada)
// - VIGENTE: rige hoy
const estadoVigencia = (p, today = new Date()) => {
  const desde = p.vigencia_desde ? new Date(p.vigencia_desde) : null;
  const hasta = p.vigencia_hasta ? new Date(p.vigencia_hasta) : null;
  if (!desde) return "HISTORICO";
  if (desde > today) return "PROGRAMADA";
  if (hasta && hasta < today) return "HISTORICO";
  return "VIGENTE";
};

const ESTADO_LABEL = { VIGENTE: "Vigente", PROGRAMADA: "Programada", HISTORICO: "Histórico" };

export function ParametrosTab() {
  const { reloadPrereqs } = useRRHHContext();
  const { confirm, dialogs } = useConfirmDialog();
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [seeding, setSeeding] = useState(false);
  const [soloVigentes, setSoloVigentes] = useState(true);
  const [categoriaFiltro, setCategoriaFiltro] = useState("");
  const [editingId, setEditingId] = useState(null);
  const [editingNoEditable, setEditingNoEditable] = useState(false);
  const [form, setForm] = useState(EMPTY);

  const load = async () => {
    try {
      setLoading(true);
      const params = {};
      if (soloVigentes) params.vigente = "true";
      if (categoriaFiltro) params.categoria = categoriaFiltro;
      setData(await getParametros(params));
    } catch {
      toast.error("Error al cargar parámetros");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { load(); /* eslint-disable-next-line */ }, [soloVigentes, categoriaFiltro]);

  const handleSeed = async () => {
    const ok = await confirm({
      title: "Sembrar parámetros y conceptos por defecto",
      message: (
        <div style={{ fontSize: "0.875rem", lineHeight: 1.6 }}>
          <p style={{ margin: "0 0 10px" }}>Se crearán los registros que faltan. <strong>Los que ya existen no serán modificados.</strong></p>
          <p style={{ margin: "0 0 4px", fontWeight: 600 }}>Parámetros legales:</p>
          <ul style={{ margin: "0 0 10px", paddingLeft: 18 }}>
            <li>IPS obrero 9%, IPS patronal 16,5%, IPS administrativo 1%</li>
            <li>SMLV 2026: Gs. 2.550.307</li>
            <li>% base microempresa, límites de descuento</li>
          </ul>
          <p style={{ margin: "0 0 4px", fontWeight: 600 }}>Conceptos de liquidación:</p>
          <ul style={{ margin: 0, paddingLeft: 18 }}>
            <li>SALARIO_BASE, IPS_OBRERO, IPS_PATRONAL</li>
            <li>ANTICIPO_QUINCENAL, HORAS_EXTRA, VACACIONES y otros</li>
          </ul>
        </div>
      ),
      confirmText: "Sembrar",
      confirmColor: "primary",
    });
    if (!ok) return;
    try {
      setSeeding(true);
      const resp = await sembrarRrhhDefaults();
      const p = resp?.parametros || {};
      const c = resp?.conceptos || {};
      toast.success(
        `Listo: ${p.creados || 0} parámetros y ${c.creados || 0} conceptos creados. ${(p.existentes || 0) + (c.existentes || 0)} ya existían y no fueron modificados.`,
      );
      load();
      reloadPrereqs();
    } catch (error) {
      toast.error(error?.response?.data?.message || "Error al sembrar valores por defecto");
    } finally {
      setSeeding(false);
    }
  };

  const handleGuardar = async () => {
    const valorNormalizado = isMoneyParam(form) ? moneyRawValue(form.valor) : form.valor;
    if (!form.clave.trim() || !form.nombre.trim() || valorNormalizado === "") {
      return toast.error("Clave, nombre y valor son requeridos");
    }
    try {
      const payload = {
        ...form,
        valor: valorNormalizado,
        vigencia_hasta: form.vigencia_hasta || undefined,
      };
      if (editingId) {
        await actualizarParametro(editingId, payload);
        toast.success("Parámetro actualizado");
      } else {
        await crearParametro(payload);
        toast.success("Parámetro creado");
      }
      setForm(EMPTY);
      setEditingId(null);
      setEditingNoEditable(false);
      load();
      reloadPrereqs();
    } catch (error) {
      toast.error(error?.response?.data?.message || "Error al guardar parámetro");
    }
  };

  const handleEditar = (p) => {
    setEditingId(p.id);
    setEditingNoEditable(!p.editable);
    setForm({
      clave: p.clave || "",
      nombre: p.nombre || "",
      valor: p.valor ?? "",
      tipo_dato: p.tipo_dato || "NUMERO",
      categoria: p.categoria || "OTRO",
      editable: p.editable ?? true,
      vigencia_desde: p.vigencia_desde ? p.vigencia_desde.slice(0, 10) : todayYmd(),
      vigencia_hasta: p.vigencia_hasta ? p.vigencia_hasta.slice(0, 10) : "",
    });
  };

  const handleEliminar = async (p) => {
    if (!p.editable) {
      return toast.error("Los parámetros legales no editables no pueden eliminarse");
    }
    const ok = await confirm({
      title: "Eliminar parámetro",
      message: `¿Eliminar parámetro "${p.clave}" (vigencia desde ${fmtDate(p.vigencia_desde)})?`,
      confirmText: "Eliminar",
      confirmColor: "error",
    });
    if (!ok) return;
    try {
      await eliminarParametro(p.id);
      toast.success("Parámetro eliminado");
      load();
      reloadPrereqs();
    } catch (error) {
      toast.error(error?.response?.data?.message || "No se pudo eliminar");
    }
  };

  const handleNuevaVersion = (p) => {
    // Crea una nueva versión con vigencia_desde = mañana, copiando el resto
    const manana = new Date();
    manana.setDate(manana.getDate() + 1);
    setEditingId(null);
    setEditingNoEditable(false);
    setForm({
      clave: p.clave,
      nombre: p.nombre,
      valor: p.valor,
      tipo_dato: p.tipo_dato,
      categoria: p.categoria,
      editable: true,
      vigencia_desde: manana.toISOString().slice(0, 10),
      vigencia_hasta: "",
    });
    toast.info("Editá el valor y guardá para registrar la nueva vigencia");
  };

  const updateField = (key, value) => setForm((p) => ({ ...p, [key]: value }));

  const datos = useMemo(() => data, [data]);
  const valorEsNumero = isNumberParam(form);
  const valorEsMoneda = isMoneyParam(form);

  const isEmpty = !loading && datos.length === 0;
  const hayParametros = datos.length > 0;

  return (
    <Container>
      <RRHHGuia seccion="parametros" />
      {isEmpty && (
        <Alert
          severity="info"
          icon={<Icon icon="lucide:sparkles" width={18} />}
          action={
            <FooterActionButton type="button" $variant="primary" disabled={seeding} onClick={handleSeed}>
              <Icon icon="lucide:sparkles" /> {seeding ? "Sembrando..." : "Pre-cargar valores 2026"}
            </FooterActionButton>
          }
        >
          <Typography variant="body2" sx={{ fontWeight: 600 }}>
            No hay parámetros vigentes
          </Typography>
          <Typography variant="caption">
            Podés cargarlos manualmente o usar &quot;Sembrar defaults&quot; para pre-cargar los valores legales 2026 (IPS, SMLV, microempresa). Revisá los valores antes de liquidar.
          </Typography>
        </Alert>
      )}

      <FormPanel>
        <FormHead>
          <SectionTitle>
            <Icon icon={editingId ? "lucide:edit-3" : "lucide:plus-circle"} />
            {editingId ? "Editar parámetro" : "Nuevo parámetro / nueva vigencia"}
          </SectionTitle>
          {(editingId || form.clave) && (
            <GhostButton onClick={() => { setForm(EMPTY); setEditingId(null); setEditingNoEditable(false); }}>
              <Icon icon="lucide:x" /> Limpiar
            </GhostButton>
          )}
        </FormHead>

        {editingNoEditable && (
          <Alert severity="warning" sx={{ mb: 2 }}>
            Este parámetro está marcado como <strong>no editable</strong>. Para registrar un cambio normativo, creá una nueva versión con vigencia futura.
          </Alert>
        )}

        <FieldsGrid $cols={4}>
          <Field>
            <label>Clave *</label>
            <input value={form.clave} disabled={editingNoEditable}
              placeholder="Ej: SMLV_2026"
              onChange={(e) => updateField("clave", e.target.value.toUpperCase())} />
          </Field>
          <Field $span={2}>
            <label>Nombre *</label>
            <input value={form.nombre} placeholder="Ej: Salario Mínimo Legal Vigente 2026"
              onChange={(e) => updateField("nombre", e.target.value)} />
          </Field>
          <Field>
            <label>Categoría</label>
            <select value={form.categoria}
              onChange={(e) => updateField("categoria", e.target.value)}>
              {CATEGORIAS.map((c) => <option key={c} value={c}>{c}</option>)}
            </select>
          </Field>

          <Field>
            <label>Tipo de dato *</label>
            <select value={form.tipo_dato} disabled={editingNoEditable}
              onChange={(e) => updateField("tipo_dato", e.target.value)}>
              {TIPOS_DATO.map((t) => <option key={t.value} value={t.value}>{t.label}</option>)}
            </select>
          </Field>
          <Field>
            <label>Valor *</label>
            {valorEsNumero ? (
              <MoneyInputBox>
                {valorEsMoneda && <span>Gs.</span>}
                <input
                  value={formatMoneyInput(form.valor)}
                  inputMode="numeric"
                  autoComplete="off"
                  onChange={(e) => updateField("valor", moneyRawValue(e.target.value))}
                  placeholder={valorEsMoneda ? "2.550.307" : "2.550"}
                />
              </MoneyInputBox>
            ) : form.tipo_dato === "BOOLEANO" ? (
              <select value={form.valor === "true" ? "true" : "false"}
                onChange={(e) => updateField("valor", e.target.value)}>
                <option value="true">Sí (activado)</option>
                <option value="false">No (desactivado)</option>
              </select>
            ) : (
              <input value={form.valor}
                onChange={(e) => updateField("valor", e.target.value)}
                placeholder={
                  form.tipo_dato === "PORCENTAJE" ? "Ej: 0.09 (= 9%)" :
                  form.tipo_dato === "NUMERO" ? "Ej: 2550307" :
                  form.tipo_dato === "TEXTO" ? "Ej: PYG" : ""
                } />
            )}
          </Field>
          <Field>
            <label>Editable</label>
            <select value={form.editable ? "true" : "false"}
              onChange={(e) => updateField("editable", e.target.value === "true")}>
              <option value="true">Sí</option>
              <option value="false">No (legal)</option>
            </select>
          </Field>

          <Field>
            <label>Vigencia desde *</label>
            <input type="date" value={form.vigencia_desde}
              onChange={(e) => updateField("vigencia_desde", e.target.value)} />
          </Field>
          <Field>
            <label>Vigencia hasta</label>
            <input type="date" value={form.vigencia_hasta}
              onChange={(e) => updateField("vigencia_hasta", e.target.value)} />
          </Field>
        </FieldsGrid>

        <Footer>
          <FooterActionButton type="button" $variant="primary" onClick={handleGuardar}>
            <Icon icon={editingId ? "lucide:check-circle" : "lucide:plus"} />
            {editingId ? "Actualizar parámetro" : "Crear parámetro"}
          </FooterActionButton>
        </Footer>
      </FormPanel>

      <ListPanel>
        <ListBody>
          <ToolBar>
            <SectionTitle>
              <Icon icon="lucide:list" /> Parámetros del sistema
            </SectionTitle>
            <span style={{ flex: 1 }} />
            <select value={categoriaFiltro} onChange={(e) => setCategoriaFiltro(e.target.value)}
              style={{ minWidth: 140, height: 38, borderRadius: 8, padding: "0 10px" }}>
              <option value="">Todas las categorías</option>
              {CATEGORIAS.map((c) => <option key={c} value={c}>{c}</option>)}
            </select>
            <Tooltip
              enterDelay={300}
              title={
                soloVigentes
                  ? "Estás viendo solo las versiones vigentes HOY. Tocá para ver también las versiones pasadas y futuras (histórico completo)."
                  : "Estás viendo TODAS las versiones (histórico). Tocá para volver a ver solo las vigentes hoy."
              }
            >
              <GhostButton
                onClick={() => setSoloVigentes((p) => !p)}
                style={soloVigentes ? undefined : { borderColor: "#a78bfa", color: "#a78bfa" }}
              >
                <Icon icon={soloVigentes ? "lucide:filter" : "lucide:filter-x"} />
                {soloVigentes ? "Sólo vigentes" : "Viendo histórico"}
              </GhostButton>
            </Tooltip>
            {hayParametros && (
              <GhostButton onClick={handleSeed} disabled={seeding}>
                <Icon icon="lucide:sparkles" /> {seeding ? "Sembrando..." : "Agregar faltantes"}
              </GhostButton>
            )}
          </ToolBar>

          <Typography
            variant="caption"
            onClick={() => setSoloVigentes((p) => !p)}
            sx={{
              display: "flex", alignItems: "center", gap: 0.75, mt: -0.5, mb: 1, px: 0.5,
              color: "text.secondary", cursor: "pointer", "&:hover": { color: "text.primary" },
            }}
          >
            <Icon icon="lucide:info" width={14} />
            {soloVigentes ? (
              <span>
                Mostrando solo lo vigente <strong>hoy</strong>. ¿Buscás una versión anterior o futura
                (p. ej. el valor que regía un mes que estás liquidando)? Tocá acá para{" "}
                <strong>Ver histórico</strong>.
              </span>
            ) : (
              <span>
                Mostrando <strong>todas</strong> las versiones (vigentes, programadas e históricas).
                Tocá acá para volver a <strong>Sólo vigentes</strong>.
              </span>
            )}
          </Typography>

          {loading ? (
            <EmptyState>Cargando...</EmptyState>
          ) : datos.length === 0 ? (
            <RRHHEmptyState
              icon="lucide:settings-2"
              titulo={soloVigentes ? "Sin parámetros vigentes" : "Sin parámetros registrados"}
              descripcion="Los parámetros definen los valores legales del período: SMLV, porcentaje IPS, límites de descuento y contribuciones patronales. Son obligatorios para liquidar. Usá «Sembrar defaults» para cargar los valores vigentes automáticamente."
              guiaSeccion="parametros"
            />
          ) : (
            <TableWrap>
              <table>
                <thead>
                  <tr>
                    <th>Clave</th>
                    <th>Nombre</th>
                    <th>Categoría</th>
                    <th>Tipo</th>
                    <th style={{ textAlign: "right" }}>Valor</th>
                    <th>Vigencia desde</th>
                    <th>Vigencia hasta</th>
                    <th>Estado</th>
                    <th style={{ textAlign: "center" }}>Acciones</th>
                  </tr>
                </thead>
                <tbody>
                  {datos.map((p) => {
                    const estado = estadoVigencia(p);
                    return (
                      <tr key={p.id}>
                        <td>
                          {p.clave}
                          {!p.editable && (
                            <Icon icon="lucide:lock" width={12} style={{ marginLeft: 6, opacity: 0.6 }} />
                          )}
                        </td>
                        <td>{p.nombre}</td>
                        <td>{p.categoria}</td>
                        <td>{p.tipo_dato}</td>
                        <td style={{ textAlign: "right", fontFamily: "monospace" }}>{formatValor(p)}</td>
                        <td>{fmtDate(p.vigencia_desde)}</td>
                        <td>{fmtDate(p.vigencia_hasta)}</td>
                        <td>
                          <Badge $state={estado}>
                            {ESTADO_LABEL[estado]}
                          </Badge>
                        </td>
                        <td style={{ textAlign: "center" }}>
                          <RowActions>
                            <Tooltip title="Nueva vigencia (clonar)">
                              <IconButton size="small" onClick={() => handleNuevaVersion(p)}>
                                <Icon icon="lucide:copy-plus" width={16} />
                              </IconButton>
                            </Tooltip>
                            <Tooltip title="Editar">
                              <IconButton size="small" onClick={() => handleEditar(p)}>
                                <Icon icon="lucide:pencil" width={16} />
                              </IconButton>
                            </Tooltip>
                            <Tooltip title={p.editable ? "Eliminar" : "Parámetro legal — no eliminable"}>
                              <span>
                                <IconButton size="small" color="error"
                                  disabled={!p.editable}
                                  onClick={() => handleEliminar(p)}>
                                  <Icon icon="lucide:trash-2" width={16} />
                                </IconButton>
                              </span>
                            </Tooltip>
                          </RowActions>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </TableWrap>
          )}
        </ListBody>
      </ListPanel>
      {dialogs}
    </Container>
  );
}
