"use client";

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

export interface TaxBreakdownEditorProps {
  taxes: TaxBreakdownItem[];
  currency?: string;
  activeHighlightField?: string | null;
  onSelectField?: (fieldKey: string) => void;
  onChange: (next: TaxBreakdownItem[], opts?: { recomputeFromGross?: boolean }) => void;
}

function round2(value: number): number {
  return Math.round((value + Number.EPSILON) * 100) / 100;
}

export function TaxBreakdownEditor({
  taxes,
  currency = "EUR",
  activeHighlightField,
  onSelectField,
  onChange,
}: TaxBreakdownEditorProps) {
  const { language } = useI18n();
  const isDe = language === "de";
  const rows = taxes ?? [];
  const [addDraft, setAddDraft] = useState("");

  const usedRates = new Set(rows.map((row) => row.ratePercent));
  const quickRates = COMMON_TAX_RATES.filter((rate) => rate > 0 && !usedRates.has(rate));

  const commitRate = (index: number, raw: string) => {
    const parsed = parseTaxRatePercent(raw);
    const current = rows[index]?.ratePercent;
    if (parsed === null || parsed === current) return;

    const next = rows.map((row) => ({ ...row }));
    const duplicateAt = next.findIndex((row, i) => i !== index && row.ratePercent === parsed);
    if (duplicateAt >= 0) {
      next[duplicateAt] = {
        ...next[duplicateAt],
        taxAmount: round2((next[duplicateAt].taxAmount ?? 0) + (next[index].taxAmount ?? 0)),
        netAmount:
          next[duplicateAt].netAmount != null || next[index].netAmount != null
            ? round2((next[duplicateAt].netAmount ?? 0) + (next[index].netAmount ?? 0))
            : null,
      };
      next.splice(index, 1);
    } else {
      next[index] = { ...next[index], ratePercent: parsed };
    }
    onChange(next, { recomputeFromGross: true });
  };

  const commitAmount = (index: number, raw: string) => {
    const parsed = parseAmountInput(raw);
    const current = rows[index]?.taxAmount ?? null;
    if (parsed === null && (current === null || current === 0)) {
      const next = rows.filter((_, i) => i !== index);
      onChange(next, { recomputeFromGross: false });
      return;
    }
    if (parsed !== null && current !== null && parsed === current) return;
    const next = rows.map((row, i) =>
      i === index ? { ...row, taxAmount: parsed ?? 0 } : row
    );
    onChange(next, { recomputeFromGross: false });
  };

  const addRate = (rate: number) => {
    if (usedRates.has(rate)) return;
    const next = [...rows, { ratePercent: rate, taxAmount: 0, netAmount: null }].sort(
      (a, b) => (a.ratePercent ?? 0) - (b.ratePercent ?? 0)
    );
    setAddDraft("");
    onChange(next, { recomputeFromGross: rows.length > 0 });
  };

  const handleAdd = () => {
    const parsed = parseTaxRatePercent(addDraft);
    if (parsed === null) return;
    addRate(parsed);
  };

  const removeRow = (index: number) => {
    onChange(
      rows.filter((_, i) => i !== index),
      { recomputeFromGross: true }
    );
  };

  return (
    <div className="space-y-3" data-testid="tax-breakdown-editor">
      <div className="flex items-center justify-between">
        <span className="font-mono text-[10px] uppercase tracking-caps font-semibold text-[#475569]">
          {isDe ? "Steuersätze (MwSt %)" : "Tax rates (VAT %)"}
        </span>
        <span className="font-mono text-[10px] text-[#64748B]">
          {isDe ? "Satz und Betrag sind frei editierbar" : "Rate and amount are freely editable"}
        </span>
      </div>

      {rows.length === 0 && (
        <p className="text-xs text-[#64748B]">
          {isDe
            ? "Kein Steuersatz erfasst — wähle 7 %, 19 % oder einen anderen Satz."
            : "No tax rate yet — pick 7%, 19%, or any other rate."}
        </p>
      )}

      <div className="space-y-2">
        {rows.map((row, index) => {
          const fieldKey = `tax:${row.ratePercent}`;
          const selected =
            activeHighlightField === fieldKey ||
            activeHighlightField === `taxBreakdown:${index}`;
          return (
            <div
              key={`${row.ratePercent}-${index}`}
              className={`grid grid-cols-[7rem_1fr_auto] gap-2 items-end ${
                selected ? "ring-1 ring-inset ring-[#0066FF] p-1" : ""
              }`}
            >
              <label className="block">
                <span className="font-mono text-[10px] uppercase tracking-caps text-[#64748B] block mb-1">
                  {isDe ? "Satz %" : "Rate %"}
                </span>
                <input
                  type="number"
                  inputMode="decimal"
                  step="0.1"
                  min="0"
                  max="100"
                  list="tax-rate-presets-breakdown"
                  data-testid={`tax-rate-input-${index}`}
                  key={`rate-${index}-${row.ratePercent}`}
                  defaultValue={formatTaxRateInput(row.ratePercent)}
                  onFocus={() => onSelectField?.(fieldKey)}
                  onBlur={(e) => commitRate(index, e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      e.preventDefault();
                      commitRate(index, (e.target as HTMLInputElement).value);
                    }
                  }}
                  className="w-full bg-[#F8FAFC] border border-[#E2E8F0] px-2 py-2 text-sm font-mono text-black focus:border-black focus:bg-white focus:outline-none"
                />
              </label>
              <label className="block">
                <span className="font-mono text-[10px] uppercase tracking-caps text-[#64748B] block mb-1">
                  {isDe ? `Betrag (${currency})` : `Amount (${currency})`}
                </span>
                <input
                  type="text"
                  inputMode="decimal"
                  data-testid={`modal-tax-${row.ratePercent}`}
                  key={`amt-${index}-${row.taxAmount}`}
                  defaultValue={formatAmountInput(row.taxAmount ?? null)}
                  placeholder="—"
                  onFocus={() => onSelectField?.(fieldKey)}
                  onBlur={(e) => commitAmount(index, e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      e.preventDefault();
                      commitAmount(index, (e.target as HTMLInputElement).value);
                    }
                  }}
                  className="w-full bg-[#F8FAFC] border border-[#E2E8F0] px-2 py-2 text-sm font-mono text-black focus:border-black focus:bg-white focus:outline-none"
                />
              </label>
              <button
                type="button"
                data-testid={`tax-rate-remove-${index}`}
                onClick={() => removeRow(index)}
                className="p-2 text-[#94A3B8] hover:text-red-600 transition-colors"
                title={isDe ? "Steuersatz entfernen" : "Remove tax rate"}
              >
                <Trash2 className="w-4 h-4" />
              </button>
            </div>
          );
        })}
      </div>

      <div className="flex flex-wrap items-center gap-2 pt-1">
        {quickRates.slice(0, 6).map((rate) => (
          <button
            key={rate}
            type="button"
            data-testid={`tax-rate-quick-${rate}`}
            onClick={() => addRate(rate)}
            className="px-2 py-1 font-mono text-[10px] uppercase tracking-caps border border-[#E2E8F0] hover:border-black text-black bg-white"
          >
            {Number.isInteger(rate) ? rate : rate.toFixed(1)}%
          </button>
        ))}
        <div className="flex items-center gap-1">
          <input
            type="number"
            inputMode="decimal"
            step="0.1"
            min="0"
            max="100"
            list="tax-rate-presets-breakdown"
            data-testid="tax-rate-add-input"
            value={addDraft}
            placeholder={isDe ? "z. B. 20" : "e.g. 20"}
            onChange={(e) => setAddDraft(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter") {
                e.preventDefault();
                handleAdd();
              }
            }}
            className="w-20 bg-[#F8FAFC] border border-[#E2E8F0] px-2 py-1 text-xs font-mono text-black focus:border-black focus:outline-none"
          />
          <button
            type="button"
            data-testid="tax-rate-add-btn"
            onClick={handleAdd}
            className="inline-flex items-center gap-1 px-2 py-1 text-[10px] font-mono uppercase tracking-caps border border-[#E2E8F0] hover:border-black bg-white"
          >
            <Plus className="w-3 h-3" />
            {isDe ? "Satz" : "Rate"}
          </button>
        </div>
      </div>

      <datalist id="tax-rate-presets-breakdown">
        {COMMON_TAX_RATES.map((rate) => (
          <option key={rate} value={rate} />
        ))}
      </datalist>
    </div>
  );
}
