"use client";

import { useState } from "react";
import { usePreciosStore } from "@/lib/calculadora/store";
import type { PreciosData } from "@/lib/calculadora/engine";

function fmtPreciso(n: number) {
  return `$${Math.round(n).toLocaleString("es-AR")}`;
}

interface Props {
  canEdit: boolean;
}

type TipoMaterial = "mdf" | "blanco" | "color";

const TIPO_OPTIONS: { value: TipoMaterial; label: string }[] = [
  { value: "mdf",    label: "MDF" },
  { value: "blanco", label: "Blanco" },
  { value: "color",  label: "Color" },
];

function tipoDeCodigo(code: string) {
  if (code.endsWith("c")) return "Color";
  if (code.endsWith("b")) return "Blanco";
  return "MDF";
}

// Compone el código final según el tipo elegido. El motor de cálculo deduce el tipo
// del sufijo del código (b = blanco, c = color, sin sufijo = MDF), así que el selector
// normaliza el código base para que coincida.
function composeCodigo(base: string, tipo: TipoMaterial) {
  const clean = base.trim().toLowerCase().replace(/[bc]+$/, "");
  if (tipo === "blanco") return clean + "b";
  if (tipo === "color")  return clean + "c";
  return clean;
}

function pinoDes(code: string) {
  const m = code.match(/p(\d+)x(\d+(?:,\d+)?)/);
  if (!m) return code;
  return `Pino ${m[1]}"×${m[2]}"`;
}

function SectionCard({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="bg-surface border border-line rounded-xl p-4">
      <h3 className="text-sm font-semibold text-ink mb-3">{title}</h3>
      {children}
    </div>
  );
}

function NumInput({
  value, onChange, disabled, step = "1", min = "0", className = "",
}: {
  value: number; onChange: (v: number) => void; disabled: boolean;
  step?: string; min?: string; className?: string;
}) {
  return (
    <input
      type="number"
      value={value}
      min={min}
      step={step}
      disabled={disabled}
      onChange={e => onChange(parseFloat(e.target.value) || 0)}
      className={`w-full bg-white/5 border border-line rounded px-2 py-1 text-sm text-ink outline-none
        focus:border-brand disabled:opacity-40 disabled:cursor-not-allowed text-right ${className}`}
    />
  );
}

function THead({ cols }: { cols: string[] }) {
  return (
    <thead>
      <tr>
        {cols.map(c => (
          <th key={c} className="text-left text-xs text-faint font-normal pb-1.5 pr-3 last:pr-0">{c}</th>
        ))}
      </tr>
    </thead>
  );
}

export default function PreciosTab({ canEdit }: Props) {
  const { data, saveData, saveToDB, syncStatus } = usePreciosStore();

  const [newPanel, setNewPanel] = useState<{ codigo: string; valorPlaca: string; ancho: string; alto: string; tipo: TipoMaterial }>({ codigo: "", valorPlaca: "", ancho: "244", alto: "183", tipo: "mdf" });
  const [newPino, setNewPino]   = useState({ codigo: "", precio: "" });
  const [newHerr, setNewHerr]   = useState({ nombre: "", precio: "" });

  const [ordenCodigo, setOrdenCodigo] = useState("");
  const [ordenCant,   setOrdenCant]   = useState(1);
  const [orden,       setOrden]       = useState<{ codigo: string; cantidad: number; costo: number; unidad: string }[]>([]);

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

  function patchData(patch: Partial<PreciosData>) {
    saveData({ ...data, ...patch });
  }

  // ── Placas ──────────────────────────────────────────────────────────────

  function getValorPlaca(code: string) {
    return (data.dimensiones[code]?.[2] ?? 0);
  }
  function getPrecioM2(code: string) {
    const [ancho, alto] = data.dimensiones[code] || [244, 183];
    const vp = getValorPlaca(code);
    return ancho > 0 && alto > 0 ? vp / ((ancho / 100) * (alto / 100)) : 0;
  }

  function handleDimChange(code: string, field: "ancho" | "alto", val: number) {
    const dim = data.dimensiones[code] || [244, 183, 0];
    const next: [number, number, number] = [...dim] as [number, number, number];
    if (field === "ancho") next[0] = val;
    else next[1] = val;
    const pm2 = next[0] > 0 && next[1] > 0 ? next[2] / ((next[0] / 100) * (next[1] / 100)) : 0;
    patchData({
      precios: { ...data.precios, [code]: pm2 },
      dimensiones: { ...data.dimensiones, [code]: next },
    });
  }

  function handleValorPlacaChange(code: string, val: number) {
    const dim = data.dimensiones[code] || [244, 183, 0];
    const next: [number, number, number] = [dim[0], dim[1], val];
    const pm2 = dim[0] > 0 && dim[1] > 0 ? val / ((dim[0] / 100) * (dim[1] / 100)) : 0;
    patchData({
      precios: { ...data.precios, [code]: pm2 },
      dimensiones: { ...data.dimensiones, [code]: next },
    });
  }

  function addPanel() {
    const code = composeCodigo(newPanel.codigo, newPanel.tipo);
    if (!code || !newPanel.valorPlaca) return;
    const ancho = parseFloat(newPanel.ancho) || 244;
    const alto  = parseFloat(newPanel.alto)  || 183;
    const vp    = parseFloat(newPanel.valorPlaca) || 0;
    const pm2   = ancho > 0 && alto > 0 ? vp / ((ancho / 100) * (alto / 100)) : 0;
    patchData({
      precios: { ...data.precios, [code]: pm2 },
      dimensiones: { ...data.dimensiones, [code]: [ancho, alto, vp] },
    });
    setNewPanel({ codigo: "", valorPlaca: "", ancho: "244", alto: "183", tipo: "mdf" });
  }

  function deletePanel(code: string) {
    const precios = { ...data.precios }; delete precios[code];
    const dimensiones = { ...data.dimensiones }; delete dimensiones[code];
    patchData({ precios, dimensiones });
  }

  // ── Pino ─────────────────────────────────────────────────────────────────

  function handlePinoChange(code: string, val: number) {
    patchData({ precios: { ...data.precios, [code]: val } });
  }

  function addPino() {
    const raw  = newPino.codigo.trim();
    if (!raw || !newPino.precio) return;
    const code = raw.startsWith("p") ? raw : "p" + raw;
    patchData({ precios: { ...data.precios, [code]: parseFloat(newPino.precio) || 0 } });
    setNewPino({ codigo: "", precio: "" });
  }

  function deletePino(code: string) {
    const precios = { ...data.precios }; delete precios[code];
    patchData({ precios });
  }

  // ── Tapacantos ───────────────────────────────────────────────────────────

  function handleTapaChange(key: string, field: "costo" | "coef", val: number) {
    patchData({
      tapacantos: { ...data.tapacantos, [key]: { ...data.tapacantos[key], [field]: val } },
    });
  }

  // ── Herrajes ─────────────────────────────────────────────────────────────

  function handleHerrajeChange(key: string, field: "costo" | "coef", val: number) {
    patchData({
      herrajes: { ...data.herrajes, [key]: { ...data.herrajes[key], [field]: val } },
    });
  }

  function addHerraje() {
    const nombre = newHerr.nombre.trim();
    if (!nombre || !newHerr.precio) return;
    patchData({
      herrajes: { ...data.herrajes, [nombre]: { costo: parseFloat(newHerr.precio) || 0, coef: 1.0 } },
    });
    setNewHerr({ nombre: "", precio: "" });
  }

  function deleteHerraje(key: string) {
    const herrajes = { ...data.herrajes }; delete herrajes[key];
    patchData({ herrajes });
  }

  // ── Calculadora de compra ─────────────────────────────────────────────────

  function costoOrden(cod: string, cant: number): number {
    if (cod.startsWith("h_")) {
      const h = data.herrajes[cod.slice(2)];
      return (h?.costo ?? 0) * cant;
    }
    if (cod.startsWith("p")) return (data.precios[cod] || 0) * cant;
    return (data.dimensiones[cod]?.[2] ?? 0) * cant;
  }

  function unidadOrden(cod: string) {
    if (cod.startsWith("h_")) return "u";
    if (cod.startsWith("p"))  return "ml";
    return "placas";
  }

  function addOrdenRow() {
    if (!ordenCodigo) return;
    setOrden(prev => [...prev, {
      codigo: ordenCodigo,
      cantidad: ordenCant,
      costo: costoOrden(ordenCodigo, ordenCant),
      unidad: unidadOrden(ordenCodigo),
    }]);
    setOrdenCant(1);
  }

  const totalOrden = orden.reduce((s, r) => s + r.costo, 0);

  const dbLabel = { ok: "Guardado ✓", syncing: "Guardando...", error: "Error ✗" }[syncStatus] ?? "Guardar en DB";

  return (
    <div className="flex flex-col gap-4 pb-8">

      {/* Save button */}
      <div className="flex justify-end">
        <button
          onClick={() => saveToDB()}
          disabled={syncStatus === "syncing" || !canEdit}
          className="px-4 py-1.5 text-sm rounded-lg bg-brand text-white font-medium
            hover:bg-brand/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
        >
          {dbLabel}
        </button>
      </div>

      {/* ── Placas MDF / Melamina ─────────────────────────────────────────── */}
      <SectionCard title="Placas — MDF / Melamina">
        <table className="w-full text-sm">
          <THead cols={["Código", "Tipo", "Ancho (cm)", "Alto (cm)", "Valor placa", "$/m² (calc)", ""]} />
          <tbody className="divide-y divide-line">
            {panelMats.map(code => {
              const dim = data.dimensiones[code] || [244, 183, 0];
              return (
                <tr key={code}>
                  <td className="py-1 pr-3 font-mono text-brand text-xs">{code}</td>
                  <td className="py-1 pr-3 text-faint text-xs">{tipoDeCodigo(code)}</td>
                  <td className="py-1 pr-3 w-28">
                    <NumInput value={dim[0]} onChange={v => handleDimChange(code, "ancho", v)} disabled={!canEdit} />
                  </td>
                  <td className="py-1 pr-3 w-28">
                    <NumInput value={dim[1]} onChange={v => handleDimChange(code, "alto", v)} disabled={!canEdit} />
                  </td>
                  <td className="py-1 pr-3 w-32">
                    <NumInput value={getValorPlaca(code)} onChange={v => handleValorPlacaChange(code, v)} disabled={!canEdit} />
                  </td>
                  <td className="py-1 pr-3 text-right font-mono text-xs text-ink whitespace-nowrap">{fmtPreciso(getPrecioM2(code))}</td>
                  <td className="py-1 text-right">
                    {canEdit && (
                      <button onClick={() => deletePanel(code)}
                        className="text-faint hover:text-bad text-xs px-1 transition-colors">✕</button>
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {canEdit && (
          <div className="flex gap-2 mt-3 flex-wrap items-center">
            <input placeholder="Código base (ej: 18)"
              value={newPanel.codigo} onChange={e => setNewPanel({ ...newPanel, codigo: e.target.value })}
              className="bg-white/5 border border-line rounded px-2 py-1 text-sm text-ink outline-none focus:border-brand w-32" />
            <select
              value={newPanel.tipo}
              onChange={e => setNewPanel({ ...newPanel, tipo: e.target.value as TipoMaterial })}
              className="bg-white/5 border border-line rounded px-2 py-1 text-sm text-ink outline-none focus:border-brand cursor-pointer"
            >
              {TIPO_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
            </select>
            {newPanel.codigo.trim() && (
              <span className="text-xs text-faint">
                → <span className="font-mono text-brand">{composeCodigo(newPanel.codigo, newPanel.tipo)}</span>
              </span>
            )}
            <input type="number" placeholder="Ancho cm"
              value={newPanel.ancho} onChange={e => setNewPanel({ ...newPanel, ancho: e.target.value })}
              className="bg-white/5 border border-line rounded px-2 py-1 text-sm text-ink outline-none focus:border-brand w-24" />
            <input type="number" placeholder="Alto cm"
              value={newPanel.alto} onChange={e => setNewPanel({ ...newPanel, alto: e.target.value })}
              className="bg-white/5 border border-line rounded px-2 py-1 text-sm text-ink outline-none focus:border-brand w-24" />
            <input type="number" placeholder="$ placa entera"
              value={newPanel.valorPlaca} onChange={e => setNewPanel({ ...newPanel, valorPlaca: e.target.value })}
              className="bg-white/5 border border-line rounded px-2 py-1 text-sm text-ink outline-none focus:border-brand w-32" />
            <button onClick={addPanel}
              className="px-3 py-1 text-sm rounded-lg bg-brand/20 text-brand hover:bg-brand/30 transition-colors">
              + Agregar
            </button>
          </div>
        )}
      </SectionCard>

      {/* ── Pino ─────────────────────────────────────────────────────────── */}
      <SectionCard title="Pino">
        <table className="w-full text-sm">
          <THead cols={["Código", "Descripción", "$/ml", ""]} />
          <tbody className="divide-y divide-line">
            {pinoMats.map(code => (
              <tr key={code}>
                <td className="py-1 pr-3 font-mono text-brand text-xs">{code}</td>
                <td className="py-1 pr-3 text-faint text-xs">{pinoDes(code)}</td>
                <td className="py-1 pr-3 w-32">
                  <NumInput value={data.precios[code] || 0} onChange={v => handlePinoChange(code, v)} disabled={!canEdit} />
                </td>
                <td className="py-1 text-right">
                  {canEdit && (
                    <button onClick={() => deletePino(code)}
                      className="text-faint hover:text-bad text-xs px-1 transition-colors">✕</button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {canEdit && (
          <div className="flex gap-2 mt-3">
            <input placeholder="Código (ej: 1x6)"
              value={newPino.codigo} onChange={e => setNewPino({ ...newPino, codigo: e.target.value })}
              className="bg-white/5 border border-line rounded px-2 py-1 text-sm text-ink outline-none focus:border-brand w-28" />
            <input type="number" placeholder="$/ml"
              value={newPino.precio} onChange={e => setNewPino({ ...newPino, precio: e.target.value })}
              className="bg-white/5 border border-line rounded px-2 py-1 text-sm text-ink outline-none focus:border-brand w-28" />
            <button onClick={addPino}
              className="px-3 py-1 text-sm rounded-lg bg-brand/20 text-brand hover:bg-brand/30 transition-colors">
              + Agregar
            </button>
          </div>
        )}
      </SectionCard>

      {/* ── Pintura ───────────────────────────────────────────────────────── */}
      <SectionCard title="Pintura">
        <table className="w-full text-sm">
          <THead cols={["Tipo", "$/m² por cara"]} />
          <tbody>
            <tr>
              <td className="py-1 pr-3 text-faint text-xs">Pintura en tablero</td>
              <td className="py-1 font-mono text-xs text-right">{fmtPreciso(data.coefs.VALOR_PINTURA)}</td>
            </tr>
          </tbody>
        </table>
        <p className="text-xs text-faint mt-2">Editable desde pestaña Lógica de Cálculo.</p>
      </SectionCard>

      {/* ── Tapacantos ───────────────────────────────────────────────────── */}
      <SectionCard title="Tapacantos">
        <table className="w-full text-sm">
          <THead cols={["Tipo", "Costo $/ml", "Coef", "Precio final $/ml"]} />
          <tbody className="divide-y divide-line">
            {Object.entries(data.tapacantos).map(([key, t]) => (
              <tr key={key}>
                <td className="py-1 pr-3 text-xs text-ink">{t.nombre}</td>
                <td className="py-1 pr-3 w-32">
                  <NumInput value={t.costo || 0} onChange={v => handleTapaChange(key, "costo", v)} disabled={!canEdit} />
                </td>
                <td className="py-1 pr-3 w-24">
                  <NumInput value={t.coef || 1} step="0.1" onChange={v => handleTapaChange(key, "coef", v)} disabled={!canEdit} />
                </td>
                <td className="py-1 text-right font-mono text-xs whitespace-nowrap">{fmtPreciso((t.costo || 0) * (t.coef || 1))}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </SectionCard>

      {/* ── Herrajes ─────────────────────────────────────────────────────── */}
      <SectionCard title="Herrajes">
        <table className="w-full text-sm">
          <THead cols={["Nombre", "Costo $/u", "Coef", "Precio final $/u", ""]} />
          <tbody className="divide-y divide-line">
            {Object.entries(data.herrajes).map(([key, h]) => (
              <tr key={key}>
                <td className="py-1 pr-3 font-mono text-brand text-xs">{key}</td>
                <td className="py-1 pr-3 w-32">
                  <NumInput value={h.costo || 0} onChange={v => handleHerrajeChange(key, "costo", v)} disabled={!canEdit} />
                </td>
                <td className="py-1 pr-3 w-24">
                  <NumInput value={h.coef || 1} step="0.1" onChange={v => handleHerrajeChange(key, "coef", v)} disabled={!canEdit} />
                </td>
                <td className="py-1 pr-3 text-right font-mono text-xs whitespace-nowrap">{fmtPreciso((h.costo || 0) * (h.coef || 1))}</td>
                <td className="py-1 text-right">
                  {canEdit && (
                    <button onClick={() => deleteHerraje(key)}
                      className="text-faint hover:text-bad text-xs px-1 transition-colors">✕</button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {canEdit && (
          <div className="flex gap-2 mt-3">
            <input placeholder="Nombre (ej: corredor)"
              value={newHerr.nombre} onChange={e => setNewHerr({ ...newHerr, nombre: e.target.value })}
              className="bg-white/5 border border-line rounded px-2 py-1 text-sm text-ink outline-none focus:border-brand w-36" />
            <input type="number" placeholder="Costo $/u"
              value={newHerr.precio} onChange={e => setNewHerr({ ...newHerr, precio: e.target.value })}
              className="bg-white/5 border border-line rounded px-2 py-1 text-sm text-ink outline-none focus:border-brand w-28" />
            <button onClick={addHerraje}
              className="px-3 py-1 text-sm rounded-lg bg-brand/20 text-brand hover:bg-brand/30 transition-colors">
              + Agregar
            </button>
          </div>
        )}
      </SectionCard>

      {/* ── Calculadora de compra ─────────────────────────────────────────── */}
      <SectionCard title="Calculadora de compra">
        <div className="flex gap-2 flex-wrap items-center mb-3">
          <select
            value={ordenCodigo}
            onChange={e => setOrdenCodigo(e.target.value)}
            className="bg-white/5 border border-line rounded px-2 py-1 text-sm text-ink outline-none focus:border-brand flex-1 min-w-48 cursor-pointer"
          >
            <option value="">— Seleccionar material —</option>
            <optgroup label="Placas MDF / Melamina">
              {panelMats.map(c => (
                <option key={c} value={c}>{c} — {tipoDeCodigo(c)} ({fmtPreciso(getValorPlaca(c))}/placa)</option>
              ))}
            </optgroup>
            <optgroup label="Pino">
              {pinoMats.map(c => (
                <option key={c} value={c}>{c} — {pinoDes(c)} ({fmtPreciso(data.precios[c] || 0)}/ml)</option>
              ))}
            </optgroup>
            <optgroup label="Herrajes">
              {Object.keys(data.herrajes).map(k => (
                <option key={k} value={`h_${k}`}>{k} ({fmtPreciso(data.herrajes[k]?.costo ?? 0)}/u)</option>
              ))}
            </optgroup>
          </select>
          <input
            type="number" min="1" value={ordenCant}
            onChange={e => setOrdenCant(parseFloat(e.target.value) || 1)}
            className="bg-white/5 border border-line rounded px-2 py-1 text-sm text-ink outline-none focus:border-brand w-20 text-right"
          />
          <button onClick={addOrdenRow}
            className="px-3 py-1 text-sm rounded-lg bg-brand/20 text-brand hover:bg-brand/30 transition-colors">
            + Agregar
          </button>
        </div>

        {orden.length > 0 && (
          <table className="w-full text-sm mb-3">
            <THead cols={["Material", "Cant.", "Unidad", "Subtotal", ""]} />
            <tbody className="divide-y divide-line">
              {orden.map((r, i) => (
                <tr key={i}>
                  <td className="py-1 pr-3 font-mono text-brand text-xs">{r.codigo.startsWith("h_") ? r.codigo.slice(2) : r.codigo}</td>
                  <td className="py-1 pr-3 text-right text-xs">{r.cantidad}</td>
                  <td className="py-1 pr-3 text-xs text-faint">{r.unidad}</td>
                  <td className="py-1 pr-3 text-right font-mono text-xs whitespace-nowrap">{fmtPreciso(r.costo)}</td>
                  <td className="py-1 text-right">
                    <button onClick={() => setOrden(o => o.filter((_, j) => j !== i))}
                      className="text-faint hover:text-bad text-xs px-1 transition-colors">✕</button>
                  </td>
                </tr>
              ))}
              <tr className="border-t-2 border-brand/30">
                <td colSpan={3} className="py-1.5 text-xs text-faint font-semibold">Total orden</td>
                <td className="py-1.5 text-right font-mono text-sm text-brand font-semibold whitespace-nowrap">{fmtPreciso(totalOrden)}</td>
                <td />
              </tr>
            </tbody>
          </table>
        )}

        {orden.length > 0 && (
          <button onClick={() => setOrden([])}
            className="text-xs text-faint hover:text-bad transition-colors">
            Limpiar orden
          </button>
        )}
      </SectionCard>
    </div>
  );
}
