"use client";

import React, { useState, useEffect, useRef } from "react";
import { useI18n } from "@/lib/i18n/context";
import {
  FileSpreadsheet,
  Scan,
  CheckCircle2,
  Cpu,
  Layers,
  Sparkles,
  ArrowRight,
  Download,
  Eye,
  ShieldCheck,
} from "lucide-react";
import gsap from "gsap";

interface DemoPreset {
  id: string;
  nameDe: string;
  nameEn: string;
  categoryDe: string;
  categoryEn: string;
  merchant: string;
  date: string;
  net: number;
  tax7: number;
  tax19: number;
  gross: number;
  items: { desc: string; qty: number; price: number; tax: number }[];
  boundingHighlights: { label: string; x: string; y: string; w: string; h: string }[];
}

const DEMO_PRESETS: DemoPreset[] = [
  {
    id: "aral",
    nameDe: "Aral Tankstelle",
    nameEn: "Aral Gas Station",
    categoryDe: "KFZ & Treibstoff",
    categoryEn: "Fuel & Vehicle",
    merchant: "Aral Station 4920 München",
    date: "2026-08-14",
    net: 75.63,
    tax7: 0.0,
    tax19: 14.37,
    gross: 90.0,
    items: [
      { desc: "Super E10 (45.23 L @ 1.769€)", qty: 1, price: 80.01, tax: 19 },
      { desc: "Scheibenenteiser 500ml", qty: 1, price: 9.99, tax: 19 },
    ],
    boundingHighlights: [
      { label: "MERCHANT", x: "10%", y: "12%", w: "80%", h: "8%" },
      { label: "DATE", x: "10%", y: "24%", w: "45%", h: "6%" },
      { label: "LINE_ITEMS", x: "10%", y: "36%", w: "80%", h: "28%" },
      { label: "TAX_19%", x: "10%", y: "68%", w: "80%", h: "8%" },
      { label: "TOTAL_GROSS", x: "10%", y: "78%", w: "80%", h: "10%" },
    ],
  },
  {
    id: "rewe",
    nameDe: "REWE Supermarkt",
    nameEn: "REWE Supermarket",
    categoryDe: "Verpflegung & Bürobedarf",
    categoryEn: "Groceries & Office",
    merchant: "REWE Markt GmbH Köln",
    date: "2026-08-15",
    net: 38.46,
    tax7: 1.82,
    tax19: 2.12,
    gross: 42.4,
    items: [
      { desc: "Bio Kaffeebohnen 1kg", qty: 1, price: 14.99, tax: 7 },
      { desc: "Hafermilch Barista 1L", qty: 3, price: 7.47, tax: 7 },
      { desc: "Druckerpapier A4 500 Blatt", qty: 2, price: 13.98, tax: 19 },
      { desc: "Glas-Pfand Rückgabe", qty: 1, price: -0.5, tax: 19 },
      { desc: "Bio Äpfel 1.5kg", qty: 1, price: 6.46, tax: 7 },
    ],
    boundingHighlights: [
      { label: "MERCHANT", x: "15%", y: "8%", w: "70%", h: "7%" },
      { label: "DATE", x: "10%", y: "18%", w: "40%", h: "5%" },
      { label: "SPLIT_TAX_ITEMS", x: "10%", y: "28%", w: "80%", h: "42%" },
      { label: "TAX_SPLIT (7%/19%)", x: "10%", y: "73%", w: "80%", h: "8%" },
      { label: "SUMME_EUR", x: "10%", y: "83%", w: "80%", h: "9%" },
    ],
  },
  {
    id: "trattoria",
    nameDe: "Trattoria Bella Vista",
    nameEn: "Trattoria Restaurant",
    categoryDe: "Bewirtung (§4 Abs. 5 EStG)",
    categoryEn: "Meals & Entertainment",
    merchant: "Trattoria Bella Vista Berlin",
    date: "2026-08-12",
    net: 113.45,
    tax7: 0.0,
    tax19: 21.55,
    gross: 135.0,
    items: [
      { desc: "2x Business Lunch Menu", qty: 2, price: 68.0, tax: 19 },
      { desc: "San Pellegrino 0.75L", qty: 2, price: 14.0, tax: 19 },
      { desc: "2x Espresso Doppio", qty: 2, price: 9.0, tax: 19 },
      { desc: "Trinkgeld (Freiwillig bar)", qty: 1, price: 15.0, tax: 0 },
      { desc: "Dessert Tiramisu", qty: 2, price: 18.0, tax: 19 },
    ],
    boundingHighlights: [
      { label: "BEWIRTUNG_HEADER", x: "10%", y: "10%", w: "80%", h: "8%" },
      { label: "ANLASS & PERSONEN", x: "10%", y: "20%", w: "80%", h: "12%" },
      { label: "BEWIRTUNG_SPEISEN", x: "10%", y: "35%", w: "80%", h: "35%" },
      { label: "MWST_19%", x: "10%", y: "73%", w: "80%", h: "7%" },
      { label: "TOTAL_INKL_TRINKGELD", x: "10%", y: "82%", w: "80%", h: "10%" },
    ],
  },
];

export function InteractiveProductDemo() {
  const { language } = useI18n();
  const isDe = language === "de";
  const [activePreset, setActivePreset] = useState<DemoPreset>(DEMO_PRESETS[0]);
  const [activeTab, setActiveTab] = useState<"sheet1" | "sheet2">("sheet1");
  const [hoveredField, setHoveredField] = useState<string | null>(null);
  const [isScanningAnim, setIsScanningAnim] = useState<boolean>(false);

  const containerRef = useRef<HTMLDivElement>(null);
  const laserRef = useRef<HTMLDivElement>(null);

  // Trigger smooth GSAP scan pulse when preset changes
  useEffect(() => {
    setIsScanningAnim(true);
    if (laserRef.current) {
      gsap.fromTo(
        laserRef.current,
        { top: "0%", opacity: 0.8 },
        {
          top: "100%",
          opacity: 0.8,
          duration: 1.2,
          ease: "power2.inOut",
          onComplete: () => setIsScanningAnim(false),
        }
      );
    }
  }, [activePreset]);

  return (
    <section
      ref={containerRef}
      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]">
              INTERAKTIVER PRODUKT-SIMULATOR
            </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
              ? "Vom unleserlichen Beleg zur perfekten Excel-Tabelle."
              : "From crumpled receipt to verified Dual-Sheet Excel."}
          </h2>
        </div>
        <p className="font-sans text-sm text-[#475569] max-w-md leading-relaxed">
          {isDe
            ? "Wähle einen typischen deutschen Beleg und beobachte, wie die multimodale KI-Engine Text extrahiert, Steuersätze prüft und native Excel-Formeln generiert."
            : "Select a real-world receipt and see how multimodal AI extracts text, verifies tax rates, and compiles native Excel formulas."}
        </p>
      </div>

      {/* Preset Selector Bar */}
      <div className="flex flex-wrap items-center gap-2 sm:gap-3 mb-8">
        <span className="font-mono text-xs text-[#64748B] uppercase tracking-caps mr-2 hidden sm:inline">
          {isDe ? "BELEG-BEISPIEL:" : "RECEIPT SAMPLE:"}
        </span>
        {DEMO_PRESETS.map((preset) => (
          <button
            key={preset.id}
            onClick={() => setActivePreset(preset)}
            className={`px-4 py-2.5 font-mono text-xs uppercase tracking-caps transition-all flex items-center gap-2 border ${
              activePreset.id === preset.id
                ? "bg-black text-white border-black"
                : "bg-white text-[#475569] border-[#E2E8F0] hover:border-black hover:text-black"
            }`}
          >
            <Scan className="w-3.5 h-3.5" />
            <span className="font-medium">{isDe ? preset.nameDe : preset.nameEn}</span>
            <span
              className={`text-[10px] px-1.5 py-0.5 border ${
                activePreset.id === preset.id
                  ? "bg-white/20 border-white/30 text-white"
                  : "bg-[#F8FAFC] border-[#E2E8F0] text-[#64748B]"
              }`}
            >
              {(isDe ? preset.categoryDe : preset.categoryEn).split(" ")[0]}
            </span>
          </button>
        ))}
      </div>

      {/* Main Interactive Dual-Screen Canvas */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
        {/* Left Column: Multimodal OCR Vision Scanner (5 cols) */}
        <div className="lg:col-span-5 bg-white border border-[#E2E8F0] p-6 flex flex-col relative overflow-hidden">
          {/* Top Telemetry Bar */}
          <div className="flex items-center justify-between pb-4 mb-4 border-b border-[#E2E8F0]">
            <div className="flex items-center gap-2">
              <div className="w-2 h-2 bg-emerald-500 animate-pulse"></div>
              <span className="font-mono text-[11px] uppercase tracking-caps text-black font-semibold">
                {isDe ? "KI-VISION // OCR TRACKER" : "AI VISION // OCR TRACKER"}
              </span>
            </div>
            <span className="font-mono text-[10px] bg-[#EEF4FC] border border-[#E2E8F0] px-2 py-0.5 text-[#475569]">
              CONFIDENCE 94%
            </span>
          </div>

          {/* Receipt Mockup with Interactive Bounding Boxes */}
          <div className="relative bg-[#F8FAFC] border border-[#E2E8F0] p-6 font-mono text-xs text-black min-h-[420px] flex flex-col justify-between select-none overflow-hidden">
            {/* Animated Laser Scanline */}
            <div
              ref={laserRef}
              className="absolute left-0 right-0 h-0.5 bg-black z-20 pointer-events-none"
              style={{ opacity: isScanningAnim ? 0.8 : 0 }}
            />

            {/* Bounding Box Overlays */}
            {activePreset.boundingHighlights.map((box, idx) => (
              <div
                key={idx}
                onMouseEnter={() => setHoveredField(box.label)}
                onMouseLeave={() => setHoveredField(null)}
                className={`absolute border border-dashed transition-all z-10 cursor-pointer ${
                  hoveredField === box.label
                    ? "border-black bg-black/10 scale-[1.01]"
                    : "border-black/30 hover:border-black bg-black/5"
                }`}
                style={{
                  top: box.y,
                  left: box.x,
                  width: box.w,
                  height: box.h,
                }}
              >
                <span className="absolute -top-3 left-1 bg-black text-white text-[8px] font-mono px-1 py-0.2 uppercase tracking-tight">
                  {box.label}
                </span>
              </div>
            ))}

            {/* Thermal Receipt Text Mockup */}
            <div className="space-y-4 pt-2">
              <div className="text-center pb-2 border-b border-black/20">
                <div className="font-bold text-sm tracking-wider uppercase">
                  {activePreset.merchant}
                </div>
                <div className="text-[10px] text-[#64748B]">
                  DE-STEUER-NR: 143/284/90123 • UST-ID: DE814920491
                </div>
                <div className="text-[10px] text-[#64748B]">
                  {isDe ? "DATUM:" : "DATE:"} {activePreset.date} • {isDe ? "UHRZEIT:" : "TIME:"} 14:32:10
                </div>
              </div>

              {/* Items List */}
              <div className="space-y-1 py-1">
                {activePreset.items.map((item, i) => (
                  <div key={i} className="flex justify-between text-[11px]">
                    <span className="truncate max-w-[200px]">{item.desc}</span>
                    <span className="font-semibold whitespace-nowrap">
                      {item.price.toFixed(2)} € (B {item.tax}%)
                    </span>
                  </div>
                ))}
              </div>

              {/* Tax & Total calculation */}
              <div className="border-t border-black/20 pt-2 space-y-1 text-[11px]">
                <div className="flex justify-between text-[#64748B]">
                  <span>{isDe ? "NETTO:" : "NET:"}</span>
                  <span>{activePreset.net.toFixed(2)} €</span>
                </div>
                {activePreset.tax7 > 0 && (
                  <div className="flex justify-between text-[#64748B]">
                    <span>{isDe ? "MWST 7%:" : "TAX 7%:"}</span>
                    <span>{activePreset.tax7.toFixed(2)} €</span>
                  </div>
                )}
                {activePreset.tax19 > 0 && (
                  <div className="flex justify-between text-[#64748B]">
                    <span>{isDe ? "MWST 19%:" : "TAX 19%:"}</span>
                    <span>{activePreset.tax19.toFixed(2)} €</span>
                  </div>
                )}
                <div className="flex justify-between font-bold text-sm border-t border-black pt-1">
                  <span>{isDe ? "GESAMT (EUR):" : "TOTAL (EUR):"}</span>
                  <span>{activePreset.gross.toFixed(2)} €</span>
                </div>
              </div>
            </div>

            {/* Receipt Footer */}
            <div className="text-center text-[9px] text-[#64748B] pt-4 border-t border-dashed border-black/20">
              {isDe ? "TSE-SIGNATUR: qB94_xL902_V1_OK • VIELEN DANK FÜR IHREN EINKAUF" : "TSE-SIGNATURE: qB94_xL902_V1_OK • THANK YOU FOR YOUR PURCHASE"}
            </div>
          </div>

          {/* Under-Scanner Info */}
          <div className="mt-4 flex items-center justify-between font-mono text-xs text-[#64748B]">
            <span className="flex items-center gap-1.5">
              <Cpu className="w-3.5 h-3.5 text-black" />
              <span>Bounding Coordinates Auto-Lock</span>
            </span>
            <span className="text-black font-semibold">{isDe ? "Jede Summe nachgerechnet" : "Every total verified"}</span>
          </div>
        </div>

        {/* Right Column: Interactive Dual-Sheet Excel Simulator (7 cols) */}
        <div className="lg:col-span-7 bg-white border border-[#E2E8F0] p-6 flex flex-col justify-between">
          {/* Header Bar */}
          <div>
            <div className="flex flex-col sm:flex-row sm:items-center justify-between pb-4 mb-4 border-b border-[#E2E8F0] gap-3">
              <div className="flex items-center gap-2">
                <FileSpreadsheet className="w-4 h-4 text-black" />
                <span className="font-mono text-xs uppercase tracking-caps font-bold text-black">
                  DUAL-SHEET EXCEL ENGINE (.XLSX)
                </span>
              </div>
              <div className="flex items-center gap-2">
                <span className="font-mono text-[10px] bg-[#EEF4FC] text-black border border-[#E2E8F0] px-2 py-0.5 font-medium">
                  {isDe ? "FORMEL: =SUM(G2:G10)" : "FORMULA: =SUM(G2:G10)"}
                </span>
                <span className="font-mono text-[10px] bg-black text-white px-2 py-0.5 font-medium">
                  {isDe ? "NATIV FORMEL-KOMPATIBEL" : "NATIVE FORMULA COMPATIBLE"}
                </span>
              </div>
            </div>

            {/* Excel Sheet Switcher Tabs */}
            <div className="flex items-center gap-1 mb-4 border-b border-[#E2E8F0]">
              <button
                onClick={() => setActiveTab("sheet1")}
                className={`px-4 py-2 font-mono text-xs uppercase tracking-caps transition-colors flex items-center gap-2 border-b-2 ${
                  activeTab === "sheet1"
                    ? "border-black text-black font-bold bg-[#F8FAFC]"
                    : "border-transparent text-[#64748B] hover:text-black"
                }`}
              >
                <Layers className="w-3.5 h-3.5" />
                <span>{isDe ? "SHEET 1: ZUSAMMENFASSUNG" : "SHEET 1: SUMMARY"}</span>
              </button>
              <button
                onClick={() => setActiveTab("sheet2")}
                className={`px-4 py-2 font-mono text-xs uppercase tracking-caps transition-colors flex items-center gap-2 border-b-2 ${
                  activeTab === "sheet2"
                    ? "border-black text-black font-bold bg-[#F8FAFC]"
                    : "border-transparent text-[#64748B] hover:text-black"
                }`}
              >
                <Layers className="w-3.5 h-3.5" />
                <span>{isDe ? "SHEET 2: EINZELPOSITIONEN" : "SHEET 2: LINE ITEMS"}</span>
              </button>
            </div>

            {/* Formula Bar Simulation */}
            <div className="flex items-center gap-2 px-3 py-1.5 bg-[#F8FAFC] border border-[#E2E8F0] mb-4 font-mono text-xs">
              <span className="text-[#64748B] font-bold">fx</span>
              <span className="text-black font-semibold">
                {activeTab === "sheet1"
                  ? `=SUM(G2:G${DEMO_PRESETS.length + 1})`
                  : `=C2*D2`}
              </span>
            </div>

            {/* Spreadsheet Table View */}
            <div className="border border-[#E2E8F0] overflow-x-auto">
              {activeTab === "sheet1" ? (
                /* Sheet 1: Summary */
                <table className="w-full text-left font-mono text-xs border-collapse">
                  <thead>
                    <tr className="bg-[#F8FAFC] text-black border-b border-[#E2E8F0] text-[11px] uppercase tracking-caps">
                      <th className="p-2 border-r border-[#E2E8F0]">A: ID</th>
                      <th className="p-2 border-r border-[#E2E8F0]">B: {isDe ? "DATUM" : "DATE"}</th>
                      <th className="p-2 border-r border-[#E2E8F0]">C: {isDe ? "HÄNDLER" : "MERCHANT"}</th>
                      <th className="p-2 border-r border-[#E2E8F0]">D: {isDe ? "KATEGORIE" : "CATEGORY"}</th>
                      <th className="p-2 border-r border-[#E2E8F0] text-right">E: {isDe ? "NETTO" : "NET"}</th>
                      <th className="p-2 border-r border-[#E2E8F0] text-right">F: {isDe ? "MWST 19%" : "TAX 19%"}</th>
                      <th className="p-2 text-right">G: {isDe ? "BRUTTO" : "GROSS"}</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-[#E2E8F0] bg-white">
                    {DEMO_PRESETS.map((p, idx) => (
                      <tr
                        key={p.id}
                        className={`transition-colors ${
                          p.id === activePreset.id
                            ? "bg-[#EEF4FC] font-semibold"
                            : "hover:bg-[#F8FAFC]"
                        }`}
                      >
                        <td className="p-2 border-r border-[#E2E8F0] text-[#64748B]">
                          REC-00{idx + 1}
                        </td>
                        <td className="p-2 border-r border-[#E2E8F0]">{p.date}</td>
                        <td className="p-2 border-r border-[#E2E8F0] text-black">
                          {p.merchant.split(" ")[0]} {p.merchant.split(" ")[1]}
                        </td>
                        <td className="p-2 border-r border-[#E2E8F0] text-[#475569]">
                          {(isDe ? p.categoryDe : p.categoryEn).split(" ")[0]}
                        </td>
                        <td className="p-2 border-r border-[#E2E8F0] text-right">
                          {p.net.toFixed(2)} €
                        </td>
                        <td className="p-2 border-r border-[#E2E8F0] text-right">
                          {p.tax19.toFixed(2)} €
                        </td>
                        <td className="p-2 text-right font-bold text-black">
                          {p.gross.toFixed(2)} €
                        </td>
                      </tr>
                    ))}
                    {/* Native SUM Formula Total Row */}
                    <tr className="bg-black text-white font-bold">
                      <td colSpan={4} className="p-2 border-r border-white/20 uppercase tracking-caps">
                        {isDe ? "SUMMEN (FORMEL =SUM)" : "TOTALS (FORMULA =SUM)"}
                      </td>
                      <td className="p-2 border-r border-white/20 text-right">
                        {DEMO_PRESETS.reduce((acc, p) => acc + p.net, 0).toFixed(2)} €
                      </td>
                      <td className="p-2 border-r border-white/20 text-right">
                        {DEMO_PRESETS.reduce((acc, p) => acc + p.tax19, 0).toFixed(2)} €
                      </td>
                      <td className="p-2 text-right text-white">
                        {DEMO_PRESETS.reduce((acc, p) => acc + p.gross, 0).toFixed(2)} €
                      </td>
                    </tr>
                  </tbody>
                </table>
              ) : (
                /* Sheet 2: Line Items */
                <table className="w-full text-left font-mono text-xs border-collapse">
                  <thead>
                    <tr className="bg-[#F8FAFC] text-black border-b border-[#E2E8F0] text-[11px] uppercase tracking-caps">
                      <th className="p-2 border-r border-[#E2E8F0]">A: {isDe ? "BELEG" : "RECEIPT"}</th>
                      <th className="p-2 border-r border-[#E2E8F0]">B: {isDe ? "POSITION" : "ITEM"}</th>
                      <th className="p-2 border-r border-[#E2E8F0] text-center">C: {isDe ? "MENGE" : "QTY"}</th>
                      <th className="p-2 border-r border-[#E2E8F0] text-right">D: {isDe ? "STÜCK (€)" : "UNIT (€)"}</th>
                      <th className="p-2 border-r border-[#E2E8F0] text-center">E: {isDe ? "MWST %" : "TAX %"}</th>
                      <th className="p-2 text-right">F: {isDe ? "GESAMT (€)" : "TOTAL (€)"}</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-[#E2E8F0] bg-white">
                    {activePreset.items.map((item, idx) => (
                      <tr key={idx} className="hover:bg-[#F8FAFC]">
                        <td className="p-2 border-r border-[#E2E8F0] text-[#64748B]">
                          {(isDe ? activePreset.nameDe : activePreset.nameEn).split(" ")[0]}
                        </td>
                        <td className="p-2 border-r border-[#E2E8F0] text-black">
                          {item.desc}
                        </td>
                        <td className="p-2 border-r border-[#E2E8F0] text-center">
                          {item.qty}
                        </td>
                        <td className="p-2 border-r border-[#E2E8F0] text-right">
                          {(item.price / (item.qty || 1)).toFixed(2)} €
                        </td>
                        <td className="p-2 border-r border-[#E2E8F0] text-center">
                          {item.tax}%
                        </td>
                        <td className="p-2 text-right font-bold text-black">
                          {item.price.toFixed(2)} €
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </div>
          </div>

          {/* Bottom Features Strip */}
          <div className="mt-6 pt-4 border-t border-[#E2E8F0] flex flex-col sm:flex-row sm:items-center justify-between gap-4">
            <div className="flex items-center gap-4 text-xs font-mono text-[#475569]">
              <span className="flex items-center gap-1.5">
                <CheckCircle2 className="w-3.5 h-3.5 text-emerald-500" />
                <span>{isDe ? "Mathematisch Verifiziert (Netto + MwSt = Brutto)" : "Mathematically Verified (Net + Tax = Gross)"}</span>
              </span>
              <span className="hidden md:flex items-center gap-1.5">
                <ShieldCheck className="w-3.5 h-3.5 text-black" />
                <span>Excel & CSV Export</span>
              </span>
            </div>

            <a
              href="/dashboard"
              className="px-4 py-2 bg-black text-white font-mono text-xs uppercase tracking-caps hover:bg-[#334155] transition-colors flex items-center justify-center gap-2 font-medium"
            >
              <span>{isDe ? "Live im Dashboard testen" : "Test Live in Dashboard"}</span>
              <ArrowRight className="w-3.5 h-3.5" />
            </a>
          </div>
        </div>
      </div>
    </section>
  );
}
