// =============================================================
// Invoices.jsx — Rēķinu Modulis
// =============================================================
// Klients redz: "MANI RĒĶINI" — tikai savus, ar kopējo summu
// Admins redz:  "FINANSES" — visus rēķinus + statistiku
// =============================================================

import { useState, useEffect } from "react";
import { api } from "../../apiConfig";

// ── STATUS KONFIGURĀCIJA ──────────────────────────────────────
const STATUS_CFG = {
  GAIDA:     { label: "GAIDA",     bg: "#3b3b00", color: "#facc15", border: "#facc15" },
  APMAKSATS: { label: "APMAKSĀTS", bg: "#003b00", color: "#00ff41", border: "#00ff41" },
  NOKAVETS:  { label: "NOKAVĒTS",  bg: "#3b0000", color: "#ff4444", border: "#ff4444" },
  ATCELTS:   { label: "ATCELTS",   bg: "#1a1a1a", color: "#666",    border: "#666"    },
};
const DEFAULT_STATUS = { label: "?", bg: "#222", color: "#666", border: "#666" };

// ── PALĪGFUNKCIJAS ────────────────────────────────────────────
const fmt = (amount) =>
  `€ ${parseFloat(amount || 0).toLocaleString("lv-LV", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })}`;

// ── GALVENĀ KOMPONENTE ────────────────────────────────────────
export default function Invoices({ isAdmin }) {
  const [invoices, setInvoices] = useState([]);
  const [loading, setLoading]   = useState(true);
  const [error, setError]       = useState(null);
  const [filter, setFilter]     = useState("ALL"); // ALL | GAIDA | APMAKSATS | NOKAVETS

  useEffect(() => {
    fetchInvoices();
  }, []);

  const fetchInvoices = async () => {
    setLoading(true);
    setError(null);
    try {
      const res  = await api.get("/api/invoices/");
      const data = Array.isArray(res.data) ? res.data : res.data.results ?? [];
      setInvoices(data);
    } catch (err) {
      if (err.response?.status === 401) {
        setError("SESSION_EXPIRED — lūdzu ielogojieties no jauna.");
      } else {
        setError("CONNECTION_ERROR — neizdevās ielādēt rēķinus.");
      }
    } finally {
      setLoading(false);
    }
  };

  // ── FILTRĒŠANA ────────────────────────────────────────────
  const filtered = filter === "ALL"
    ? invoices
    : invoices.filter((inv) => inv.status === filter);

  // ── STATISTIKA ────────────────────────────────────────────
  const totalAll     = invoices.reduce((s, i) => s + parseFloat(i.amount || 0), 0);
  const totalGaida   = invoices.filter((i) => i.status === "GAIDA")
                               .reduce((s, i) => s + parseFloat(i.amount || 0), 0);
  const totalPaid    = invoices.filter((i) => i.status === "APMAKSATS")
                               .reduce((s, i) => s + parseFloat(i.amount || 0), 0);
  const countNokavets = invoices.filter((i) => i.status === "NOKAVETS").length;

  // ── STILI ─────────────────────────────────────────────────
  const s = {
    wrap:    { padding: "20px", color: "#00ff41", fontFamily: "'Courier New', monospace" },
    statRow: { display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: "15px", marginBottom: "25px" },
    statCard: (accent = "#00ff41") => ({
      border: `1px solid ${accent}33`,
      background: "rgba(0,20,0,0.7)",
      padding: "18px 20px",
      position: "relative",
    }),
    statLabel: { fontSize: "9px", color: "#1a7a35", letterSpacing: "2px", textTransform: "uppercase", marginBottom: "8px" },
    statVal:   (color = "#00ff41") => ({ fontSize: "22px", fontWeight: "bold", color }),
    filterRow: { display: "flex", gap: "8px", marginBottom: "20px", flexWrap: "wrap" },
    filterBtn: (active) => ({
      padding: "7px 18px", fontSize: "10px", fontWeight: "bold",
      letterSpacing: "1px", cursor: "pointer", fontFamily: "'Courier New', monospace",
      background: active ? "#00ff41" : "transparent",
      color:      active ? "black"   : "#1a7a35",
      border:     active ? "1px solid #00ff41" : "1px solid #1a7a35",
      transition: "all 0.2s",
    }),
    table:  { width: "100%", borderCollapse: "collapse", fontSize: "12px" },
    th:     { textAlign: "left", padding: "10px", borderBottom: "1px solid #1a7a35", color: "#1a7a35", letterSpacing: "1px", fontSize: "10px" },
    td:     { padding: "14px 10px", borderBottom: "1px solid rgba(0,255,65,0.08)", verticalAlign: "middle" },
    emptyBox: { textAlign: "center", padding: "50px", border: "1px dashed #1a7a35", color: "#1a7a35" },
    errorBox: { padding: "20px", border: "1px solid #ff4444", color: "#ff4444", background: "#1a0000", textAlign: "center" },
    retryBtn: { marginTop: "10px", background: "transparent", border: "1px solid #ff4444", color: "#ff4444", padding: "8px 20px", cursor: "pointer", fontFamily: "'Courier New', monospace" },
    amountPaid:    { color: "#00ff41", fontWeight: "bold" },
    amountPending: { color: "#facc15", fontWeight: "bold" },
    amountOverdue: { color: "#ff4444", fontWeight: "bold" },
  };

  // ── STATUS BADGE ──────────────────────────────────────────
  const Badge = ({ status }) => {
    const cfg = STATUS_CFG[status] ?? DEFAULT_STATUS;
    return (
      <span style={{
        padding: "3px 8px", fontSize: "9px", fontWeight: "bold",
        letterSpacing: "1px", whiteSpace: "nowrap",
        background: cfg.bg, color: cfg.color, border: `1px solid ${cfg.border}`,
      }}>
        {cfg.label}
      </span>
    );
  };

  // ── SUMMAS KRĀSA PĒC STATUSA ──────────────────────────────
  const amountStyle = (status) => {
    if (status === "APMAKSATS") return s.amountPaid;
    if (status === "NOKAVETS")  return s.amountOverdue;
    return s.amountPending;
  };

  // ── RENDER ────────────────────────────────────────────────
  return (
    <div style={s.wrap}>

      {/* STATISTIKAS KARTĪTES */}
      {!loading && !error && (
        <div style={s.statRow}>

          <div style={s.statCard("#00ff41")}>
            <div style={s.statLabel}>{isAdmin ? "Kopā rēķini" : "Kopā summa"}</div>
            <div style={s.statVal("#00ff41")}>{isAdmin ? invoices.length : fmt(totalAll)}</div>
          </div>

          <div style={s.statCard("#facc15")}>
            <div style={s.statLabel}>Gaida apmaksu</div>
            <div style={s.statVal("#facc15")}>{fmt(totalGaida)}</div>
          </div>

          <div style={s.statCard("#00ff41")}>
            <div style={s.statLabel}>Apmaksāts</div>
            <div style={s.statVal("#00ff41")}>{fmt(totalPaid)}</div>
          </div>

          {countNokavets > 0 && (
            <div style={s.statCard("#ff4444")}>
              <div style={s.statLabel}>⚠ Nokavēti</div>
              <div style={s.statVal("#ff4444")}>{countNokavets}</div>
            </div>
          )}

        </div>
      )}

      {/* FILTRĒŠANAS POGAS */}
      {!loading && !error && invoices.length > 0 && (
        <div style={s.filterRow}>
          {["ALL", "GAIDA", "APMAKSATS", "NOKAVETS", "ATCELTS"].map((f) => (
            <button
              key={f}
              style={s.filterBtn(filter === f)}
              onClick={() => setFilter(f)}
            >
              {f === "ALL" ? "VISI" : (STATUS_CFG[f]?.label ?? f)}
              {f !== "ALL" && (
                <span style={{ marginLeft: "5px", opacity: 0.6 }}>
                  ({invoices.filter((i) => i.status === f).length})
                </span>
              )}
            </button>
          ))}
        </div>
      )}

      {/* IELĀDES STĀVOKLIS */}
      {loading && (
        <div style={{ textAlign: "center", padding: "40px", color: "#1a7a35" }}>
          ⟳ LOADING_INVOICES...
        </div>
      )}

      {/* KĻŪDAS STĀVOKLIS */}
      {!loading && error && (
        <div style={s.errorBox}>
          <div>⚠ {error}</div>
          <button style={s.retryBtn} onClick={fetchInvoices}>RETRY_CONNECTION</button>
        </div>
      )}

      {/* TUKŠS */}
      {!loading && !error && filtered.length === 0 && (
        <div style={s.emptyBox}>
          {filter !== "ALL"
            ? `NO_INVOICES WITH STATUS "${filter}"`
            : "NO_INVOICES_FOUND"}
        </div>
      )}

      {/* RĒĶINU TABULA */}
      {!loading && !error && filtered.length > 0 && (
        <table style={s.table}>
          <thead>
            <tr>
              <th style={s.th}>RĒĶINS_#</th>
              {isAdmin && <th style={s.th}>KLIENTS</th>}
              <th style={s.th}>PROJEKTS</th>
              <th style={s.th}>SUMMA</th>
              <th style={s.th}>STATUSS</th>
              <th style={s.th}>IZRAKSTĪTS</th>
              <th style={s.th}>TERMIŅŠ</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map((inv) => (
              <tr
                key={inv.id}
                onMouseEnter={(e) => (e.currentTarget.style.background = "rgba(0,255,65,0.03)")}
                onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}
              >
                <td style={{ ...s.td, color: "#1a7a35", fontWeight: "bold", fontSize: "11px" }}>
                  {inv.invoice_number}
                </td>

                {isAdmin && (
                  <td style={{ ...s.td, color: "#aaa" }}>
                    {inv.client_name}
                  </td>
                )}

                <td style={{ ...s.td, color: "#888", fontSize: "11px" }}>
                  {inv.project_name}
                </td>

                <td style={{ ...s.td, ...amountStyle(inv.status) }}>
                  {fmt(inv.amount)}
                </td>

                <td style={s.td}>
                  <Badge status={inv.status} />
                </td>

                <td style={{ ...s.td, color: "#666", fontSize: "11px" }}>
                  {inv.issued_date ?? "—"}
                </td>

                <td style={{
                  ...s.td, fontSize: "11px",
                  color: inv.status === "NOKAVETS" ? "#ff4444" : "#666",
                  fontWeight: inv.status === "NOKAVETS" ? "bold" : "normal",
                }}>
                  {inv.due_date ?? "—"}
                  {inv.status === "NOKAVETS" && " ⚠"}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}

    </div>
  );
}
