import React, { useState, useRef } from "react";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";

export default function LiquidadorGananciaOcasional({ darkMode }) {
  const resultRef = useRef(null);

  const obtenerUVTPorYear = (year) => {
    const uvtPorYear = {
      2022: 38004,
      2023: 42412,
      2024: 47065,
      2025: 49799
    };
    return uvtPorYear[year] || 49799;
  };

  const [formData, setFormData] = useState({
    tipoInmueble: "habitacional",
    valorVenta: "",
    yearAdquisicion: new Date().getFullYear(),
    yearVenta: new Date().getFullYear(),
    metodosCostoFiscal: "historico",
    costoFiscalDeclaracion: "",
    comisionesVenta: "",
    otrosGastosVenta: "",
    destinoFondos: "otro",
    esDedicadoInmobiliaria: false
  });

  const [resultado, setResultado] = useState(null);
  const [mostrarResultado, setMostrarResultado] = useState(false);

  const tiposInmueble = [
    { value: "habitacional", label: "Inmueble Habitacional" },
    { value: "comercial", label: "Inmueble Comercial" },
    { value: "industrial", label: "Inmueble Industrial" },
    { value: "rural", label: "Inmueble Rural" },
    { value: "lote", label: "Lote o Terreno" }
  ];

  const destinosFondos = [
    { value: "otro", label: "Otro destino (sin exención)" },
    { value: "afc", label: "Depositar en AFC para nueva vivienda" },
    { value: "hipoteca", label: "Pago de crédito hipotecario" }
  ];

  const calcularGananciaOcasional = () => {
    const valorVenta = parseFloat(formData.valorVenta) || 0;
    const costoFiscal = parseFloat(formData.costoFiscalDeclaracion) || 0;
    const comisionesVenta = parseFloat(formData.comisionesVenta) || 0;
    const otrosGastosVenta = parseFloat(formData.otrosGastosVenta) || 0;

    const yearAdq = parseInt(formData.yearAdquisicion);
    const yearVta = parseInt(formData.yearVenta);
    const tenencia = yearVta - yearAdq;

    const tipoInmueble = tiposInmueble.find(t => t.value === formData.tipoInmueble)?.label;

    let errores = [];

    if (tenencia < 2) {
      errores.push("Menos de 2 años de tenencia - No aplica ganancia ocasional");
    }

    if (formData.esDedicadoInmobiliaria) {
      errores.push("Se dedica a la actividad inmobiliaria - No aplica ganancia ocasional");
    }

    const gastoVenta = comisionesVenta + otrosGastosVenta;
    const baseGravable = valorVenta - gastoVenta;
    const utilidadBruta = baseGravable - costoFiscal;

    let exencionVivienda = 0;
    let aplicaExencionVivienda = false;
    let razonNoExencion = "";

    if (formData.tipoInmueble === "habitacional" && tenencia >= 2 && !formData.esDedicadoInmobiliaria) {
      if (formData.destinoFondos === "afc" || formData.destinoFondos === "hipoteca") {
        const uvtVenta = obtenerUVTPorYear(yearVta);
        exencionVivienda = 5000 * uvtVenta;
        aplicaExencionVivienda = true;
      } else {
        razonNoExencion = "El destino de los fondos no cumple requisitos de exención";
      }
    } else if (formData.tipoInmueble === "habitacional" && tenencia < 2) {
      razonNoExencion = "Menos de 2 años de tenencia";
    } else if (formData.tipoInmueble === "habitacional" && formData.esDedicadoInmobiliaria) {
      razonNoExencion = "Titular dedicado a actividad inmobiliaria";
    } else {
      razonNoExencion = "No es vivienda de habitación - tasa del 20%";
    }

    const utilidadPositiva = Math.max(0, utilidadBruta);
    const utilidadExenta = aplicaExencionVivienda ? Math.min(exencionVivienda, utilidadPositiva) : 0;
    const utilidadGravable = Math.max(0, utilidadPositiva - utilidadExenta);

    const tasaPorYear = {
      2022: 0.10,
      2023: 0.15,
      2024: 0.15,
      2025: 0.15
    };
    const tasa = tasaPorYear[yearVta] || 0.15;
    const impuestoBasico = utilidadGravable * tasa;
    const retencion = impuestoBasico * 0.10;
    const impuestoNeto = impuestoBasico - retencion;

    setResultado({
      tipoInmueble,
      tenencia,
      valorVenta,
      costoFiscal,
      gastoVenta,
      baseGravable,
      utilidadBruta,
      aplicaExencionVivienda,
      exencionVivienda,
      utilidadExenta,
      utilidadPositiva,
      utilidadGravable,
      tasa,
      impuestoBasico,
      retencion,
      impuestoNeto,
      uvtAplicado: obtenerUVTPorYear(yearVta),
      razonNoExencion,
      tasaAplicada: tasa * 100,
      yearVenta: yearVta,
      errores: errores,
      esValido: errores.length === 0 && tenencia >= 2 && !formData.esDedicadoInmobiliaria
    });

    setMostrarResultado(true);
  };

  const descargarResultado = async (formato) => {
    if (!resultRef.current) return;

    try {
      const element = resultRef.current;
      const canvas = await html2canvas(element, {
        scale: 1.5,
        backgroundColor: "#ffffff",
        logging: false,
        useCORS: true,
        allowTaint: true,
        windowHeight: element.scrollHeight,
        windowWidth: element.scrollWidth
      });

      if (formato === "imagen") {
        const link = document.createElement("a");
        link.href = canvas.toDataURL("image/png");
        link.download = `liquidacion-ganancia-${new Date().getTime()}.png`;
        link.click();
      } else if (formato === "pdf") {
        const imgData = canvas.toDataURL("image/png");
        const pdf = new jsPDF({
          orientation: "p",
          unit: "mm",
          format: "a4"
        });

        const pageWidth = pdf.internal.pageSize.getWidth();
        const pageHeight = pdf.internal.pageSize.getHeight();
        const imgWidth = pageWidth - 10;
        const imgHeight = (canvas.height * imgWidth) / canvas.width;

        if (imgHeight <= pageHeight - 10) {
          pdf.addImage(imgData, "PNG", 5, 5, imgWidth, imgHeight);
        } else {
          const scale = (pageHeight - 10) / imgHeight;
          const scaledHeight = imgHeight * scale;
          const scaledWidth = imgWidth * scale;
          pdf.addImage(imgData, "PNG", 5, 5, scaledWidth, scaledHeight);
        }

        pdf.save(`liquidacion-ganancia-${new Date().getTime()}.pdf`);
      }
    } catch (error) {
      console.error("Error descargando:", error);
    }
  };

  const imprimirResultado = () => {
    if (!resultRef.current) return;
    const ventana = window.open("", "_blank");
    ventana.document.write(`
      <html>
        <head>
          <style>
            body { font-family: Arial, sans-serif; padding: 20px; }
            table { width: 100%; border-collapse: collapse; margin: 10px 0; }
            th, td { border: 1px solid #333; padding: 10px; text-align: right; }
            th { background-color: #1e3a8a; color: white; }
            .label { text-align: left; }
          </style>
        </head>
        <body>
          ${resultRef.current.innerHTML}
        </body>
      </html>
    `);
    ventana.document.close();
    setTimeout(() => ventana.print(), 250);
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const formatInputValue = (value) => {
    if (!value) return "";
    const num = parseFloat(value.replace(/\D/g, "")) || 0;
    return new Intl.NumberFormat("es-CO").format(num);
  };

  const handleCurrencyInput = (e) => {
    const { name, value } = e.target;
    const numericValue = value.replace(/\D/g, "");
    setFormData(prev => ({
      ...prev,
      [name]: numericValue
    }));
  };

  const resetForm = () => {
    setFormData({
      tipoInmueble: "habitacional",
      valorVenta: "",
      yearAdquisicion: new Date().getFullYear(),
      yearVenta: new Date().getFullYear(),
      metodosCostoFiscal: "historico",
      costoFiscalDeclaracion: "",
      comisionesVenta: "",
      otrosGastosVenta: "",
      destinoFondos: "otro",
      esDedicadoInmobiliaria: false
    });
    setMostrarResultado(false);
    setResultado(null);
  };

  const formatCurrency = (value) => {
    return new Intl.NumberFormat("es-CO", {
      style: "currency",
      currency: "COP",
      minimumFractionDigits: 0,
      maximumFractionDigits: 0
    }).format(value);
  };

  return (
    <div className={`p-6 max-w-6xl mx-auto ${darkMode ? 'bg-gray-900' : 'bg-gray-50'}`}>
      <div className={`border rounded-xl p-6 mb-8 ${
        darkMode
          ? 'bg-blue-900/20 border-blue-800'
          : 'bg-blue-50 border-blue-200'
      }`}>
        <div className="flex items-start gap-4">
          <div className={`w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0 ${
            darkMode
              ? 'bg-blue-800'
              : 'bg-blue-100'
          }`}>
            <span className={`material-icons ${
              darkMode ? 'text-blue-400' : 'text-blue-600'
            }`}>info</span>
          </div>
          <div>
            <h3 className={`text-lg font-semibold mb-2 ${
              darkMode ? 'text-blue-100' : 'text-blue-900'
            }`}>
              Liquidador de Ganancia Ocasional - Normativa Colombiana
            </h3>
            <p className={`text-sm ${
              darkMode ? 'text-blue-300' : 'text-blue-700'
            }`}>
              Cálculo según Estatuto Tributario Art. 277 y 311-1 (Ley 2277/2022). Requisito: Tenencia 2+ años, no dedicado a actividad inmobiliaria.
            </p>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div className="lg:col-span-1 space-y-6">
          <div className={`rounded-xl shadow-sm border p-6 ${
            darkMode
              ? 'bg-gray-800 border-gray-700'
              : 'bg-white border-gray-200'
          }`}>
            <h2 className={`text-xl font-bold mb-6 ${
              darkMode ? 'text-white' : 'text-gray-900'
            }`}>Datos del Inmueble</h2>

            <form className="space-y-4">
              <div>
                <label className={`block text-sm font-medium mb-2 ${
                  darkMode ? 'text-gray-300' : 'text-gray-700'
                }`}>
                  Tipo de Inmueble
                </label>
                <select
                  name="tipoInmueble"
                  value={formData.tipoInmueble}
                  onChange={handleInputChange}
                  className={`w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-500 ${
                    darkMode
                      ? 'bg-gray-700 border-gray-600 text-white'
                      : 'bg-white border-gray-300 text-gray-900'
                  }`}
                >
                  {tiposInmueble.map((tipo) => (
                    <option key={tipo.value} value={tipo.value}>
                      {tipo.label}
                    </option>
                  ))}
                </select>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className={`block text-sm font-medium mb-2 ${
                    darkMode ? 'text-gray-300' : 'text-gray-700'
                  }`}>
                    Año Compra
                  </label>
                  <input
                    type="number"
                    name="yearAdquisicion"
                    value={formData.yearAdquisicion}
                    onChange={handleInputChange}
                    min="1900"
                    max={new Date().getFullYear()}
                    className={`w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-500 ${
                      darkMode
                        ? 'bg-gray-700 border-gray-600 text-white'
                        : 'bg-white border-gray-300 text-gray-900'
                    }`}
                  />
                </div>
                <div>
                  <label className={`block text-sm font-medium mb-2 ${
                    darkMode ? 'text-gray-300' : 'text-gray-700'
                  }`}>
                    Año Venta
                  </label>
                  <input
                    type="number"
                    name="yearVenta"
                    value={formData.yearVenta}
                    onChange={handleInputChange}
                    min="1900"
                    max={new Date().getFullYear()}
                    className={`w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-500 ${
                      darkMode
                        ? 'bg-gray-700 border-gray-600 text-white'
                        : 'bg-white border-gray-300 text-gray-900'
                    }`}
                  />
                </div>
              </div>

              <div>
                <label className={`block text-sm font-medium mb-2 ${
                  darkMode ? 'text-gray-300' : 'text-gray-700'
                }`}>
                  Valor Venta
                </label>
                <input
                  type="text"
                  name="valorVenta"
                  value={formatInputValue(formData.valorVenta)}
                  onChange={handleCurrencyInput}
                  placeholder="$ 0"
                  className={`w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-500 ${
                    darkMode
                      ? 'bg-gray-700 border-gray-600 text-white'
                      : 'bg-white border-gray-300 text-gray-900'
                  }`}
                />
              </div>

              <div>
                <label className={`block text-sm font-medium mb-2 ${
                  darkMode ? 'text-gray-300' : 'text-gray-700'
                }`}>
                  Método de Costo Fiscal (Art. 277 ET)
                </label>
                <select
                  name="metodosCostoFiscal"
                  value={formData.metodosCostoFiscal}
                  onChange={handleInputChange}
                  className={`w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-500 text-sm ${
                    darkMode
                      ? 'bg-gray-700 border-gray-600 text-white'
                      : 'bg-white border-gray-300 text-gray-900'
                  }`}
                >
                  <option value="historico">Costo Histórico (Compra + Avalúos)</option>
                  <option value="autoavaluo">Autoavalúo / Avalúo Catastral</option>
                  <option value="reajuste280">Reajuste Fiscal Art. 280 ET</option>
                  <option value="reajuste73">Costo Fiscal Art. 73 ET</option>
                </select>
                <p className={`text-xs mt-1 ${
                  darkMode ? 'text-gray-400' : 'text-gray-500'
                }`}>
                  Reportado en declaración de renta año anterior
                </p>
              </div>

              <div>
                <label className={`block text-sm font-medium mb-2 ${
                  darkMode ? 'text-gray-300' : 'text-gray-700'
                }`}>
                  Costo Fiscal Declarado
                </label>
                <input
                  type="text"
                  name="costoFiscalDeclaracion"
                  value={formatInputValue(formData.costoFiscalDeclaracion)}
                  onChange={handleCurrencyInput}
                  placeholder="$ 0 - Valor en declaración anterior"
                  className={`w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-500 ${
                    darkMode
                      ? 'bg-gray-700 border-gray-600 text-white'
                      : 'bg-white border-gray-300 text-gray-900'
                  }`}
                />
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className={`block text-sm font-medium mb-2 ${
                    darkMode ? 'text-gray-300' : 'text-gray-700'
                  }`}>
                    Comisión Venta
                  </label>
                  <input
                    type="text"
                    name="comisionesVenta"
                    value={formatInputValue(formData.comisionesVenta)}
                    onChange={handleCurrencyInput}
                    placeholder="$ 0"
                    className={`w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-500 ${
                      darkMode
                        ? 'bg-gray-700 border-gray-600 text-white'
                        : 'bg-white border-gray-300 text-gray-900'
                    }`}
                  />
                </div>
                <div>
                  <label className={`block text-sm font-medium mb-2 ${
                    darkMode ? 'text-gray-300' : 'text-gray-700'
                  }`}>
                    Otros Gastos Venta
                  </label>
                  <input
                    type="text"
                    name="otrosGastosVenta"
                    value={formatInputValue(formData.otrosGastosVenta)}
                    onChange={handleCurrencyInput}
                    placeholder="$ 0"
                    className={`w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-500 ${
                      darkMode
                        ? 'bg-gray-700 border-gray-600 text-white'
                        : 'bg-white border-gray-300 text-gray-900'
                    }`}
                  />
                </div>
              </div>

              <div className={`border rounded-lg p-4 ${
                darkMode
                  ? 'bg-yellow-900/20 border-yellow-800'
                  : 'bg-yellow-50 border-yellow-200'
              }`}>
                <label className="flex items-center gap-3 cursor-pointer">
                  <input
                    type="checkbox"
                    name="esDedicadoInmobiliaria"
                    checked={formData.esDedicadoInmobiliaria}
                    onChange={(e) => setFormData(prev => ({
                      ...prev,
                      esDedicadoInmobiliaria: e.target.checked
                    }))}
                    className="w-4 h-4 rounded"
                  />
                  <span className={`text-sm font-medium ${
                    darkMode ? 'text-yellow-100' : 'text-yellow-900'
                  }`}>
                    ¿Se dedica a la actividad inmobiliaria?
                  </span>
                </label>
                <p className={`text-xs mt-2 ${
                  darkMode ? 'text-yellow-300' : 'text-yellow-800'
                }`}>
                  Si marca esta opción, no aplica ganancia ocasional
                </p>
              </div>

              {formData.tipoInmueble === "habitacional" && (
                <div>
                  <label className={`block text-sm font-medium mb-2 ${
                    darkMode ? 'text-gray-300' : 'text-gray-700'
                  }`}>
                    Destino de los Fondos
                  </label>
                  <select
                    name="destinoFondos"
                    value={formData.destinoFondos}
                    onChange={handleInputChange}
                    className={`w-full p-3 border rounded-lg focus:ring-2 focus:ring-blue-500 ${
                      darkMode
                        ? 'bg-gray-700 border-gray-600 text-white'
                        : 'bg-white border-gray-300 text-gray-900'
                    }`}
                  >
                    {destinosFondos.map((destino) => (
                      <option key={destino.value} value={destino.value}>
                        {destino.label}
                      </option>
                    ))}
                  </select>
                </div>
              )}

              <div className="flex gap-3 pt-4">
                <button
                  type="button"
                  onClick={resetForm}
                  className={`flex-1 px-4 py-3 border rounded-lg transition-colors font-medium text-sm ${
                    darkMode
                      ? 'border-gray-600 text-gray-300 hover:bg-gray-700'
                      : 'border-gray-300 text-gray-700 hover:bg-gray-50'
                  }`}
                >
                  Limpiar
                </button>
                <button
                  type="button"
                  onClick={calcularGananciaOcasional}
                  disabled={!formData.valorVenta || !formData.costoFiscalDeclaracion}
                  className={`flex-1 px-4 py-3 rounded-lg transition-colors font-medium text-sm text-white ${
                    !formData.valorVenta || !formData.costoFiscalDeclaracion
                      ? 'bg-gray-400 cursor-not-allowed'
                      : 'bg-blue-600 hover:bg-blue-700'
                  }`}
                >
                  Calcular
                </button>
              </div>
            </form>
          </div>
        </div>

        <div className="lg:col-span-2 space-y-6">
          {mostrarResultado && resultado && (
            <>
              {resultado.errores && resultado.errores.length > 0 && (
                <div className={`rounded-xl p-6 border ${
                  darkMode
                    ? 'bg-red-900/20 border-red-800'
                    : 'bg-red-50 border-red-200'
                }`}>
                  <h3 className={`font-bold mb-3 ${
                    darkMode ? 'text-red-100' : 'text-red-900'
                  }`}>Restricciones Legales</h3>
                  <ul className="space-y-2">
                    {resultado.errores.map((error, idx) => (
                      <li key={idx} className={`text-sm ${
                        darkMode ? 'text-red-300' : 'text-red-800'
                      }`}>
                        <span className="material-icons text-sm align-middle mr-2">block</span>
                        {error}
                      </li>
                    ))}
                  </ul>
                </div>
              )}

              {resultado.esValido && (
                <>
                  <div ref={resultRef} className={`rounded-xl shadow-sm border p-8 space-y-6 ${
                    darkMode
                      ? 'bg-gray-800 border-gray-700'
                      : 'bg-white border-gray-200'
                  }`}>
                    <div className={`text-center border-b-2 border-blue-600 pb-4`}>
                      <h2 className={`text-2xl font-bold ${
                        darkMode ? 'text-white' : 'text-gray-900'
                      }`}>
                        Liquidación de Ganancia Ocasional
                      </h2>
                      <p className={`text-sm mt-2 ${
                        darkMode ? 'text-gray-400' : 'text-gray-600'
                      }`}>
                        Año Gravable: {resultado.yearVenta} | UVT Aplicado: {formatCurrency(resultado.uvtAplicado)}
                      </p>
                    </div>

                    <div className={`grid grid-cols-2 gap-4 p-4 rounded-lg ${
                      darkMode
                        ? 'bg-gray-700/30'
                        : 'bg-gray-50'
                    }`}>
                      <div>
                        <span className={`text-sm ${
                          darkMode ? 'text-gray-400' : 'text-gray-600'
                        }`}>Tipo de Inmueble:</span>
                        <p className={`font-semibold ${
                          darkMode ? 'text-white' : 'text-gray-900'
                        }`}>{resultado.tipoInmueble}</p>
                      </div>
                      <div>
                        <span className={`text-sm ${
                          darkMode ? 'text-gray-400' : 'text-gray-600'
                        }`}>Tenencia:</span>
                        <p className={`font-semibold ${
                          darkMode ? 'text-white' : 'text-gray-900'
                        }`}>{resultado.tenencia} años</p>
                      </div>
                    </div>

                    <table className={`w-full text-sm`}>
                      <tbody className="space-y-2">
                        <tr className={darkMode ? 'bg-blue-900/20' : 'bg-blue-50'}>
                          <td className={`p-3 font-semibold ${
                            darkMode ? 'text-white' : 'text-gray-900'
                          }`}>Valor de Venta</td>
                          <td className={`p-3 text-right font-semibold ${
                            darkMode ? 'text-white' : 'text-gray-900'
                          }`}>{formatCurrency(resultado.valorVenta)}</td>
                        </tr>
                        <tr>
                          <td className={`p-3 ${
                            darkMode ? 'text-gray-400' : 'text-gray-600'
                          }`}>- Gastos de Venta</td>
                          <td className={`p-3 text-right ${
                            darkMode ? 'text-gray-400' : 'text-gray-600'
                          }`}>{formatCurrency(resultado.gastoVenta)}</td>
                        </tr>
                        <tr className={darkMode ? 'bg-green-900/20' : 'bg-green-50'}>
                          <td className={`p-3 font-semibold ${
                            darkMode ? 'text-white' : 'text-gray-900'
                          }`}>Base Gravable</td>
                          <td className={`p-3 text-right font-semibold ${
                            darkMode ? 'text-white' : 'text-gray-900'
                          }`}>{formatCurrency(resultado.baseGravable)}</td>
                        </tr>
                        <tr className={`border-t-2 ${
                          darkMode ? 'border-gray-600' : 'border-gray-300'
                        }`}>
                          <td className={`p-3 ${
                            darkMode ? 'text-gray-400' : 'text-gray-600'
                          }`}>- Costo Fiscal</td>
                          <td className={`p-3 text-right ${
                            darkMode ? 'text-gray-400' : 'text-gray-600'
                          }`}>{formatCurrency(resultado.costoFiscal)}</td>
                        </tr>
                        <tr className={`border-t-2 ${
                          darkMode 
                            ? 'bg-green-900/20 border-gray-600'
                            : 'bg-green-50 border-gray-300'
                        }`}>
                          <td className={`p-3 font-semibold ${
                            darkMode ? 'text-white' : 'text-gray-900'
                          }`}>Utilidad Bruta</td>
                          <td className={`p-3 text-right font-semibold ${
                            darkMode ? 'text-green-400' : 'text-green-600'
                          }`}>{formatCurrency(resultado.utilidadBruta)}</td>
                        </tr>

                        {resultado.aplicaExencionVivienda && (
                          <tr className={darkMode ? 'bg-yellow-900/20' : 'bg-yellow-50'}>
                            <td className={`p-3 font-semibold ${
                              darkMode ? 'text-white' : 'text-gray-900'
                            }`}>- Exención Vivienda (5.000 UVT)</td>
                            <td className={`p-3 text-right font-semibold ${
                              darkMode ? 'text-yellow-400' : 'text-yellow-600'
                            }`}>{formatCurrency(resultado.utilidadExenta)}</td>
                          </tr>
                        )}

                        {resultado.razonNoExencion && !resultado.aplicaExencionVivienda && (
                          <tr className={darkMode ? 'bg-red-900/20' : 'bg-red-50'}>
                            <td colSpan="2" className={`p-3 text-sm ${
                              darkMode ? 'text-red-300' : 'text-red-700'
                            }`}>
                              Sin Exención: {resultado.razonNoExencion}
                            </td>
                          </tr>
                        )}

                        <tr className={`border-t-2 ${
                          darkMode 
                            ? 'bg-blue-900/20 border-gray-600'
                            : 'bg-blue-50 border-gray-300'
                        }`}>
                          <td className={`p-3 font-semibold ${
                            darkMode ? 'text-white' : 'text-gray-900'
                          }`}>Utilidad Gravable</td>
                          <td className={`p-3 text-right font-semibold ${
                            darkMode ? 'text-blue-400' : 'text-blue-600'
                          }`}>{formatCurrency(resultado.utilidadGravable)}</td>
                        </tr>
                        <tr>
                          <td className={`p-3 ${
                            darkMode ? 'text-gray-400' : 'text-gray-600'
                          }`}>Tasa de Impuesto</td>
                          <td className={`p-3 text-right ${
                            darkMode ? 'text-gray-400' : 'text-gray-600'
                          }`}>{resultado.tasaAplicada}%</td>
                        </tr>
                        <tr className={darkMode ? 'bg-red-900/20' : 'bg-red-50'}>
                          <td className={`p-3 font-semibold ${
                            darkMode ? 'text-white' : 'text-gray-900'
                          }`}>Impuesto Básico</td>
                          <td className={`p-3 text-right font-semibold ${
                            darkMode ? 'text-red-400' : 'text-red-600'
                          }`}>{formatCurrency(resultado.impuestoBasico)}</td>
                        </tr>
                        <tr>
                          <td className={`p-3 ${
                            darkMode ? 'text-gray-400' : 'text-gray-600'
                          }`}>- Retención en la Fuente (10%)</td>
                          <td className={`p-3 text-right ${
                            darkMode ? 'text-gray-400' : 'text-gray-600'
                          }`}>{formatCurrency(resultado.retencion)}</td>
                        </tr>
                        <tr className={`border-t-2 bg-gradient-to-r from-blue-600 to-blue-700 text-white ${
                          darkMode ? 'border-gray-600' : 'border-gray-300'
                        }`}>
                          <td className="p-3 font-bold">Impuesto a Pagar</td>
                          <td className="p-3 text-right font-bold text-lg">{formatCurrency(resultado.impuestoNeto)}</td>
                        </tr>
                      </tbody>
                    </table>

                    <div className={`border rounded-lg p-4 ${
                      darkMode
                        ? 'bg-purple-900/20 border-purple-800'
                        : 'bg-purple-50 border-purple-200'
                    }`}>
                      <h4 className={`font-bold mb-3 ${
                        darkMode ? 'text-purple-100' : 'text-purple-900'
                      }`}>Marco Legal Aplicado</h4>
                      <ul className={`space-y-2 text-sm ${
                        darkMode ? 'text-purple-200' : 'text-purple-800'
                      }`}>
                        <li>Art. 277 ET: Costo Fiscal = Valor declaración año anterior</li>
                        <li>Art. 300 ET: Ganancia ocasional = Precio venta - Costo fiscal</li>
                        <li>Requisito: Tenencia mínima 2 años + No dedicarse a actividad inmobiliaria</li>
                        <li>Art. 311-1 ET: Exención 5.000 UVT para vivienda de habitación (Ley 2277/2022)</li>
                        <li>Tarifa: 10% (2022) | 15% (2023-2025)</li>
                      </ul>
                    </div>
                  </div>

                  <div className={`rounded-xl shadow-sm border p-6 flex gap-3 ${
                    darkMode
                      ? 'bg-gray-800 border-gray-700'
                      : 'bg-white border-gray-200'
                  }`}>
                    <button
                      onClick={imprimirResultado}
                      className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium"
                    >
                      <span className="material-icons">print</span>
                      <span className="hidden sm:inline">Imprimir</span>

                    </button>
                    <button
                      onClick={() => descargarResultado("pdf")}
                      className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors font-medium"
                    >
                      <span className="material-icons">picture_as_pdf</span>
                      <span className="hidden sm:inline" >
                      Descargar PDF </span>
                      <span className="lg:hidden">PDF</span> 
                    </button>
                    <button
                      onClick={() => descargarResultado("imagen")}
                      className="flex-1 flex items-center justify-center gap-2 px-4 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors font-medium"
                    >
                      <span className="material-icons">image</span>
                      <span className="hidden sm:inline" >
                      Descargar Imagen </span>
                      <span className="lg:hidden">JPG</span> 
                    </button>
                    
                  </div>
                </>
              )}

              {!resultado.esValido && resultado.errores.length > 0 && (
                <div className={`rounded-xl p-8 text-center border ${
                  darkMode
                    ? 'bg-red-900/20 border-red-800'
                    : 'bg-red-50 border-red-200'
                }`}>
                  <span className={`material-icons text-6xl block mb-4 ${
                    darkMode ? 'text-red-600' : 'text-red-300'
                  }`}>block</span>
                  <h3 className={`text-lg font-bold mb-2 ${
                    darkMode ? 'text-red-100' : 'text-red-900'
                  }`}>
                    No aplica ganancia ocasional
                  </h3>
                  <p className={darkMode ? 'text-red-300' : 'text-red-800'}>
                    Verifica los requisitos legales arriba indicados
                  </p>
                </div>
              )}
            </>
          )}

          {!mostrarResultado && (
            <div className={`rounded-xl border p-8 text-center ${
              darkMode
                ? 'bg-gray-800 border-gray-700'
                : 'bg-gray-50 border-gray-200'
            }`}>
              <span className={`material-icons text-6xl block mb-4 ${
                darkMode ? 'text-gray-600' : 'text-gray-300'
              }`}>description</span>
              <h3 className={`text-lg font-semibold mb-2 ${
                darkMode ? 'text-white' : 'text-gray-900'
              }`}>
                Completa los datos para generar la liquidación
              </h3>
              <p className={darkMode ? 'text-gray-400' : 'text-gray-600'}>
                Ingresa la información de tu transacción inmobiliaria para calcular automáticamente el impuesto según normativa colombiana
              </p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}