"use client";

import { TAGS, STD_FAMILY, validateLine, cortesDefault, calcLinePrice, fmtARS, toNum } from "@/lib/calculadora/engine";
import type { TagType, Line, PreciosData, CortesCajon } from "@/lib/calculadora/engine";

interface Props {
  tag:       TagType;
  line:      Line;
  data:      PreciosData;
  onChange:  (l: Line) => void;
  onRemove:  () => void;
  onAddLine: () => void;
}

// Wrapper de input pequeño estilo calculadora
function F({ children, grow }: { children: React.ReactNode; grow?: number }) {
  return (
    <div
      className="flex items-center bg-white/5 border border-line rounded-lg px-2.5 py-2 focus-within:border-brand transition-colors"
      style={{ flex: grow ?? 1, minWidth: 72 }}
    >
      {children}
    </div>
  );
}

function Inp({ value, onChange, placeholder, type = "text", onKeyDown, className = "", list }: {
  value: string;
  onChange: (v: string) => void;
  placeholder?: string;
  type?: string;
  onKeyDown?: React.KeyboardEventHandler<HTMLInputElement>;
  className?: string;
  list?: string;
}) {
  return (
    <input
      value={value}
      onChange={e => onChange(e.target.value)}
      placeholder={placeholder}
      type={type}
      onKeyDown={onKeyDown}
      list={list}
      className={`flex-1 w-full bg-transparent border-0 text-ink outline-none text-sm ${className}`}
    />
  );
}

function Sel({ value, onChange, children }: {
  value: string;
  onChange: (v: string) => void;
  children: React.ReactNode;
}) {
  return (
    <select
      value={value}
      onChange={e => onChange(e.target.value)}
      className="flex-1 w-full bg-transparent border-0 text-ink outline-none text-sm cursor-pointer"
    >
      {children}
    </select>
  );
}

export default function LineEditor({ tag, line: ln, data, onChange, onRemove, onAddLine }: Props) {
  const isValid = validateLine(tag, ln, data);
  const set = (patch: Partial<Line>) => onChange({ ...ln, ...patch });
  const onKey: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
    if (e.key === "Enter") { e.preventDefault(); onAddLine(); }
  };

  const panelMats = Object.keys(data.precios).filter(k => !k.startsWith("p"));
  const pinoMats  = Object.keys(data.precios).filter(k => k.startsWith("p"));

  const obsField = tag !== "#Adicional" ? (
    <F grow={2}>
      <Inp value={ln.obs || ""} onChange={v => set({ obs: v })} placeholder="Nota..." onKeyDown={onKey} />
    </F>
  ) : null;

  function renderInputs() {
    if (tag === "#Adicional") return (
      <>
        <F><Inp type="number" value={ln.monto || ""} onChange={v => set({ monto: v })} placeholder="$ Monto" onKeyDown={onKey} /></F>
        <F grow={3}><Inp value={ln.desc || ""} onChange={v => set({ desc: v })} placeholder="Descripción..." onKeyDown={onKey} /></F>
      </>
    );

    if (tag === "#Herraje") return (
      <>
        <F><Inp type="number" value={ln.cant || ""} onChange={v => set({ cant: v })} placeholder="cant" onKeyDown={onKey} /></F>
        <F grow={2}>
          <Sel value={ln.tipo || "bisagra"} onChange={v => set({ tipo: v })}>
            {Object.keys(data.herrajes).map(k => <option key={k} value={k}>{k}</option>)}
          </Sel>
        </F>
        {obsField}
      </>
    );

    if (tag === "#Pino") return (
      <>
        <F><Inp type="number" value={ln.cant || ""} onChange={v => set({ cant: v })} placeholder="cant" onKeyDown={onKey} /></F>
        <F><Inp type="number" value={ln.largo || ""} onChange={v => set({ largo: v })} placeholder="largo cm" onKeyDown={onKey} /></F>
        <F>
          <Sel value={ln.mat || "p1x2"} onChange={v => set({ mat: v })}>
            {pinoMats.map(k => <option key={k} value={k}>{k}</option>)}
          </Sel>
        </F>
        {obsField}
      </>
    );

    if (tag === "#Cajón" || tag === "#Placas") return (
      <>
        <F><Inp type="number" value={ln.cant || ""} onChange={v => set({ cant: v })} placeholder="cant" onKeyDown={onKey} /></F>
        <F><Inp type="number" value={ln.a || ""} onChange={v => set({ a: v })} placeholder="A cm" onKeyDown={onKey} /></F>
        <F><Inp type="number" value={ln.b || ""} onChange={v => set({ b: v })} placeholder="B cm" onKeyDown={onKey} /></F>
        <F><Inp type="number" value={ln.c || ""} onChange={v => set({ c: v })} placeholder="C cm" onKeyDown={onKey} /></F>
        {obsField}
      </>
    );

    if (tag === "#Calado" || tag === "#Círculo") return (
      <>
        <F><Inp type="number" value={ln.cant || ""} onChange={v => set({ cant: v })} placeholder="cant" onKeyDown={onKey} /></F>
        <F><Inp type="number" value={ln.a || ""} onChange={v => set({ a: v })} placeholder="cm" onKeyDown={onKey} /></F>
        <F><Inp type="number" value={ln.esp || ""} onChange={v => set({ esp: v })} placeholder="esp" onKeyDown={onKey} /></F>
        {obsField}
      </>
    );

    // STD_FAMILY: #Mueble, #Corte, #Sobrante
    return (
      <>
        <F><Inp type="number" value={ln.cant || ""} onChange={v => set({ cant: v })} placeholder="cant" onKeyDown={onKey} /></F>
        <F><Inp type="number" value={ln.a || ""} onChange={v => set({ a: v })} placeholder="cm" onKeyDown={onKey} /></F>
        <F><Inp type="number" value={ln.b || ""} onChange={v => set({ b: v })} placeholder="cm" onKeyDown={onKey} /></F>
        <F>
          <Inp value={ln.mat || ""} onChange={v => set({ mat: v })} placeholder="mat" onKeyDown={onKey}
            list="mat-options" className="w-full" />
          <datalist id="mat-options">
            {panelMats.map(k => <option key={k} value={k} />)}
          </datalist>
        </F>
        <F><Inp value={ln.canto || ""} onChange={v => set({ canto: v })} placeholder="[xx]" onKeyDown={onKey} /></F>
        <F><Inp value={ln.pint || ""} onChange={v => set({ pint: v })} placeholder="(1)" onKeyDown={onKey} /></F>
        {obsField}
      </>
    );
  }

  const tapType = "abs-encolado";
  const precio = isValid ? fmtARS(calcLinePrice(tag, ln, tapType, data)) : null;

  return (
    <>
      <div className={`flex gap-1.5 items-center flex-wrap px-1 py-0.5 rounded-lg border-l-2 ${isValid ? "border-transparent" : "border-bad bg-bad/5"}`}>
        {renderInputs()}
        {precio && <span className="text-xs text-brand font-mono ml-auto shrink-0">{precio}</span>}
        {!isValid && <span className="text-bad text-sm shrink-0" title="Dato inválido o $0">⚠</span>}
        <button onClick={onRemove} className="text-faint hover:text-bad text-sm px-1 shrink-0 transition-colors">✕</button>
      </div>

      {tag === "#Cajón" && ln.cant && ln.a && ln.b && ln.c && (
        <CajonCuts ln={ln} set={set} data={data} />
      )}
    </>
  );
}

function CajonCuts({ ln, set, data }: { ln: Line; set: (p: Partial<Line>) => void; data: PreciosData }) {
  const cortes: CortesCajon = ln.cortes || cortesDefault();
  const Q = toNum(ln.cant), A = toNum(ln.a), B = toNum(ln.b), C = toNum(ln.c);
  const panelMats = Object.keys(data.precios).filter(k => !k.startsWith("p"));
  const upd = (tipo: keyof CortesCajon, field: "mat" | "canto", val: string) =>
    set({ cortes: { ...cortes, [tipo]: { ...cortes[tipo], [field]: val } } });

  const sideThickness = parseInt(cortes.laterales.mat) || 18;
  const frenteIntLen = A - 2 * sideThickness;
  let fondoA = A - 2 * sideThickness;
  let fondoB = B;
  if (cortes.fondo.mat === "3") {
    fondoA = A - 20;
    fondoB = B - 10;
  }

  const rows = [
    { key: "laterales"    as const, label: "Laterales",     qty: Q*2, dimA: B, dimB: C },
    { key: "frenteInt"    as const, label: "Frente int.",   qty: Q*2, dimA: frenteIntLen, dimB: C },
    { key: "frenteVisible"as const, label: "Frente cajón",  qty: Q,   dimA: A, dimB: C },
    { key: "fondo"        as const, label: "Fondo",         qty: Q,   dimA: fondoA, dimB: fondoB },
  ];

  return (
    <div className="ml-6 mt-1 mb-2 border-l-2 border-brand/20 pl-3 flex flex-col gap-1.5">
      <span className="text-[10px] uppercase tracking-widest text-faint">Cortes del cajón</span>
      {rows.map(r => (
        <div key={r.key} className="flex items-center gap-1.5 flex-wrap">
          <span className="text-xs font-mono bg-brand/10 text-brand px-1.5 py-0.5 rounded min-w-[28px] text-center">{r.qty}</span>
          <span className="text-xs font-mono bg-line/60 text-ink px-1.5 py-0.5 rounded">{r.dimA}</span>
          <span className="text-faint text-xs">×</span>
          <span className="text-xs font-mono bg-line/60 text-ink px-1.5 py-0.5 rounded">{r.dimB}</span>
          <span className="text-xs text-faint min-w-[80px]">{r.label}</span>
          <div className="flex bg-white/5 border border-line rounded-lg px-2 py-1 focus-within:border-brand transition-colors min-w-[60px]">
            <select value={cortes[r.key].mat} onChange={e => upd(r.key, "mat", e.target.value)}
              className="bg-transparent border-0 text-ink outline-none text-xs cursor-pointer">
              {panelMats.map(m => <option key={m} value={m}>{m}</option>)}
            </select>
          </div>
          <div className="flex bg-white/5 border border-line rounded-lg px-2 py-1 focus-within:border-brand transition-colors w-[50px]">
            <input value={cortes[r.key].canto || ""} onChange={e => upd(r.key, "canto", e.target.value)}
              placeholder="canto" className="flex-1 bg-transparent border-0 text-ink outline-none text-xs" />
          </div>
        </div>
      ))}
    </div>
  );
}

// Re-export TAGS for use in page without extra import
export { TAGS };
