import { Icon } from "@iconify/react/dist/iconify.js";
import {
  Autocomplete,
  CircularProgress,
  TextField,
} from "@mui/material";
import { useEffect, useMemo, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import styled from "styled-components";
import { searchProveedores } from "../api/proveedores.service";
import { ClienteSearch } from "../components/organismos/POSAdmin/ClienteSearch";
import { MonedaInput } from "../components/common/MonedaInput";
import {
  useCompraAsistidaByIdQuery,
  useCrearCompraAsistidaMutation,
  useEditarCompraAsistidaMutation,
} from "../tanstack/CompraAsistidaStack";
import {
  useEmpresaMonedasQuery,
  useUltimaCotizacionQuery,
} from "../tanstack/MonedasStack";
import { formatMoney } from "../utils/formatMoney";

const ITEM_VACIO = () => ({
  key: Math.random(),
  descripcion: "",
  url_producto: "",
  proveedor_china: "",
  cantidad: 1,
  precio_usd: 0,
});

export function NuevaCompraAsistidaPage() {
  const navigate = useNavigate();
  const { id } = useParams();
  const isEdit = !!id;

  const { data: compraExistente, isLoading: loadingCompra } = useCompraAsistidaByIdQuery(id);

  // ── Cotización USD desde monedas de la empresa ───────────────────────────────
  const { data: empresaMonedasRaw } = useEmpresaMonedasQuery();
  const usdMoneda = useMemo(() => {
    const list = Array.isArray(empresaMonedasRaw)
      ? empresaMonedasRaw
      : (empresaMonedasRaw?.data ?? []);
    return list.find((m) => m.moneda?.codigo === "USD") ?? null;
  }, [empresaMonedasRaw]);
  const { data: ultimaCotizacion } = useUltimaCotizacionQuery(usdMoneda?.moneda_id ?? null);

  // ── Form state ──────────────────────────────────────────────────────────────
  const [cliente, setCliente] = useState(null);

  const [cotizacion, setCotizacion] = useState(7500);
  const [servicio, setServicio] = useState(0);
  const [logistica, setLogistica] = useState(0);
  const [comision, setComision] = useState(0);
  const [notas, setNotas] = useState("");
  const [fechaEntrega, setFechaEntrega] = useState("");
  const [items, setItems] = useState([ITEM_VACIO()]);

  const crearMutation = useCrearCompraAsistidaMutation();
  const editarMutation = useEditarCompraAsistidaMutation();

  // ── Cotización default desde última cotización USD (solo al crear) ───────────
  useEffect(() => {
    if (isEdit || !ultimaCotizacion?.cotizacion_venta) return;
    setCotizacion(Number(ultimaCotizacion.cotizacion_venta));
  }, [ultimaCotizacion, isEdit]);

  // ── Pre-llenar al editar ─────────────────────────────────────────────────────
  useEffect(() => {
    if (!compraExistente) return;
    setCotizacion(Number(compraExistente.cotizacion_usd_gs) || 7500);
    setServicio(Number(compraExistente.servicio_gs) || 0);
    setLogistica(Number(compraExistente.logistica_gs) || 0);
    setComision(Number(compraExistente.comision_gs) || 0);
    setNotas(compraExistente.notas || "");
    setFechaEntrega(
      compraExistente.fecha_entrega_estimada
        ? compraExistente.fecha_entrega_estimada.substring(0, 10)
        : "",
    );
    if (compraExistente.items?.length) {
      setItems(
        compraExistente.items.map((i) => ({
          key: Math.random(),
          descripcion: i.descripcion,
          url_producto: i.url_producto || "",
          proveedor_china: i.proveedor_china || "",
          cantidad: i.cantidad,
          precio_usd: Number(i.precio_usd),
        })),
      );
    }
    if (compraExistente.cliente) {
      setCliente(compraExistente.cliente);
      setClienteOptions([compraExistente.cliente]);
    }
  }, [compraExistente]);

  // ── Cálculos ─────────────────────────────────────────────────────────────────
  const subtotalUsd = useMemo(
    () => items.reduce((s, i) => s + Number(i.cantidad || 0) * Number(i.precio_usd || 0), 0),
    [items],
  );
  const subtotalGs = subtotalUsd * Number(cotizacion || 0);
  const totalGs = subtotalGs + Number(servicio || 0) + Number(logistica || 0) + Number(comision || 0);

  // ── Helpers de items ─────────────────────────────────────────────────────────
  const updateItem = (idx, field, value) =>
    setItems((prev) => prev.map((it, i) => (i === idx ? { ...it, [field]: value } : it)));
  const addItem = () => setItems((prev) => [...prev, ITEM_VACIO()]);
  const removeItem = (idx) => {
    if (items.length === 1) return;
    setItems((prev) => prev.filter((_, i) => i !== idx));
  };

  // ── Submit ───────────────────────────────────────────────────────────────────
  const handleSubmit = () => {
    const payload = {
      cliente_id: cliente?.id ?? null,
      cotizacion_usd_gs: Number(cotizacion),
      servicio_gs: Number(servicio),
      logistica_gs: Number(logistica),
      comision_gs: Number(comision),
      notas: notas || null,
      fecha_entrega_estimada: fechaEntrega || null,
      items: items.map((it, idx) => ({
        descripcion: it.descripcion,
        url_producto: it.url_producto || null,
        proveedor_china: it.proveedor_china || null,
        cantidad: Number(it.cantidad),
        precio_usd: Number(it.precio_usd),
        orden: idx,
      })),
    };
    if (payload.items.some((i) => !i.descripcion)) {
      alert("Todos los ítems deben tener descripción");
      return;
    }
    const goBack = () => navigate("/ventas?tab=compras-asistidas");
    if (isEdit) {
      editarMutation.mutate({ id, data: payload }, { onSuccess: goBack });
    } else {
      crearMutation.mutate(payload, { onSuccess: goBack });
    }
  };

  const isPending = crearMutation.isPending || editarMutation.isPending;

  if (isEdit && loadingCompra) {
    return (
      <PageWrap>
        <LoadingCenter>
          <CircularProgress size={32} sx={{ color: "#f88533" }} />
        </LoadingCenter>
      </PageWrap>
    );
  }

  return (
    <PageWrap>
      {/* ── Header ── */}
      <PageHeader>
        <BackBtn onClick={() => navigate("/ventas?tab=compras-asistidas")}>
          <Icon icon="lucide:arrow-left" />
        </BackBtn>
        <PageTitle>{isEdit ? "Editar Compra Asistida" : "Nueva Compra Asistida"}</PageTitle>
      </PageHeader>

      {/* ── Body: izquierda + derecha ── */}
      <Body>
        <LeftCol>
          {/* Datos del Pedido */}
          <Section>
            <SectionTitle>
              <Icon icon="lucide:file-text" />
              Datos del Pedido
            </SectionTitle>
            <FieldRow>
              <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                <MonedaInput
                  label="Cotización USD → Gs"
                  moneda="PYG"
                  decimales={2}
                  value={cotizacion}
                  onChange={setCotizacion}
                  sx={{ width: 200 }}
                />
                {ultimaCotizacion && (
                  <CotizHint>
                    <Icon icon="lucide:info" style={{ width: 11, height: 11 }} />
                    Última cotización:{" "}
                    {new Date(ultimaCotizacion.fecha).toLocaleDateString("es-PY")}
                  </CotizHint>
                )}
              </div>
              <TextField
                label="Fecha entrega estimada"
                type="date"
                size="small"
                value={fechaEntrega}
                onChange={(e) => setFechaEntrega(e.target.value)}
                InputLabelProps={{ shrink: true }}
                sx={{ width: 220 }}
              />
            </FieldRow>
            <TextField
              label="Notas"
              size="small"
              value={notas}
              onChange={(e) => setNotas(e.target.value)}
              multiline
              rows={2}
              fullWidth
            />
          </Section>

          {/* Cliente */}
          <Section>
            <SectionTitle>
              <Icon icon="lucide:user" />
              Datos del Cliente
            </SectionTitle>
            <FieldLabel>BUSCAR CLIENTE</FieldLabel>
            <ClienteSearch value={cliente} onChange={setCliente} />
          </Section>

          {/* Items */}
          <Section>
            <SectionTitle>
              <Icon icon="lucide:package" />
              Ítems del Pedido
            </SectionTitle>
            <ItemsTable>
              <thead>
                <tr>
                  <Th style={{ width: "28%" }}>Descripción *</Th>
                  <Th>URL</Th>
                  <Th style={{ width: "22%" }}>Proveedor</Th>
                  <Th style={{ width: 70 }}>Cant.</Th>
                  <Th style={{ width: 110 }}>Precio USD</Th>
                  <Th style={{ width: 40 }} />
                </tr>
              </thead>
              <tbody>
                {items.map((item, idx) => (
                  <ItemRow key={item.key}>
                    <Td>
                      <ItemInput
                        placeholder="Descripción del producto"
                        value={item.descripcion}
                        onChange={(e) => updateItem(idx, "descripcion", e.target.value)}
                      />
                    </Td>
                    <Td>
                      <ItemInput
                        placeholder="https://..."
                        value={item.url_producto}
                        onChange={(e) => updateItem(idx, "url_producto", e.target.value)}
                      />
                    </Td>
                    <Td>
                      <ProveedorCell idx={idx} value={item.proveedor_china} onChange={updateItem} />
                    </Td>
                    <Td>
                      <ItemInput
                        type="number"
                        value={item.cantidad}
                        onChange={(e) => updateItem(idx, "cantidad", e.target.value)}
                        min={1}
                        style={{ textAlign: "center" }}
                      />
                    </Td>
                    <Td>
                      <MonedaInput
                        moneda="USD"
                        value={item.precio_usd}
                        onChange={(v) => updateItem(idx, "precio_usd", v)}
                        size="small"
                        sx={{ width: "100%", "& .MuiInputBase-root": { borderRadius: "6px", fontSize: 13 } }}
                      />
                    </Td>
                    <Td>
                      <TrashBtn
                        onClick={() => removeItem(idx)}
                        disabled={items.length === 1}
                        title="Eliminar ítem"
                      >
                        <Icon icon="lucide:trash-2" />
                      </TrashBtn>
                    </Td>
                  </ItemRow>
                ))}
              </tbody>
            </ItemsTable>
            <AddItemBtn onClick={addItem}>
              <Icon icon="lucide:plus" /> Agregar ítem
            </AddItemBtn>
          </Section>
        </LeftCol>

        {/* ── Panel derecho: resumen ── */}
        <RightCol>
          <ResumenCard>
            <ResumenTitle>
              <Icon icon="lucide:calculator" /> Resumen
            </ResumenTitle>

            <ResumenRow>
              <span>Subtotal USD</span>
              <strong>{subtotalUsd.toFixed(2)} USD</strong>
            </ResumenRow>
            <ResumenRow>
              <span>Cotización</span>
              <strong>{Number(cotizacion).toLocaleString("es-PY")} Gs/USD</strong>
            </ResumenRow>
            <ResumenRow>
              <span>Subtotal en Gs</span>
              <strong>{formatMoney(subtotalGs, "PYG")}</strong>
            </ResumenRow>

            <ResumenDivider />

            <MonedaInput
              label="Servicio (Gs)"
              moneda="PYG"
              value={servicio}
              onChange={setServicio}
              sx={{ width: "100%" }}
            />
            <MonedaInput
              label="Logística (Gs)"
              moneda="PYG"
              value={logistica}
              onChange={setLogistica}
              sx={{ width: "100%" }}
            />
            <MonedaInput
              label="Comisión (Gs)"
              moneda="PYG"
              value={comision}
              onChange={setComision}
              sx={{ width: "100%" }}
            />

            <ResumenDivider />

            <TotalRow>
              <span>TOTAL GS</span>
              <span>{formatMoney(totalGs, "PYG")}</span>
            </TotalRow>

            <SubmitBtn onClick={handleSubmit} disabled={isPending}>
              {isPending ? (
                <CircularProgress size={18} color="inherit" />
              ) : isEdit ? (
                "GUARDAR CAMBIOS"
              ) : (
                "CREAR PEDIDO"
              )}
            </SubmitBtn>
          </ResumenCard>
        </RightCol>
      </Body>
    </PageWrap>
  );
}

// ── Subcomponente: búsqueda de proveedor por ítem ───────────────────────────
function ProveedorCell({ idx, value, onChange }) {
  const [options, setOptions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [inputValue, setInputValue] = useState(value || "");

  useEffect(() => { setInputValue(value || ""); }, [value]);

  const getLabel = (opt) => {
    if (typeof opt === "string") return opt;
    return opt?.personas?.razon_social || opt?.nombre_fantasia || opt?.ruc || "";
  };

  const handleInputChange = (_, newVal) => {
    setInputValue(newVal);
    onChange(idx, "proveedor_china", newVal);
    if (newVal.length < 2) { setOptions([]); return; }
    setLoading(true);
    searchProveedores(newVal).then((res) => {
      setOptions(res);
      setLoading(false);
    });
  };

  return (
    <Autocomplete
      freeSolo
      options={options}
      getOptionLabel={getLabel}
      inputValue={inputValue}
      onInputChange={handleInputChange}
      onChange={(_, val) => {
        const nombre = typeof val === "string" ? val : getLabel(val);
        setInputValue(nombre);
        onChange(idx, "proveedor_china", nombre);
      }}
      loading={loading}
      noOptionsText="Sin resultados"
      filterOptions={(x) => x}
      renderInput={(params) => (
        <TextField
          {...params}
          size="small"
          placeholder="Buscar proveedor..."
          sx={{
            "& .MuiOutlinedInput-root": {
              fontSize: 13,
              borderRadius: "6px",
              "& fieldset": { borderColor: "transparent" },
              "&:hover fieldset": { borderColor: "rgba(255,255,255,0.15)" },
              "&.Mui-focused fieldset": { borderColor: "#3b82f6" },
            },
          }}
        />
      )}
      renderOption={(props, opt) => (
        <li {...props} key={opt.id}>
          <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
            <span style={{ fontSize: 13 }}>{getLabel(opt)}</span>
            {opt.personas?.ruc && (
              <span style={{ fontSize: 11, color: "#64748b" }}>
                RUC {opt.personas.ruc}-{opt.personas.dv ?? 0}
              </span>
            )}
          </div>
        </li>
      )}
    />
  );
}

// ── Styled components ────────────────────────────────────────────────────────
const PageWrap = styled.div`
  display: flex;
  flex-direction: column;
  min-height: 100%;
  background: ${({ theme }) => theme.bg1};
  color: ${({ theme }) => theme.text};
`;

const PageHeader = styled.div`
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 20px 24px 12px;
  border-bottom: 1px solid ${({ theme }) => theme.color2};
`;

const BackBtn = styled.button`
  display: flex;
  align-items: center;
  justify-content: center;
  width: 34px;
  height: 34px;
  border-radius: 8px;
  border: 1px solid ${({ theme }) => theme.color2};
  background: transparent;
  cursor: pointer;
  color: ${({ theme }) => theme.text};
  transition: background 0.15s;
  &:hover { background: ${({ theme }) => theme.bg2}; }
  svg { width: 18px; height: 18px; }
`;

const PageTitle = styled.h1`
  margin: 0;
  font-size: 22px;
  font-weight: 700;
  color: ${({ theme }) => theme.text};
`;

const Body = styled.div`
  display: flex;
  gap: 0;
  flex: 1;
  align-items: flex-start;
`;

const LeftCol = styled.div`
  flex: 7;
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 20px 20px 40px;
  overflow-y: auto;
`;

const RightCol = styled.div`
  flex: 3;
  min-width: 280px;
  max-width: 360px;
  padding: 20px 20px 40px;
  position: sticky;
  top: 0;
`;

const Section = styled.div`
  background: ${({ theme }) => theme.bg2};
  border: 1px solid ${({ theme }) => theme.color2};
  border-radius: 12px;
  padding: 18px;
  display: flex;
  flex-direction: column;
  gap: 14px;
`;

const SectionTitle = styled.div`
  color: #3b82f6;
  font-weight: 700;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  svg { width: 16px; height: 16px; }
`;

const FieldRow = styled.div`
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
`;

const FieldLabel = styled.div`
  font-size: 11px;
  font-weight: 700;
  letter-spacing: 0.5px;
  color: ${({ theme }) => theme.text}88;
  text-transform: uppercase;
`;

const ItemsTable = styled.table`
  width: 100%;
  border-collapse: collapse;
`;

const Th = styled.th`
  padding: 8px 10px;
  text-align: left;
  font-size: 11px;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.4px;
  color: ${({ theme }) => theme.text}66;
  background: ${({ theme }) => theme.bg1};
  border-bottom: 1px solid ${({ theme }) => theme.color2};
`;

const ItemRow = styled.tr`
  &:hover td { background: ${({ theme }) => theme.bg1}55; }
`;

const Td = styled.td`
  padding: 6px 6px;
  border-bottom: 1px solid ${({ theme }) => theme.color2}40;
  vertical-align: middle;
`;

const ItemInput = styled.input`
  width: 100%;
  background: transparent;
  border: 1px solid transparent;
  border-radius: 6px;
  padding: 6px 8px;
  font-size: 13px;
  color: ${({ theme }) => theme.text};
  outline: none;
  &:focus {
    border-color: #3b82f6;
    background: ${({ theme }) => theme.bg1};
  }
  &::placeholder { color: ${({ theme }) => theme.text}44; }
`;

// ItemInput para renderInput de Autocomplete (ref compatible)
const ItemInputRef = styled.input`
  width: 100%;
  background: transparent;
  border: 1px solid transparent;
  border-radius: 6px;
  padding: 6px 8px;
  font-size: 13px;
  color: ${({ theme }) => theme.text};
  outline: none;
  &:focus {
    border-color: #3b82f6;
    background: ${({ theme }) => theme.bg1};
  }
  &::placeholder { color: ${({ theme }) => theme.text}44; }
`;

const TrashBtn = styled.button`
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border: none;
  background: transparent;
  cursor: pointer;
  border-radius: 6px;
  color: #ef4444;
  &:hover:not(:disabled) { background: #ef444418; }
  &:disabled { opacity: 0.3; cursor: default; }
  svg { width: 14px; height: 14px; }
`;

const AddItemBtn = styled.button`
  display: flex;
  align-items: center;
  gap: 6px;
  background: transparent;
  border: none;
  cursor: pointer;
  color: #3b82f6;
  font-size: 13px;
  font-weight: 600;
  padding: 4px 0;
  align-self: flex-start;
  &:hover { opacity: 0.8; }
  svg { width: 15px; height: 15px; }
`;

const ResumenCard = styled.div`
  background: ${({ theme }) => theme.bg2};
  border: 1px solid ${({ theme }) => theme.color2};
  border-radius: 12px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 10px;
`;

const ResumenTitle = styled.div`
  font-size: 15px;
  font-weight: 700;
  color: ${({ theme }) => theme.text};
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
  svg { width: 16px; height: 16px; }
`;

const ResumenRow = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 13px;
  color: ${({ theme }) => theme.text}cc;
`;

const ResumenDivider = styled.hr`
  border: none;
  border-top: 1px solid ${({ theme }) => theme.color2};
  margin: 4px 0;
`;

const CotizHint = styled.div`
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 11px;
  color: ${({ theme }) => theme.text}66;
`;

const TotalRow = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 800;
  color: ${({ theme }) => theme.text};
  margin: 4px 0;
`;

const SubmitBtn = styled.button`
  width: 100%;
  padding: 14px;
  background: #f88533;
  border: none;
  border-radius: 10px;
  color: #fff;
  font-size: 15px;
  font-weight: 700;
  letter-spacing: 0.5px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-top: 8px;
  transition: background 0.15s;
  &:hover:not(:disabled) { background: #e07320; }
  &:disabled { opacity: 0.6; cursor: default; }
`;

const LoadingCenter = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300px;
`;
