import { useEffect, useMemo, useState } from "react";
import SectionCard from "../components/SectionCard";
import { api } from "../lib/api";

function emptyForm() {
  return {
    code: "",
    label: "",
    tax_rate_percent: "19",
    is_active: true,
    sort_order: "1000",
  };
}

function asNumber(value) {
  const parsed = Number(value || 0);
  return Number.isFinite(parsed) ? parsed : 0;
}

function percent(value) {
  return `${new Intl.NumberFormat("de-DE", { maximumFractionDigits: 3 }).format(asNumber(value))} %`;
}

function normalizeCode(value) {
  return String(value || "")
    .trim()
    .replace(/\s+/g, "_")
    .replace(/[^a-zA-Z0-9_()%./%-]/g, "_");
}

export default function FinanceTaxCodesPage() {
  const [rows, setRows] = useState([]);
  const [form, setForm] = useState(() => emptyForm());
  const [editingId, setEditingId] = useState("");
  const [showInactive, setShowInactive] = useState(true);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  async function loadData() {
    setLoading(true);
    setError("");
    try {
      const data = await api.get(`/finance/tax-codes${showInactive ? "" : "?active=true"}`);
      setRows(data || []);
    } catch (err) {
      setError(err.message || "MwSt.-Sätze konnten nicht geladen werden.");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    loadData();
  }, [showInactive]);

  const activeCount = useMemo(() => rows.filter((row) => row.is_active).length, [rows]);

  function updateField(field, value) {
    setForm((prev) => ({ ...prev, [field]: value }));
  }

  function resetForm() {
    setEditingId("");
    setForm(emptyForm());
  }

  function editRow(row) {
    setEditingId(String(row.id));
    setForm({
      code: row.code || "",
      label: row.label || "",
      tax_rate_percent: String(row.tax_rate_percent ?? "0"),
      is_active: Boolean(row.is_active),
      sort_order: String(row.sort_order ?? "1000"),
    });
    setMessage("");
    setError("");
  }

  async function saveRow(event) {
    event.preventDefault();
    setMessage("");
    setError("");
    const payload = {
      ...form,
      code: normalizeCode(form.code),
      label: form.label.trim(),
      tax_rate_percent: Number(form.tax_rate_percent || 0),
      sort_order: Number(form.sort_order || 1000),
      is_active: Boolean(form.is_active),
    };

    if (!payload.code || !payload.label) {
      setError("Code und Bezeichnung sind Pflichtfelder.");
      return;
    }

    try {
      if (editingId) {
        await api.put(`/finance/tax-codes/${editingId}`, payload);
        setMessage("MwSt.-/Kostenart gespeichert.");
      } else {
        await api.post("/finance/tax-codes", payload);
        setMessage("MwSt.-/Kostenart angelegt.");
      }
      resetForm();
      await loadData();
    } catch (err) {
      setError(err.message || "MwSt.-/Kostenart konnte nicht gespeichert werden.");
    }
  }

  async function disableRow(row) {
    if (!window.confirm(`MwSt.-/Kostenart „${row.label}“ deaktivieren?`)) return;
    setMessage("");
    setError("");
    try {
      await api.delete(`/finance/tax-codes/${row.id}`);
      setMessage("MwSt.-/Kostenart deaktiviert.");
      await loadData();
    } catch (err) {
      setError(err.message || "MwSt.-/Kostenart konnte nicht deaktiviert werden.");
    }
  }

  return (
    <>
      <style>{`
        .tax-code-grid { display: grid; gap: 18px; }
        .tax-code-form { display: grid; gap: 12px; }
        .tax-code-inline { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
        .tax-code-badge { display: inline-block; padding: 4px 9px; border-radius: 999px; font-weight: 700; font-size: .84rem; }
        .tax-code-badge.active { background: rgba(22, 163, 74, .12); color: #15803d; }
        .tax-code-badge.inactive { background: rgba(100, 116, 139, .14); color: #475569; }
        @media (max-width: 900px) { .tax-code-inline { grid-template-columns: 1fr; } }
      `}</style>

      <div className="tax-code-grid">
        {error ? <div className="alert error">{error}</div> : null}
        {message ? <div className="alert success">{message}</div> : null}

        <SectionCard
          title="MwSt.-Sätze Finanzen"
          subtitle="Hier werden die Kostenarten und MwSt.-Sätze gepflegt, die bei Rechnungspositionen im Finanzmodul als Dropdown angeboten werden."
          actions={
            <div className="row-actions">
              <label className="checkbox-row">
                <input type="checkbox" checked={showInactive} onChange={(event) => setShowInactive(event.target.checked)} />
                <span>Inaktive anzeigen</span>
              </label>
              <button className="btn secondary" type="button" onClick={loadData} disabled={loading}>{loading ? "Lade…" : "Aktualisieren"}</button>
            </div>
          }
        >
          <p className="muted">Aktive Einträge: {activeCount}. Der Satz wird in Prozent gepflegt, also z. B. <strong>19</strong> für 19&nbsp;% oder <strong>7</strong> für 7&nbsp;%.</p>
        </SectionCard>

        <SectionCard title={editingId ? "MwSt.-/Kostenart bearbeiten" : "MwSt.-/Kostenart anlegen"}>
          <form className="tax-code-form" onSubmit={saveRow}>
            <div className="tax-code-inline">
              <label>
                <span>Code</span>
                <input className="input" required value={form.code} onChange={(event) => updateField("code", event.target.value)} onBlur={(event) => updateField("code", normalizeCode(event.target.value))} placeholder="z. B. Buerobedarf_19%" />
              </label>
              <label>
                <span>Bezeichnung</span>
                <input className="input" required value={form.label} onChange={(event) => updateField("label", event.target.value)} placeholder="z. B. Bürobedarf 19%" />
              </label>
            </div>

            <div className="tax-code-inline">
              <label>
                <span>MwSt.-Satz in %</span>
                <input className="input" type="number" min="0" max="100" step="0.001" required value={form.tax_rate_percent} onChange={(event) => updateField("tax_rate_percent", event.target.value)} />
              </label>
              <label>
                <span>Sortierung</span>
                <input className="input" type="number" min="0" step="1" value={form.sort_order} onChange={(event) => updateField("sort_order", event.target.value)} />
              </label>
            </div>

            <label className="checkbox-row">
              <input type="checkbox" checked={form.is_active} onChange={(event) => updateField("is_active", event.target.checked)} />
              <span>Aktiv und in Rechnungen auswählbar</span>
            </label>

            <div className="row-actions">
              <button className="btn" type="submit">{editingId ? "Speichern" : "Anlegen"}</button>
              {editingId ? <button className="btn secondary" type="button" onClick={resetForm}>Abbrechen</button> : null}
            </div>
          </form>
        </SectionCard>

        <SectionCard title="Vorhandene MwSt.-/Kostenarten">
          <div className="table-wrap">
            <table className="table">
              <thead>
                <tr><th>Sort.</th><th>Code</th><th>Bezeichnung</th><th>MwSt.</th><th>Status</th><th>Aktionen</th></tr>
              </thead>
              <tbody>
                {rows.map((row) => (
                  <tr key={row.id}>
                    <td>{row.sort_order}</td>
                    <td><code>{row.code}</code></td>
                    <td><strong>{row.label}</strong></td>
                    <td>{percent(row.tax_rate_percent)}</td>
                    <td><span className={`tax-code-badge ${row.is_active ? "active" : "inactive"}`}>{row.is_active ? "Aktiv" : "Inaktiv"}</span></td>
                    <td>
                      <div className="row-actions">
                        <button className="mini-btn" type="button" onClick={() => editRow(row)}>Bearbeiten</button>
                        {row.is_active ? <button className="mini-btn danger" type="button" onClick={() => disableRow(row)}>Deaktivieren</button> : null}
                      </div>
                    </td>
                  </tr>
                ))}
                {!rows.length ? <tr><td colSpan="6">Keine MwSt.-/Kostenarten vorhanden.</td></tr> : null}
              </tbody>
            </table>
          </div>
        </SectionCard>
      </div>
    </>
  );
}
