"use client";

import React, { useState } from "react";
import { LineItem } from "@/lib/schema/receipt";
import {
  COMMON_TAX_RATES,
  formatAmountInput,
  formatMoney,
  formatTaxRateInput,
  parseAmountInput,
  parseTaxRatePercent,
} from "./receiptFormat";
import { Plus, Trash2, AlertCircle, CheckCircle2, ShoppingBag } from "lucide-react";
import { useI18n } from "@/lib/i18n/context";

export interface LineItemsEditorProps {
  items: LineItem[];
  currency?: string;
  totalGross?: number;
  activeHighlightField?: string | null;
  onSelectField?: (fieldKey: string) => void;
  onChange: (updatedItems: LineItem[]) => void;
}

export function LineItemsEditor({
  items,
  currency = "EUR",
  totalGross,
  activeHighlightField,
  onSelectField,
  onChange,
}: LineItemsEditorProps) {
  const { language } = useI18n();
  const isDe = language === "de";
  const lineItems = items || [];

  const handleUpdateItem = (
    index: number,
    field: keyof LineItem,
    value: any
  ) => {
    const next = [...lineItems];
    const current = { ...next[index] };

    if (field === "description") {
      current.description = String(value);
    } else if (field === "quantity") {
      const parsedQty = parseFloat(String(value));
      current.quantity = isNaN(parsedQty) ? 1 : Math.max(0.01, parsedQty);
      if (typeof current.unitPrice === "number" && current.unitPrice > 0) {
        current.price = Math.round(current.quantity * current.unitPrice * 100) / 100;
      }
    } else if (field === "unitPrice") {
      const parsedUnit = parseAmountInput(String(value));
      current.unitPrice = parsedUnit;
      if (parsedUnit !== null) {
        current.price = Math.round((current.quantity || 1) * parsedUnit * 100) / 100;
      }
    } else if (field === "price") {
      const parsedPrice = parseAmountInput(String(value));
      current.price = parsedPrice !== null ? parsedPrice : 0;
    } else if (field === "taxRate") {
      current.taxRate = parseTaxRatePercent(String(value ?? ""));
    }

    next[index] = current;
    onChange(next);
  };

  const handleAddRow = () => {
    const newItem: LineItem = {
      description: isDe ? "Neue Position" : "New Item",
      quantity: 1,
      unitPrice: 0,
      price: 0,
      taxRate: null,
    };
    const next = [...lineItems, newItem];
    onChange(next);
    onSelectField?.(`lineItem:${next.length - 1}`);
  };

  const handleDeleteRow = (index: number) => {
    const next = lineItems.filter((_, idx) => idx !== index);
    onChange(next);
  };

  // Cross-sum comparison
  const sumPositions = Math.round(
    lineItems.reduce((acc, curr) => acc + (curr?.price ?? 0), 0) * 100
  ) / 100;

  const hasGross = typeof totalGross === "number" && !isNaN(totalGross);
  const diff = hasGross ? Math.round((sumPositions - totalGross) * 100) / 100 : 0;
  const hasDiscrepancy = hasGross && Math.abs(diff) > 0.02;

  return (
    <div className="space-y-3 font-sans" data-testid="line-items-editor">
      {/* Header with Title & Add Action */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <ShoppingBag className="w-4 h-4 text-black" />
          <h4 className="font-mono text-xs uppercase tracking-caps font-bold text-black">
            {isDe ? "Einzelpositionen" : "Line Items"} ({lineItems.length})
          </h4>
        </div>
        <button
          type="button"
          data-testid="add-line-item-btn"
          onClick={handleAddRow}
          className="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-mono uppercase tracking-caps bg-white border border-[#E2E8F0] hover:border-black text-black hover:bg-[#F8FAFC] transition-colors"
        >
          <Plus className="w-3.5 h-3.5" />
          <span>{isDe ? "Position hinzufügen" : "Add Item"}</span>
        </button>
      </div>

      {/* Cross-sum check notification */}
      {lineItems.length > 0 && hasGross && (
        <div
          data-testid="line-items-sum-status"
          className={`flex items-center justify-between px-3 py-2 border font-mono text-xs ${
            hasDiscrepancy
              ? "bg-[#FEF3C7] border-[#F59E0B] text-[#92400E]"
              : "bg-emerald-50 border-emerald-200 text-emerald-900"
          }`}
        >
          <div className="flex items-center gap-2">
            {hasDiscrepancy ? (
              <AlertCircle className="w-4 h-4 text-[#D97706] shrink-0" />
            ) : (
              <CheckCircle2 className="w-4 h-4 text-emerald-600 shrink-0" />
            )}
            <span>
              {hasDiscrepancy
                ? (isDe ? `Differenz zum Beleg-Brutto: ${diff > 0 ? "+" : ""}${formatMoney(diff, currency)}` : `Difference to receipt total: ${diff > 0 ? "+" : ""}${formatMoney(diff, currency)}`)
                : (isDe ? "Summe stimmt mit Beleg-Brutto überein" : "Sum matches receipt gross total")}
            </span>
          </div>
          <span className="font-bold text-[11px]">
            {isDe ? "Summe" : "Sum"}: {formatMoney(sumPositions, currency)} / {isDe ? "Brutto" : "Gross"}: {formatMoney(totalGross, currency)}
          </span>
        </div>
      )}

      {/* Editable Table */}
      <div className="border border-[#E2E8F0] overflow-x-auto bg-white">
        <table className="w-full text-left text-xs border-collapse">
          <thead className="bg-[#F8FAFC] text-black border-b border-[#E2E8F0] font-mono text-[10px] uppercase tracking-caps select-none">
            <tr>
              <th className="py-2.5 px-2 w-8 text-center border-r border-[#E2E8F0]">#</th>
              <th className="py-2.5 px-3 min-w-[160px] border-r border-[#E2E8F0]">{isDe ? "Beschreibung" : "Description"}</th>
              <th className="py-2.5 px-2 w-16 text-center border-r border-[#E2E8F0]">{isDe ? "Menge" : "Qty"}</th>
              <th className="py-2.5 px-2 w-24 text-right border-r border-[#E2E8F0]">{isDe ? "Einzelpreis" : "Unit Price"}</th>
              <th className="py-2.5 px-2 w-20 text-center border-r border-[#E2E8F0]">{isDe ? "MwSt %" : "Tax %"}</th>
              <th className="py-2.5 px-2 w-24 text-right border-r border-[#E2E8F0]">{isDe ? "Gesamt" : "Total"}</th>
              <th className="py-2.5 px-2 w-10 text-center">{isDe ? "Aktion" : "Action"}</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-[#E2E8F0]">
            {lineItems.length === 0 ? (
              <tr>
                <td colSpan={7} className="py-8 text-center text-[#94A3B8] font-mono">
                  <p className="text-xs mb-2">{isDe ? "Keine Einzelpositionen erfasst" : "No line items captured"}</p>
                  <button
                    type="button"
                    onClick={handleAddRow}
                    className="inline-flex items-center gap-1 px-3 py-1.5 text-xs border border-[#E2E8F0] hover:border-black text-black bg-white hover:bg-[#F8FAFC]"
                  >
                    <Plus className="w-3.5 h-3.5" />
                    <span>{isDe ? "Erste Position anlegen" : "Add First Item"}</span>
                  </button>
                </td>
              </tr>
            ) : (
              lineItems.map((item, idx) => {
                const isSelected =
                  activeHighlightField === `lineItem:${idx}` ||
                  activeHighlightField === `lineItems[${idx}]` ||
                  activeHighlightField === `lineItems:${idx}`;

                return (
                  <tr
                    key={idx}
                    data-testid={`line-item-row-${idx}`}
                    onClick={() => onSelectField?.(`lineItem:${idx}`)}
                    className={`transition-colors ${
                      isSelected
                        ? "bg-[#EEF4FC] ring-1 ring-inset ring-[#0066FF]"
                        : "hover:bg-[#F8FAFC]"
                    }`}
                  >
                    {/* Index */}
                    <td className="py-2 px-2 text-center font-mono text-[#64748B] border-r border-[#E2E8F0]">
                      {idx + 1}
                    </td>

                    {/* Description */}
                    <td className="py-1 px-2 border-r border-[#E2E8F0]">
                      <input
                        type="text"
                        data-testid={`line-item-desc-${idx}`}
                        value={item?.description ?? ""}
                        onFocus={() => onSelectField?.(`lineItem:${idx}`)}
                        onChange={(e) => handleUpdateItem(idx, "description", e.target.value)}
                        placeholder={isDe ? "Positionsbezeichnung" : "Item description"}
                        className="w-full bg-transparent border-0 border-b border-transparent focus:border-black px-1.5 py-1 text-xs text-black focus:outline-none font-sans"
                      />
                    </td>

                    {/* Quantity */}
                    <td className="py-1 px-2 border-r border-[#E2E8F0]">
                      <input
                        type="number"
                        step="any"
                        data-testid={`line-item-qty-${idx}`}
                        value={item?.quantity ?? 1}
                        onFocus={() => onSelectField?.(`lineItem:${idx}`)}
                        onChange={(e) => handleUpdateItem(idx, "quantity", e.target.value)}
                        className="w-full bg-transparent border-0 border-b border-transparent focus:border-black px-1 py-1 text-xs text-center font-mono text-black focus:outline-none"
                      />
                    </td>

                    {/* Unit Price */}
                    <td className="py-1 px-2 border-r border-[#E2E8F0]">
                      <input
                        type="text"
                        data-testid={`line-item-unit-price-${idx}`}
                        value={formatAmountInput(item?.unitPrice ?? null)}
                        placeholder="—"
                        onFocus={() => onSelectField?.(`lineItem:${idx}`)}
                        onChange={(e) => handleUpdateItem(idx, "unitPrice", e.target.value)}
                        className="w-full bg-transparent border-0 border-b border-transparent focus:border-black px-1 py-1 text-xs text-right font-mono text-black focus:outline-none"
                      />
                    </td>

                    {/* Tax Rate — any percent, not only 7/19 */}
                    <td className="py-1 px-2 border-r border-[#E2E8F0]">
                      <input
                        type="number"
                        inputMode="decimal"
                        step="0.1"
                        min="0"
                        max="100"
                        list="tax-rate-presets-line-items"
                        data-testid={`line-item-tax-${idx}`}
                        value={formatTaxRateInput(item?.taxRate)}
                        placeholder="—"
                        onFocus={() => onSelectField?.(`lineItem:${idx}`)}
                        onChange={(e) => handleUpdateItem(idx, "taxRate", e.target.value)}
                        className="w-full bg-transparent border-0 border-b border-transparent focus:border-black px-1 py-1 text-xs text-center font-mono text-black focus:outline-none"
                      />
                    </td>

                    {/* Total Price */}
                    <td className="py-1 px-2 border-r border-[#E2E8F0]">
                      <input
                        type="text"
                        data-testid={`line-item-price-${idx}`}
                        value={formatAmountInput(item?.price ?? 0)}
                        onFocus={() => onSelectField?.(`lineItem:${idx}`)}
                        onChange={(e) => handleUpdateItem(idx, "price", e.target.value)}
                        className="w-full bg-transparent border-0 border-b border-transparent focus:border-black px-1 py-1 text-xs text-right font-mono font-bold text-black focus:outline-none"
                      />
                    </td>

                    {/* Delete Action */}
                    <td className="py-1 px-1 text-center">
                      <button
                        type="button"
                        data-testid={`delete-line-item-${idx}`}
                        onClick={(e) => {
                          e.stopPropagation();
                          handleDeleteRow(idx);
                        }}
                        className="p-1 text-slate-400 hover:text-red-600 transition-colors"
                        title={isDe ? "Position löschen" : "Delete item"}
                      >
                        <Trash2 className="w-3.5 h-3.5" />
                      </button>
                    </td>
                  </tr>
                );
              })
            )}
          </tbody>
        </table>
        <datalist id="tax-rate-presets-line-items">
          {COMMON_TAX_RATES.map((rate) => (
            <option key={rate} value={rate} />
          ))}
        </datalist>
      </div>
    </div>
  );
}
