"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import Link from "next/link";
import { FileText, Trash2, ChevronDown, ChevronUp, Plus, Upload, Settings } from "lucide-react";
import { useRouter } from "next/navigation";
import LegacyAppFrame from "@/components/layout/LegacyAppFrame";
import { usePreciosStore, initPreciosSync } from "@/lib/calculadora/store";
import {
  TAGS, emptyLine, calcularTotales, generateOdooText, parseImportText, fmtARS, generateCortesCode,
} from "@/lib/calculadora/engine";
import type { Block, TagType, PreciosData } from "@/lib/calculadora/engine";
import LineEditor from "@/components/calculadora/LineEditor";

const LS_BLOCKS = "fibro_presupuesto_v2";

const TAPACANTO_OPTIONS = [
  { value: "abs-encolado", label: "ABS encolado" },
  { value: "pvc-encolado", label: "PVC encolado" },
  { value: "pvc",          label: "PVC sin pegar" },
];

type TabId = "calc" | "avanzada";

function loadBlocks(): Block[] {
  if (typeof window === "undefined") return [];
  try {
    const s = localStorage.getItem(LS_BLOCKS);
    return s ? JSON.parse(s) : [];
  } catch { return []; }
}

function saveBlocksLS(blocks: Block[]) {
  if (typeof window === "undefined") return;
  localStorage.setItem(LS_BLOCKS, JSON.stringify(blocks));
}

// ── Tag color chips ──────────────────────────────────────────────────────────
const TAG_COLORS: Record<string, string> = {
  "#Mueble":   "bg-brand/20 text-brand",
  "#Corte":    "bg-sky-500/20 text-sky-400",
  "#Sobrante": "bg-faint/20 text-faint",
  "#Pino":     "bg-amber-500/20 text-amber-400",
  "#Cajón":    "bg-purple-500/20 text-purple-400",
  "#Placas":   "bg-teal-500/20 text-teal-400",
  "#Calado":   "bg-orange-500/20 text-orange-400",
  "#Círculo":  "bg-rose-500/20 text-rose-400",
  "#Adicional":"bg-yellow-500/20 text-yellow-400",
  "#Herraje":  "bg-slate-500/20 text-slate-400",
};

function tagChip(tag: TagType) {
  return TAG_COLORS[tag] ?? "bg-white/10 text-ink";
}

// ── Block card ───────────────────────────────────────────────────────────────
interface BlockCardProps {
  block:    Block;
  index:    number;
  data:     PreciosData;
  onChange: (b: Block) => void;
  onRemove: () => void;
}

function BlockCard({ block, index, data, onChange, onRemove }: BlockCardProps) {
  const [collapsed, setCollapsed] = useState(false);
  const set = (patch: Partial<Block>) => onChange({ ...block, ...patch });

  function addLine() {
    set({ lines: [...block.lines, emptyLine(block.tag)] });
  }

  function removeLine(i: number) {
    const lines = block.lines.filter((_, j) => j !== i);
    set({ lines: lines.length > 0 ? lines : [emptyLine(block.tag)] });
  }

  function updateLine(i: number, l: (typeof block.lines)[number]) {
    const lines = [...block.lines];
    lines[i] = l;
    set({ lines });
  }

  return (
    <div className="bg-surface border border-line rounded-xl overflow-hidden">
      {/* Header */}
      <div className="flex items-center gap-2 px-3 py-2 bg-white/3 border-b border-line">
        <span className={`text-xs font-mono px-2 py-0.5 rounded-full shrink-0 ${tagChip(block.tag)}`}>
          {block.tag}
        </span>
        <input
          value={block.title}
          onChange={e => set({ title: e.target.value })}
          placeholder={`Bloque ${index + 1}`}
          className="flex-1 min-w-0 bg-transparent border-0 text-sm text-ink outline-none placeholder:text-faint"
        />
        <select
          value={block.tapacanto}
          onChange={e => set({ tapacanto: e.target.value })}
          className="bg-transparent border-0 text-xs text-faint outline-none cursor-pointer"
        >
          {TAPACANTO_OPTIONS.map(o => (
            <option key={o.value} value={o.value}>{o.label}</option>
          ))}
        </select>
        <button onClick={() => setCollapsed(c => !c)} className="text-faint hover:text-ink transition-colors p-1">
          {collapsed ? <ChevronDown size={14} /> : <ChevronUp size={14} />}
        </button>
        <button onClick={onRemove} className="text-faint hover:text-bad transition-colors p-1">
          <Trash2 size={14} />
        </button>
      </div>

      {/* Lines */}
      {!collapsed && (
        <div className="flex flex-col gap-1 p-2">
          {block.lines.map((ln, i) => (
            <LineEditor
              key={i}
              tag={block.tag}
              line={ln}
              data={data}
              onChange={l => updateLine(i, l)}
              onRemove={() => removeLine(i)}
              onAddLine={addLine}
            />
          ))}
          <button
            onClick={addLine}
            className="flex items-center gap-1 text-xs text-faint hover:text-brand transition-colors mt-1 px-1"
          >
            <Plus size={12} /> Agregar línea
          </button>
        </div>
      )}
    </div>
  );
}

// ── Totals panel ─────────────────────────────────────────────────────────────
function TotalsPanel({ blocks, data }: {
  blocks: Block[];
  data: PreciosData;
}) {
  const t = calcularTotales(blocks, data);
  const margin = t.costoTotal > 0 ? ((t.precioFinal - t.costoTotal) / t.precioFinal * 100) : 0;

  return (
    <div className="bg-surface border border-line rounded-xl p-4 space-y-2">
      <div className="flex justify-between items-baseline">
        <span className="text-xs text-faint">Precio final</span>
        <span className="text-2xl font-bold text-brand font-mono">{fmtARS(t.precioFinal)}</span>
      </div>
      <div className="border-t border-line pt-2 space-y-1">
        {[
          ["Costo total",    t.costoTotal],
          ["Material",       t.costoMaterial],
          ["Tapacanto",      t.costoTapacanto],
          ["Pintura",        t.costoPintura],
          ["Herrajes",       t.costoHerrajes],
        ].map(([label, val]) => (
          <div key={label as string} className="flex justify-between text-xs">
            <span className="text-faint">{label as string}</span>
            <span className="font-mono text-ink">{fmtARS(val as number)}</span>
          </div>
        ))}
        <div className="flex justify-between text-xs border-t border-line pt-1">
          <span className="text-faint">Margen</span>
          <span className={`font-mono font-semibold ${margin >= 40 ? "text-brand" : margin >= 20 ? "text-amber-400" : "text-bad"}`}>
            {margin.toFixed(1)}%
          </span>
        </div>
      </div>
    </div>
  );
}

// ── Import modal ──────────────────────────────────────────────────────────────
function ImportModal({ onImport, onClose }: { onImport: (blocks: Block[]) => void; onClose: () => void }) {
  const [text, setText] = useState("");
  function handle() {
    const blocks = parseImportText(text);
    if (blocks.length > 0) { onImport(blocks); onClose(); }
  }
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
      <div className="bg-canvas border border-line rounded-2xl p-6 w-full max-w-lg flex flex-col gap-4">
        <h2 className="text-base font-semibold text-ink">Importar presupuesto</h2>
        <p className="text-xs text-faint">Pegá el texto de un presupuesto anterior (formato Odoo).</p>
        <textarea
          autoFocus
          value={text}
          onChange={e => setText(e.target.value)}
          rows={10}
          className="bg-white/5 border border-line rounded-lg p-3 text-sm text-ink outline-none focus:border-brand font-mono resize-none"
          placeholder="#Mueble | 2 de 600 x 400 en 18..."
        />
        <div className="flex gap-2 justify-end">
          <button onClick={onClose}
            className="px-4 py-1.5 text-sm rounded-lg border border-line text-faint hover:text-ink transition-colors">
            Cancelar
          </button>
          <button onClick={handle} disabled={!text.trim()}
            className="px-4 py-1.5 text-sm rounded-lg bg-brand text-white hover:bg-brand/90 disabled:opacity-40 transition-colors">
            Importar
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Page ──────────────────────────────────────────────────────────────────────
export default function CalculadoraPage() {
  const router = useRouter();
  const { data }  = usePreciosStore();

  const [tab,    setTab]    = useState<TabId>("calc");
  const [blocks, setBlocksState] = useState<Block[]>([]);
  const [showImport, setShowImport] = useState(false);
  const [importText, setImportText] = useState("");
  const [importCollapsed, setImportCollapsed] = useState(true);
  const syncedRef = useRef(false);

  // Load blocks from LS on mount
  useEffect(() => {
    const b = loadBlocks();
    setBlocksState(b.length > 0 ? b : []);
  }, []);

  // Init PB sync once
  useEffect(() => {
    if (syncedRef.current) return;
    syncedRef.current = true;
    initPreciosSync();
  }, []);

  const setBlocks = useCallback((b: Block[]) => {
    setBlocksState(b);
    saveBlocksLS(b);
  }, []);

  function addBlock(tag: TagType) {
    setBlocks([...blocks, {
      tag,
      title: "",
      tapacanto: "abs-encolado",
      lines: [emptyLine(tag)],
    }]);
  }

  function updateBlock(i: number, b: Block) {
    const next = [...blocks]; next[i] = b; setBlocks(next);
  }

  function removeBlock(i: number) {
    setBlocks(blocks.filter((_, j) => j !== i));
  }

  function importBlocks(b: Block[]) {
    setBlocks(b);
  }

  function clearAll() {
    if (blocks.length === 0 || !confirm("¿Limpiar todos los bloques?")) return;
    setBlocks([]);
  }

  function createBudgetFromCalculation() {
    const t = calcularTotales(blocks, data);
    const text = generateOdooText(blocks, t.precioFinal, data);
    if (typeof window !== "undefined") {
      sessionStorage.setItem("fibro_calc_presupuesto_nota", text);
      sessionStorage.setItem("fibro_calc_presupuesto_total", String(t.precioFinal));
    }
    router.push("/presupuestos/nuevo?from=calculadora");
  }

  const tabs: { id: TabId; label: string }[] = [
    { id: "calc",     label: "Calculadora" },
    { id: "avanzada", label: "Avanzada / IA" },
  ];

  return (
    <div className="flex flex-col h-full min-h-0">
      {/* Tab bar */}
      <div className="flex items-center gap-1 px-4 pt-4 border-b border-line shrink-0">
        {tabs.map(t => (
          <button
            key={t.id}
            onClick={() => setTab(t.id)}
            className={`px-4 py-2 text-sm rounded-t-lg border-b-2 transition-colors
              ${tab === t.id
                ? "border-brand text-brand font-medium"
                : "border-transparent text-faint hover:text-ink"
              }`}
          >
            {t.label}
          </button>
        ))}
        <Link
          href="/configuracion"
          className="ml-auto flex items-center gap-1.5 px-3 py-1.5 mb-1 text-xs text-faint hover:text-brand transition-colors rounded-lg border border-line"
          title="Editá precios y lógica en Configuración › Calculadora"
        >
          <Settings size={13} /> Precios y lógica
        </Link>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto p-4">

        {/* ── Calculadora tab ────────────────────────────────────────────── */}
        {tab === "calc" && (
          <div className="flex flex-col gap-4 max-w-4xl mx-auto">

            {/* Toolbar */}
            <div className="flex items-center gap-2 flex-wrap">
              <span className="text-xs text-faint">Agregar bloque:</span>
              {TAGS.map(tag => (
                <button
                  key={tag}
                  onClick={() => addBlock(tag)}
                  className={`text-xs px-2.5 py-1 rounded-full transition-colors hover:opacity-80 ${tagChip(tag)}`}
                >
                  {tag}
                </button>
              ))}
              <div className="ml-auto flex items-center gap-2">
                <button onClick={() => setShowImport(true)}
                  className="flex items-center gap-1 text-xs text-faint hover:text-ink transition-colors px-2 py-1 rounded border border-line">
                  <Upload size={12} /> Importar
                </button>
                {blocks.length > 0 && (
                  <button onClick={clearAll}
                    className="flex items-center gap-1 text-xs text-faint hover:text-bad transition-colors px-2 py-1 rounded border border-line">
                    <Trash2 size={12} /> Limpiar
                  </button>
                )}
              </div>
            </div>

            {/* Empty state */}
            {blocks.length === 0 && (
              <div className="flex flex-col items-center justify-center py-16 text-center">
                <p className="text-faint text-sm">Seleccioná un tag arriba para agregar el primer bloque.</p>
                <p className="text-faint/60 text-xs mt-1">O importá un presupuesto anterior.</p>
              </div>
            )}

            {/* Blocks */}
            <div className="flex flex-col gap-3">
              {blocks.map((b, i) => (
                <BlockCard
                  key={i}
                  block={b}
                  index={i}
                  data={data}
                  onChange={nb => updateBlock(i, nb)}
                  onRemove={() => removeBlock(i)}
                />
              ))}
            </div>

            {/* Subir código de cálculo (Tarjeta colapsable) */}
            <div className="bg-surface border border-line rounded-xl overflow-hidden">
              <button
                onClick={() => setImportCollapsed(c => !c)}
                className="flex items-center justify-between w-full px-4 py-3 bg-white/3 border-b border-line text-sm font-semibold text-ink"
              >
                <span>Subir código de cálculo</span>
                {importCollapsed ? <ChevronDown size={16} /> : <ChevronUp size={16} />}
              </button>
              {!importCollapsed && (
                <div className="p-4 space-y-3">
                  <textarea
                    value={importText}
                    onChange={e => setImportText(e.target.value)}
                    rows={6}
                    className="w-full bg-white/5 border border-line rounded-lg p-3 text-sm text-ink outline-none focus:border-brand font-mono resize-y"
                    placeholder="#Mueble | 2 de 600 x 400 en 18..."
                  />
                  <div className="flex justify-end">
                    <button
                      onClick={() => {
                        const parsed = parseImportText(importText);
                        if (parsed.length > 0) {
                          setBlocks(parsed);
                        } else {
                          alert("No se encontraron bloques válidos para cargar.");
                        }
                      }}
                      className="flex items-center gap-1.5 px-4 py-2 bg-brand text-white text-xs font-semibold rounded-lg hover:bg-brand-dark transition-all"
                    >
                      <Upload size={14} /> Cargar y corregir
                    </button>
                  </div>
                </div>
              )}
            </div>
 
            {/* Totals + copy */}
            {blocks.length > 0 && (
              <div className="flex flex-col gap-3 mt-2">
                <TotalsPanel blocks={blocks} data={data} />

                <div className="grid grid-cols-2 gap-3">
                  <button
                    onClick={() => {
                      const t = calcularTotales(blocks, data);
                      const text = generateOdooText(blocks, t.precioFinal, data);
                      navigator.clipboard.writeText(text);
                      alert("Código de cálculo copiado al portapapeles.");
                    }}
                    className="flex items-center justify-center gap-2 py-2 rounded-xl border border-line bg-surface text-ink text-xs font-semibold hover:bg-canvas transition-colors"
                  >
                    Copiar código de cálculo
                  </button>
                  <button
                    onClick={() => {
                      const text = generateCortesCode(blocks, data);
                      navigator.clipboard.writeText(text);
                      alert("Código de corte copiado al portapapeles.");
                    }}
                    className="flex items-center justify-center gap-2 py-2 rounded-xl border border-line bg-surface text-ink text-xs font-semibold hover:bg-canvas transition-colors"
                  >
                    Copiar código de corte
                  </button>
                </div>

                <button
                  onClick={createBudgetFromCalculation}
                  className="flex items-center justify-center gap-2 w-full py-2.5 rounded-xl
                    bg-brand text-white text-sm font-medium hover:bg-brand/90 transition-colors"
                >
                  <FileText size={16} />
                  Crear presupuesto
                </button>
              </div>
            )}
          </div>
        )}

        {/* ── App avanzada original ──────────────────────────────────────── */}
        {tab === "avanzada" && (
          <LegacyAppFrame
            title="Calculadora avanzada"
            description="Calculadora original con asistente IA, dictado, base de conocimiento, render e importación Odoo."
            src="/legacy/calculadora/index_lab.html"
          />
        )}
      </div>

      {/* Import modal */}
      {showImport && (
        <ImportModal onImport={importBlocks} onClose={() => setShowImport(false)} />
      )}
    </div>
  );
}
