"use client";

import React, { useState } from "react";
import { useI18n } from "@/lib/i18n/context";
import {
  ShieldCheck,
  CheckCircle2,
  AlertTriangle,
  RotateCcw,
  Sparkles,
  ArrowRight,
  Cpu,
} from "lucide-react";

export function MathVerificationMatrix() {
  const { language } = useI18n();
  const isDe = language === "de";

  // Interactive discrepancy simulator state
  const [netAmount, setNetAmount] = useState<number>(100.0);
  const [taxRate, setTaxRate] = useState<19 | 7>(19);
  const [declaredGross, setDeclaredGross] = useState<number>(119.0);

  // Exact math calculation
  const calculatedTax = parseFloat(((netAmount * taxRate) / 100).toFixed(2));
  const expectedGross = parseFloat((netAmount + calculatedTax).toFixed(2));
  const diff = Math.abs(declaredGross - expectedGross);
  const isMathValid = diff <= 0.03; // Rundungstoleranz der Demo (die App rechnet betragsabhängig)

  const handleFixDiscrepancy = () => {
    setDeclaredGross(expectedGross);
  };

  return (
    <section className="py-20 px-4 sm:px-8 max-w-[1440px] mx-auto w-full font-sans border-b border-[#E2E8F0]">
      {/* Section Header */}
      <div className="flex flex-col md:flex-row md:items-end justify-between mb-12 gap-6">
        <div>
          <div className="flex items-center gap-2 mb-3">
            <span className="w-2.5 h-2.5 bg-black"></span>
            <span className="font-mono text-xs uppercase tracking-caps font-semibold text-[#475569]">
              {isDe ? "DETERMINISTISCHE MATHEMATIK-ENGINE" : "DETERMINISTIC MATH ENGINE"}
            </span>
          </div>
          <h2 className="font-display text-3xl sm:text-4xl md:text-5xl font-bold tracking-tight text-black max-w-2xl leading-[1.08]">
            {isDe
              ? "Jede Summe wird nachgerechnet, nicht geschätzt."
              : "Every total gets recalculated, not estimated."}
          </h2>
        </div>
        <p className="font-sans text-sm text-[#475569] max-w-md leading-relaxed">
          {isDe
            ? "KI-Modelle können Zahlen falsch lesen. ScanReceipts gleicht Netto, 7%/19% Vorsteuer und Brutto mit einer deterministischen Prüfmatrix ab."
            : "AI models can misread amounts. ScanReceipts cross-checks net, VAT splits, and gross with a deterministic verification matrix."}
        </p>
      </div>

      {/* Interactive Matrix Playground */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-center">
        {/* Left Side: Interactive Playground Controls (5 cols) */}
        <div className="lg:col-span-5 bg-white border border-[#E2E8F0] p-6 space-y-6">
          <div className="flex items-center justify-between pb-3 border-b border-[#E2E8F0]">
            <div className="flex items-center gap-2">
              <Cpu className="w-4 h-4 text-black" />
              <span className="font-mono text-xs uppercase tracking-caps font-bold text-black">
                {isDe ? "MATH-MATRIX PLAYGROUND" : "MATH MATRIX PLAYGROUND"}
              </span>
            </div>
            <span className="font-mono text-[10px] text-[#64748B] bg-[#F8FAFC] border border-[#E2E8F0] px-2 py-0.5">
              {isDe ? "TOLERANZ: ±0,03 € (RUNDUNG)" : "TOLERANCE: ±0.03 € (ROUNDING)"}
            </span>
          </div>

          {/* Inputs */}
          <div className="space-y-4 font-mono text-xs">
            <div>
              <label className="block text-[#64748B] uppercase tracking-caps mb-1">
                {isDe ? "1. Netto-Betrag (€):" : "1. Net Amount (€):"}
              </label>
              <input
                type="number"
                step="1"
                value={netAmount}
                onChange={(e) => setNetAmount(parseFloat(e.target.value) || 0)}
                className="w-full bg-[#F8FAFC] border border-[#E2E8F0] px-3 py-2 text-black font-bold focus:border-black focus:outline-none"
              />
            </div>

            <div>
              <label className="block text-[#64748B] uppercase tracking-caps mb-1">
                {isDe ? "2. Steuersatz (MwSt):" : "2. Tax Rate (VAT):"}
              </label>
              <div className="grid grid-cols-2 gap-2">
                <button
                  type="button"
                  onClick={() => {
                    setTaxRate(19);
                    setDeclaredGross(parseFloat((netAmount * 1.19).toFixed(2)));
                  }}
                  className={`py-2 text-center border transition-all ${
                    taxRate === 19
                      ? "bg-black text-white border-black font-bold"
                      : "bg-white text-black border-[#E2E8F0] hover:border-black"
                  }`}
                >
                  {isDe ? "19% Regelsteuersatz" : "19% Standard Tax"}
                </button>
                <button
                  type="button"
                  onClick={() => {
                    setTaxRate(7);
                    setDeclaredGross(parseFloat((netAmount * 1.07).toFixed(2)));
                  }}
                  className={`py-2 text-center border transition-all ${
                    taxRate === 7
                      ? "bg-black text-white border-black font-bold"
                      : "bg-white text-black border-[#E2E8F0] hover:border-black"
                  }`}
                >
                  {isDe ? "7% Ermäßigt" : "7% Reduced Tax"}
                </button>
              </div>
            </div>

            <div>
              <label className="block text-[#64748B] uppercase tracking-caps mb-1">
                {isDe ? "3. Gescannter Brutto-Betrag (€) (Probiere einen Fehler aus):" : "3. Scanned Gross Amount (€) (Try an error):"}
              </label>
              <input
                type="number"
                step="0.5"
                value={declaredGross}
                onChange={(e) => setDeclaredGross(parseFloat(e.target.value) || 0)}
                className="w-full bg-[#F8FAFC] border border-[#E2E8F0] px-3 py-2 text-black font-bold focus:border-black focus:outline-none"
              />
            </div>
          </div>

          {/* Simulate Discrepancy Buttons */}
          <div className="pt-2 flex flex-wrap gap-2">
            <button
              onClick={() => setDeclaredGross(parseFloat((expectedGross + 5.0).toFixed(2)))}
              className="px-3 py-1.5 bg-[#FEF3C7] text-[#92400E] border border-[#F59E0B] font-mono text-[10px] uppercase tracking-caps font-bold hover:bg-[#FDE68A] transition-colors"
            >
              {isDe ? "⚠️ Fehler simulieren (+5,00 €)" : "⚠️ Simulate Discrepancy (+5.00 €)"}
            </button>
            <button
              onClick={handleFixDiscrepancy}
              className="px-3 py-1.5 bg-black text-white font-mono text-[10px] uppercase tracking-caps font-bold hover:bg-[#334155] transition-colors"
            >
              {isDe ? "✓ Mathematisch korrigieren" : "✓ Fix Math Total"}
            </button>
          </div>
        </div>

        {/* Right Side: Visual Ledger & Live Equation (7 cols) */}
        <div className="lg:col-span-7 bg-white border border-[#E2E8F0] p-6 flex flex-col justify-between">
          <div className="space-y-6">
            {/* Status Banner */}
            <div
              className={`p-4 border font-mono text-xs flex items-center justify-between ${
                isMathValid
                  ? "bg-[#EEF4FC] border-[#E2E8F0] text-black"
                  : "bg-[#FEF3C7] border-[#F59E0B] text-[#92400E]"
              }`}
            >
              <div className="flex items-center gap-3">
                {isMathValid ? (
                  <CheckCircle2 className="w-5 h-5 text-emerald-600 shrink-0" />
                ) : (
                  <AlertTriangle className="w-5 h-5 text-[#F59E0B] shrink-0" />
                )}
                <div>
                  <div className="font-bold uppercase tracking-caps">
                    {isDe
                      ? isMathValid
                        ? "PLAUSIBILITÄT: BESTÄTIGT (SUMME STIMMT)"
                        : "DISKREPANZ ERKANNT: 1-KLICK PRÜFUNG ERFORDERLICH"
                      : isMathValid
                      ? "MATH AUDIT: VERIFIED (SUM MATCHES)"
                      : "DISCREPANCY DETECTED: 1-CLICK REVIEW REQUIRED"}
                  </div>
                  <div className="text-[11px] opacity-80">
                    {isDe
                      ? isMathValid
                        ? "Netto + MwSt entspricht exakt dem Bruttobetrag."
                        : `Differenz von ${(declaredGross - expectedGross).toFixed(2)} € festgestellt. Determinismus-Engine schlägt Korrektur vor.`
                      : isMathValid
                      ? "Net + Tax matches the gross total exactly."
                      : `Discrepancy of ${(declaredGross - expectedGross).toFixed(2)} € detected. Engine suggests instant correction.`}
                  </div>
                </div>
              </div>
            </div>

            {/* Visual Math Ledger Formula */}
            <div className="p-6 bg-[#F8FAFC] border border-[#E2E8F0] font-mono text-sm space-y-4">
              <div className="text-xs text-[#64748B] uppercase tracking-caps border-b border-[#E2E8F0] pb-2">
                {isDe ? "DETERMINISTISCHE GLEICHUNG:" : "DETERMINISTIC EQUATION:"}
              </div>

              <div className="grid grid-cols-3 gap-4 text-center items-center">
                <div className="p-3 bg-white border border-[#E2E8F0]">
                  <div className="text-[10px] text-[#64748B] uppercase">{isDe ? "NETTO" : "NET"}</div>
                  <div className="text-base font-bold text-black">
                    {netAmount.toFixed(2)} €
                  </div>
                </div>

                <div className="p-3 bg-white border border-[#E2E8F0]">
                  <div className="text-[10px] text-[#64748B] uppercase">
                    {isDe ? "MWST" : "TAX"} ({taxRate}%)
                  </div>
                  <div className="text-base font-bold text-black">
                    {calculatedTax.toFixed(2)} €
                  </div>
                </div>

                <div
                  className={`p-3 border ${
                    isMathValid
                      ? "bg-white border-[#E2E8F0]"
                      : "bg-[#FEF3C7] border-[#F59E0B]"
                  }`}
                >
                  <div className="text-[10px] text-[#64748B] uppercase">
                    {isDe ? "BERECHNETES BRUTTO" : "CALCULATED GROSS"}
                  </div>
                  <div className="text-base font-bold text-black">
                    {expectedGross.toFixed(2)} €
                  </div>
                </div>
              </div>

              <div className="pt-2 text-center text-xs font-mono text-black font-semibold">
                {isDe ? "GLEICHUNG:" : "EQUATION:"} {isDe ? "Netto" : "Net"} ({netAmount.toFixed(2)} €) + {isDe ? "MwSt" : "Tax"} ({calculatedTax.toFixed(2)} €) = {expectedGross.toFixed(2)} € ({isDe ? "Brutto" : "Gross"})
              </div>
            </div>
          </div>

          <div className="mt-6 pt-4 border-t border-[#E2E8F0] flex items-center justify-between font-mono text-xs text-[#64748B]">
            <span>{isDe ? "Prüfung: Deterministische Rechnung im Browser" : "Verification: Deterministic math in browser"}</span>
            <span className="text-black font-semibold">Netto + MwSt = Brutto</span>
          </div>
        </div>
      </div>
    </section>
  );
}
