"use client";

import { useEffect, useMemo, useState, useTransition } from "react";
import { useRouter } from "next/navigation";

import { AdminCompanySearch } from "@/components/admin/AdminCompanySearch";
import { AdminDateTimeField } from "@/components/admin/forms/AdminDateTimeField";
import { Spinner } from "@/components/common/Spinner";
import { splitGrossAmount } from "@/lib/billing-amounts";
import {
  getInvoiceStatusLabel,
  getInvoiceTypeLabel,
  getPaymentMethodLabel,
  getPaymentStatusLabel,
  getTierAdminLabel,
} from "@/lib/module-formatters";

type BillingSummary = {
  openInvoices: number;
  overdueInvoices: number;
  paidInvoices: number;
  collectedAmount: number;
  expiringPlans: number;
};

type BillingInvoice = {
  id: string;
  number: string;
  companyId: string | null;
  planId: string | null;
  placementId: string | null;
  adCampaignId: string | null;
  status:
    | "DRAFT"
    | "ISSUED"
    | "PARTIALLY_PAID"
    | "PAID"
    | "OVERDUE"
    | "CANCELED";
  type:
    | "PLAN"
    | "INSTITUTIONAL_PLAN"
    | "PLACEMENT"
    | "AD_CAMPAIGN"
    | "JOB_PACKAGE"
    | "STORE_PACKAGE"
    | "CUSTOM";
  currency: string;
  subtotalAmount: number;
  taxAmount: number;
  totalAmount: number;
  dueAt: Date | string | null;
  note: string | null;
  buyerType: "LEGAL_ENTITY" | "ENTREPRENEUR" | "INDIVIDUAL";
  buyerName: string | null;
  buyerCompanyName: string | null;
  buyerPib: string | null;
  buyerRegistrationNumber: string | null;
  buyerAddress: string | null;
  buyerCity: string | null;
  buyerEmail: string | null;
  buyerPhone: string | null;
  buyerContactName: string | null;
  buyerOrderReference: string | null;
  finalDocumentType: "E_INVOICE" | "FISCAL_RECEIPT" | "MANUAL_INVOICE" | null;
  finalDocumentStatus: "PENDING" | "ISSUED" | "NOT_REQUIRED";
  finalDocumentNumber: string | null;
  finalDocumentIssuedAt: Date | string | null;
  company?: { name: string } | null;
  plan?: { nameSr: string; tier: string } | null;
  institutionalPlan?: { nameSr: string; tier: string } | null;
  placement?: { label: string | null; position: string } | null;
  adCampaign?: { name: string; slot: string | null } | null;
  payments: Array<{ id: string; amount: number; status: string }>;
};

type BillingPayment = {
  id: string;
  status: string;
  method: string;
  amount: number;
  currency: string;
  paidAt: Date | string | null;
  invoice: {
    number: string;
    company?: { name: string } | null;
  };
};

type BillingAlert = {
  id: string;
  title: string;
  message: string;
  level: string;
  dueAt: Date | string | null;
  company?: { name: string } | null;
  invoice?: { number: string; status: string } | null;
};

type ReferenceOptions = {
  companies: Array<{
    id: string;
    name: string;
    slug: string;
    type: string;
    email: string | null;
    phone: string | null;
    address: string | null;
    city: { nameSr: string } | null;
  }>;
  plans: Array<{
    id: string;
    nameSr: string;
    slug: string;
    tier: string;
    priceRsd: number | null;
    priceEur: number | null;
    durationDays: number | null;
    isActive: boolean;
  }>;
  placements: Array<{
    id: string;
    position: string;
    label: string | null;
    company: { name: string };
  }>;
  campaigns: Array<{ id: string; name: string; slug: string; status: string }>;
  invoices: Array<{
    id: string;
    number: string;
    totalAmount: number;
    status: string;
    company?: { name: string } | null;
  }>;
};

type BillingCommandCenterProps = {
  summary: BillingSummary;
  invoices: BillingInvoice[];
  payments: BillingPayment[];
  alerts: BillingAlert[];
  references: ReferenceOptions;
};

function formatCurrency(amount: number, currency = "RSD") {
  return new Intl.NumberFormat("sr-Latn-RS", {
    style: "currency",
    currency,
    maximumFractionDigits: 0,
  }).format(amount);
}

function formatDate(value?: Date | string | null) {
  if (!value) {
    return "Nije zadato";
  }

  return new Intl.DateTimeFormat("sr-Latn-RS", {
    day: "2-digit",
    month: "long",
    year: "numeric",
  }).format(new Date(value));
}

function buyerTypeLabel(value: BillingInvoice["buyerType"] | string) {
  const labels: Record<string, string> = {
    LEGAL_ENTITY: "Pravno lice",
    ENTREPRENEUR: "Preduzetnik",
    INDIVIDUAL: "Fizičko lice",
  };

  return labels[value] || value;
}

function finalDocumentLabel(
  value?: BillingInvoice["finalDocumentType"] | null
) {
  const labels: Record<string, string> = {
    E_INVOICE: "eFaktura",
    FISCAL_RECEIPT: "Fiskalni račun",
    MANUAL_INVOICE: "Ručni račun",
  };

  return value ? labels[value] || value : "Nije određeno";
}

export function BillingCommandCenter({
  summary,
  invoices: initialInvoices,
  payments,
  alerts,
  references,
}: BillingCommandCenterProps) {
  const router = useRouter();
  const [invoices, setInvoices] = useState(initialInvoices);
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [bulkStatus, setBulkStatus] = useState("");

  useEffect(() => {
    setInvoices(initialInvoices);
  }, [initialInvoices]);
  const [message, setMessage] = useState<string | null>(null);
  const [, startTransition] = useTransition();
  // Koji konkretan zadatak je u toku (npr. "payment", "invoice", "final:<id>")
  // — služi da prikažemo spinner na TAČNO tom dugmetu i sprečimo dupli klik.
  const [busy, setBusy] = useState<string | null>(null);

  function run(action: string, fn: () => Promise<void>) {
    if (busy) return; // već je nešto u toku — ignoriši dodatne klikove
    setBusy(action);
    startTransition(async () => {
      try {
        await fn();
      } finally {
        setBusy(null);
      }
    });
  }
  const [invoiceForm, setInvoiceForm] = useState({
    companyId: "",
    planId: "",
    placementId: "",
    adCampaignId: "",
    type: "PLAN",
    billingPeriod: "MONTHLY",
    currency: "RSD",
    subtotalAmount: "",
    taxAmount: "",
    totalAmount: "",
    dueAt: "",
    note: "",
    buyerType: "LEGAL_ENTITY",
    buyerName: "",
    buyerCompanyName: "",
    buyerPib: "",
    buyerRegistrationNumber: "",
    buyerAddress: "",
    buyerCity: "",
    buyerEmail: "",
    buyerPhone: "",
    buyerContactName: "",
    buyerOrderReference: "",
  });
  const [paymentForm, setPaymentForm] = useState({
    invoiceId: references.invoices[0]?.id ?? "",
    amount: references.invoices[0]?.totalAmount
      ? String(references.invoices[0].totalAmount)
      : "",
    currency: "RSD",
    method: "BANK_TRANSFER",
    status: "COMPLETED",
    paidAt: "",
    transactionRef: "",
    note: "",
  });

  const totalOpenBalance = useMemo(
    () =>
      invoices
        .filter((invoice) =>
          ["ISSUED", "PARTIALLY_PAID", "OVERDUE"].includes(invoice.status)
        )
        .reduce((sum, invoice) => sum + invoice.totalAmount, 0),
    [invoices]
  );

  function toggleSelection(id: string) {
    setSelectedIds((current) =>
      current.includes(id)
        ? current.filter((item) => item !== id)
        : [...current, id]
    );
  }

  function handleCreateInvoice() {
    run("invoice", async () => {
      try {
        const response = await fetch("/api/admin/invoices", {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({
            ...invoiceForm,
            billingPeriod:
              invoiceForm.type === "PLAN" ? invoiceForm.billingPeriod : undefined,
            companyId: invoiceForm.companyId || undefined,
            planId: invoiceForm.planId || undefined,
            placementId: invoiceForm.placementId || undefined,
            adCampaignId: invoiceForm.adCampaignId || undefined,
            subtotalAmount: Number(invoiceForm.subtotalAmount),
            taxAmount: Number(invoiceForm.taxAmount),
            totalAmount: Number(invoiceForm.totalAmount),
            dueAt: invoiceForm.dueAt || undefined,
            finalDocumentType:
              invoiceForm.buyerType === "INDIVIDUAL"
                ? "FISCAL_RECEIPT"
                : "E_INVOICE",
          }),
        });

        const result = (await response.json()) as {
          item?: BillingInvoice;
          message?: string;
        };

        if (!response.ok || !result.item) {
          throw new Error(result.message || "Čuvanje računa nije uspelo.");
        }

        setInvoices((current) => [result.item!, ...current]);
        setMessage(`Račun ${result.item.number} je sačuvan.`);
        router.refresh();
      } catch (error) {
        setMessage(
          error instanceof Error ? error.message : "Čuvanje računa nije uspelo."
        );
      }
    });
  }

  // Predlog iznosa iz cenovnika. Godišnje = 12 × mesečna (admin sme da izmeni).
  function planSuggestedAmount(priceRsd: number, period: string): number {
    return period === "ANNUAL" ? priceRsd * 12 : priceRsd;
  }

  function handlePlanChange(planId: string) {
    const plan = references.plans.find((item) => item.id === planId);
    const monthly = plan?.priceRsd && plan.priceRsd > 0 ? plan.priceRsd : 0;

    setInvoiceForm((current) => {
      const totalAmount = monthly > 0 ? planSuggestedAmount(monthly, current.billingPeriod) : 0;
      const amounts = splitGrossAmount(totalAmount, 20);
      return {
        ...current,
        type: "PLAN",
        planId,
        placementId: "",
        adCampaignId: "",
        currency: "RSD",
        totalAmount: totalAmount > 0 ? String(totalAmount) : "",
        subtotalAmount: totalAmount > 0 ? String(amounts.subtotalAmount) : "",
        taxAmount: totalAmount > 0 ? String(amounts.taxAmount) : "",
      };
    });
  }

  // Kad se promeni period, predlaži novi iznos iz cenovnika (× 12 za godišnje).
  function handleBillingPeriodChange(period: string) {
    const plan = references.plans.find((item) => item.id === invoiceForm.planId);
    const monthly = plan?.priceRsd && plan.priceRsd > 0 ? plan.priceRsd : 0;
    const totalAmount = monthly > 0 ? planSuggestedAmount(monthly, period) : 0;
    const amounts = splitGrossAmount(totalAmount, 20);

    setInvoiceForm((current) => ({
      ...current,
      billingPeriod: period,
      totalAmount: totalAmount > 0 ? String(totalAmount) : current.totalAmount,
      subtotalAmount: totalAmount > 0 ? String(amounts.subtotalAmount) : current.subtotalAmount,
      taxAmount: totalAmount > 0 ? String(amounts.taxAmount) : current.taxAmount,
    }));
  }

  function handleSendProforma(invoiceId: string) {
    run(`send:${invoiceId}`, async () => {
      try {
        const response = await fetch(
          `/api/admin/invoices/${invoiceId}/send-proforma`,
          {
            method: "POST",
          }
        );
        const result = (await response.json()) as {
          message?: string;
          recipient?: string;
        };

        if (!response.ok) {
          throw new Error(result.message || "Slanje predračuna nije uspelo.");
        }

        setMessage(`Predračun je poslat na ${result.recipient}.`);
      } catch (error) {
        setMessage(
          error instanceof Error
            ? error.message
            : "Slanje predračuna nije uspelo."
        );
      }
    });
  }

  function handleDeleteInvoice(invoice: BillingInvoice) {
    const confirmed = window.confirm(
      `Da li sigurno želite trajno da obrišete predračun ${invoice.number}?\n\nOva radnja se ne može poništiti.`
    );
    if (!confirmed) {
      return;
    }

    run(`delete:${invoice.id}`, async () => {
      try {
        const response = await fetch(`/api/admin/invoices/${invoice.id}`, {
          method: "DELETE",
        });
        const result = (await response.json()) as {
          ok?: boolean;
          message?: string;
        };

        if (!response.ok || !result.ok) {
          throw new Error(result.message || "Brisanje predračuna nije uspelo.");
        }

        setInvoices((current) =>
          current.filter((item) => item.id !== invoice.id)
        );
        setMessage(`Predračun ${invoice.number} je obrisan.`);
        router.refresh();
      } catch (error) {
        setMessage(
          error instanceof Error
            ? error.message
            : "Brisanje predračuna nije uspelo."
        );
      }
    });
  }

  function handleMarkFinalDocument(invoice: BillingInvoice) {
    run(`final:${invoice.id}`, async () => {
      try {
        const finalDocumentType =
          invoice.finalDocumentType ||
          (invoice.buyerType === "INDIVIDUAL" ? "FISCAL_RECEIPT" : "E_INVOICE");
        const response = await fetch(
          `/api/admin/invoices/${invoice.id}/final-document`,
          {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify({
              finalDocumentType,
              finalDocumentStatus: "ISSUED",
              finalDocumentNumber: invoice.finalDocumentNumber || undefined,
            }),
          }
        );
        const result = (await response.json()) as {
          item?: BillingInvoice;
          message?: string;
        };

        if (!response.ok || !result.item) {
          throw new Error(
            result.message || "Evidentiranje finalnog dokumenta nije uspelo."
          );
        }

        setInvoices((current) =>
          current.map((item) =>
            item.id === invoice.id ? { ...item, ...result.item } : item
          )
        );
        setMessage(
          `${finalDocumentLabel(finalDocumentType)} je označen kao izdat.`
        );
        router.refresh();
      } catch (error) {
        setMessage(
          error instanceof Error
            ? error.message
            : "Evidentiranje finalnog dokumenta nije uspelo."
        );
      }
    });
  }

  function handleRecordPayment() {
    run("payment", async () => {
      try {
        const response = await fetch("/api/admin/payments", {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({
            ...paymentForm,
            amount: Number(paymentForm.amount),
            paidAt: paymentForm.paidAt || undefined,
          }),
        });

        const result = (await response.json()) as { message?: string };

        if (!response.ok) {
          throw new Error(
            result.message || "Evidentiranje uplate nije uspelo."
          );
        }

        setMessage("Uplata je evidentirana i stanje računa je osveženo.");
        router.refresh();
      } catch (error) {
        setMessage(
          error instanceof Error
            ? error.message
            : "Evidentiranje uplate nije uspelo."
        );
      }
    });
  }

  function handleBulkUpdate() {
    run("bulk", async () => {
      try {
        const response = await fetch("/api/admin/invoices/bulk", {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({
            ids: selectedIds,
            changes: {
              status: bulkStatus,
            },
          }),
        });

        const result = (await response.json()) as {
          items?: BillingInvoice[];
          message?: string;
        };

        if (!response.ok || !result.items) {
          throw new Error(
            result.message || "Masovna izmena računa nije uspela."
          );
        }

        setInvoices(result.items);
        setSelectedIds([]);
        setBulkStatus("");
        setMessage("Masovna izmena računa je sačuvana.");
        router.refresh();
      } catch (error) {
        setMessage(
          error instanceof Error ? error.message : "Masovna izmena nije uspela."
        );
      }
    });
  }

  return (
    <div className="space-y-6">
      <section className="admin-command-shell">
        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-5">
          <div className="admin-chip">
            Otvoreni računi: {summary.openInvoices}
          </div>
          <div className="admin-chip">
            Prekoračeni: {summary.overdueInvoices}
          </div>
          <div className="admin-chip">Plaćeni: {summary.paidInvoices}</div>
          <div className="admin-chip">
            Naplata: {formatCurrency(summary.collectedAmount)}
          </div>
          <div className="admin-chip">
            Ističu paketi: {summary.expiringPlans}
          </div>
        </div>
        <p className="mt-4 text-sm text-muted-foreground">
          Trenutni otvoreni saldo kroz aktivne račune iznosi{" "}
          {formatCurrency(totalOpenBalance)}.
        </p>
      </section>

      <section className="grid gap-6 xl:grid-cols-2">
        <div className="surface rounded-[2rem] p-6">
          <p className="eyebrow">Novi predračun</p>
          <div className="mt-5 grid gap-4 lg:grid-cols-2">
            <div className="lg:col-span-2">
              <AdminCompanySearch
                selectedLabel={
                  invoiceForm.companyId
                    ? invoiceForm.buyerCompanyName || null
                    : null
                }
                onSelect={(company) =>
                  setInvoiceForm((current) => ({
                    ...current,
                    companyId: company.id,
                    buyerCompanyName: company.name ?? current.buyerCompanyName,
                    buyerEmail: company.email ?? current.buyerEmail,
                    buyerPhone: company.phone ?? current.buyerPhone,
                    buyerAddress: company.address ?? current.buyerAddress,
                    buyerCity: company.city ?? current.buyerCity,
                    buyerPib: company.pib ?? current.buyerPib,
                    buyerRegistrationNumber:
                      company.maticni ?? current.buyerRegistrationNumber,
                  }))
                }
              />
            </div>
            <select
              className="inline-select"
              value={invoiceForm.type}
              onChange={(event) => {
                const type = event.target.value;
                setInvoiceForm((current) => ({
                  ...current,
                  type,
                  planId: type === "PLAN" ? current.planId : "",
                  placementId: type === "PLACEMENT" ? current.placementId : "",
                  adCampaignId:
                    type === "AD_CAMPAIGN" ? current.adCampaignId : "",
                }));
              }}
            >
              <option value="PLAN">Paket</option>
              <option value="INSTITUTIONAL_PLAN">Institucionalni paket</option>
              <option value="PLACEMENT">Isticanje</option>
              <option value="AD_CAMPAIGN">Kampanja</option>
              <option value="JOB_PACKAGE">Paket poslova</option>
              <option value="STORE_PACKAGE">Paket prodavnice</option>
              <option value="CUSTOM">Posebna stavka</option>
            </select>
            <select
              className="inline-select"
              value={invoiceForm.planId}
              onChange={(event) => handlePlanChange(event.target.value)}
            >
              <option value="">Izaberite paket</option>
              {references.plans.map((plan) => (
                <option
                  key={plan.id}
                  value={plan.id}
                  disabled={!plan.priceRsd || plan.priceRsd <= 0}
                >
                  {plan.nameSr} · {getTierAdminLabel(plan.tier)} ·{" "}
                  {plan.priceRsd && plan.priceRsd > 0
                    ? formatCurrency(plan.priceRsd, "RSD")
                    : "Cena nije definisana"}
                </option>
              ))}
            </select>
            {invoiceForm.type === "PLAN" ? (
              <select
                className="inline-select"
                value={invoiceForm.billingPeriod}
                onChange={(event) => handleBillingPeriodChange(event.target.value)}
                title="Mesečno = cena iz cenovnika (zaključana). Godišnje = ručni iznos, paket važi 12 meseci."
              >
                <option value="MONTHLY">Naplata: Mesečno</option>
                <option value="ANNUAL">Naplata: Godišnje (12 meseci)</option>
              </select>
            ) : null}
            <select
              className="inline-select"
              value={invoiceForm.placementId}
              onChange={(event) =>
                setInvoiceForm((current) => ({
                  ...current,
                  placementId: event.target.value,
                }))
              }
            >
              <option value="">Povezano isticanje</option>
              {references.placements.map((placement) => (
                <option key={placement.id} value={placement.id}>
                  {placement.company.name} ·{" "}
                  {placement.label || placement.position}
                </option>
              ))}
            </select>
            <select
              className="inline-select"
              value={invoiceForm.adCampaignId}
              onChange={(event) =>
                setInvoiceForm((current) => ({
                  ...current,
                  adCampaignId: event.target.value,
                }))
              }
            >
              <option value="">Povezana kampanja</option>
              {references.campaigns.map((campaign) => (
                <option key={campaign.id} value={campaign.id}>
                  {campaign.name}
                </option>
              ))}
            </select>
            <AdminDateTimeField
              label="Rok plaćanja"
              value={invoiceForm.dueAt}
              onChange={(nextValue) =>
                setInvoiceForm((current) => ({ ...current, dueAt: nextValue }))
              }
              compact
              className="w-full"
            />
            <input
              className="inline-input"
              type="number"
              min={0}
              placeholder="Cena sa PDV-om"
              title="Unesite cenu SA uračunatim PDV-om — sistem sam izračuna osnovicu i PDV (20%)."
              value={invoiceForm.totalAmount}
              onChange={(event) => {
                const raw = event.target.value;
                const { subtotalAmount, taxAmount } = splitGrossAmount(
                  Number(raw) || 0,
                  20
                );
                setInvoiceForm((current) => ({
                  ...current,
                  totalAmount: raw,
                  subtotalAmount: String(subtotalAmount),
                  taxAmount: String(taxAmount),
                }));
              }}
            />
            {invoiceForm.type === "PLAN" ? (
              <p className="-mt-2 text-xs text-muted-foreground lg:col-span-2">
                Cenu određujete vi — polje je predlog iz cenovnika (kod godišnje
                12 × mesečna), slobodno je izmenite. Period „Godišnje” čini da
                paket važi 12 meseci; „Mesečno” koliko traje paket u cenovniku.
              </p>
            ) : null}
            <input
              className="inline-input opacity-70"
              placeholder="Osnovica (bez PDV)"
              title="Osnovica — izračunata automatski iz cene sa PDV-om."
              value={`Osnovica: ${invoiceForm.subtotalAmount}`}
              readOnly
            />
            <input
              className="inline-input opacity-70"
              placeholder="PDV (20%)"
              title="PDV (20%) — izračunat automatski iz cene sa PDV-om."
              value={`PDV (20%): ${invoiceForm.taxAmount}`}
              readOnly
            />
            <input
              className="inline-input"
              placeholder="Valuta"
              value={invoiceForm.currency}
              onChange={(event) =>
                setInvoiceForm((current) => ({
                  ...current,
                  currency: event.target.value,
                }))
              }
            />
          </div>
          <div className="mt-6 rounded-[1.5rem] border border-border bg-white/65 p-4">
            <p className="eyebrow">Kupac i finalni dokument</p>
            <div className="mt-4 grid gap-4 lg:grid-cols-3">
              <select
                className="inline-select"
                value={invoiceForm.buyerType}
                onChange={(event) =>
                  setInvoiceForm((current) => ({
                    ...current,
                    buyerType: event.target.value,
                  }))
                }
              >
                <option value="LEGAL_ENTITY">Pravno lice</option>
                <option value="ENTREPRENEUR">Preduzetnik</option>
                <option value="INDIVIDUAL">Fizičko lice</option>
              </select>
              {invoiceForm.buyerType === "INDIVIDUAL" ? (
                <input
                  className="inline-input lg:col-span-2"
                  placeholder="Ime i prezime"
                  value={invoiceForm.buyerName}
                  onChange={(event) =>
                    setInvoiceForm((current) => ({
                      ...current,
                      buyerName: event.target.value,
                    }))
                  }
                />
              ) : (
                <>
                  <input
                    className="inline-input lg:col-span-2"
                    placeholder="Naziv firme / preduzetnika"
                    value={invoiceForm.buyerCompanyName}
                    onChange={(event) =>
                      setInvoiceForm((current) => ({
                        ...current,
                        buyerCompanyName: event.target.value,
                      }))
                    }
                  />
                  <input
                    className="inline-input"
                    placeholder="PIB"
                    value={invoiceForm.buyerPib}
                    onChange={(event) =>
                      setInvoiceForm((current) => ({
                        ...current,
                        buyerPib: event.target.value,
                      }))
                    }
                  />
                  <input
                    className="inline-input"
                    placeholder="Matični broj"
                    value={invoiceForm.buyerRegistrationNumber}
                    onChange={(event) =>
                      setInvoiceForm((current) => ({
                        ...current,
                        buyerRegistrationNumber: event.target.value,
                      }))
                    }
                  />
                  <input
                    className="inline-input"
                    placeholder="Kontakt osoba"
                    value={invoiceForm.buyerContactName}
                    onChange={(event) =>
                      setInvoiceForm((current) => ({
                        ...current,
                        buyerContactName: event.target.value,
                      }))
                    }
                  />
                </>
              )}
              <input
                className="inline-input"
                placeholder="Email za predračun"
                value={invoiceForm.buyerEmail}
                onChange={(event) =>
                  setInvoiceForm((current) => ({
                    ...current,
                    buyerEmail: event.target.value,
                  }))
                }
              />
              <input
                className="inline-input"
                placeholder="Telefon"
                value={invoiceForm.buyerPhone}
                onChange={(event) =>
                  setInvoiceForm((current) => ({
                    ...current,
                    buyerPhone: event.target.value,
                  }))
                }
              />
              <input
                className="inline-input"
                placeholder="Grad"
                value={invoiceForm.buyerCity}
                onChange={(event) =>
                  setInvoiceForm((current) => ({
                    ...current,
                    buyerCity: event.target.value,
                  }))
                }
              />
              <input
                className="inline-input lg:col-span-2"
                placeholder="Adresa"
                value={invoiceForm.buyerAddress}
                onChange={(event) =>
                  setInvoiceForm((current) => ({
                    ...current,
                    buyerAddress: event.target.value,
                  }))
                }
              />
              <input
                className="inline-input"
                placeholder="Narudžbenica / interni broj"
                value={invoiceForm.buyerOrderReference}
                onChange={(event) =>
                  setInvoiceForm((current) => ({
                    ...current,
                    buyerOrderReference: event.target.value,
                  }))
                }
              />
            </div>
            <p className="mt-3 text-xs leading-6 text-muted-foreground">
              Za pravna lica i preduzetnike finalni dokument vodimo kao
              eFakturu. Za fizička lica vodimo fiskalni račun. Izdavanje ostaje
              ručni admin korak nakon evidentirane uplate.
            </p>
          </div>
          <textarea
            className="mt-4 min-h-[110px] w-full rounded-[1.5rem] border border-border bg-white px-4 py-3"
            placeholder="Napomena uz predračun"
            value={invoiceForm.note}
            onChange={(event) =>
              setInvoiceForm((current) => ({
                ...current,
                note: event.target.value,
              }))
            }
          />
          <button
            type="button"
            className="primary-button mt-4 inline-flex items-center justify-center gap-2"
            onClick={handleCreateInvoice}
            disabled={busy !== null}
          >
            {busy === "invoice" ? <Spinner /> : null}
            {busy === "invoice" ? "Čuvam…" : "Sačuvaj i pošalji predračun"}
          </button>
        </div>

        <div className="surface rounded-[2rem] p-6">
          <p className="eyebrow">Evidentiraj uplatu</p>
          <div className="mt-5 grid gap-4 lg:grid-cols-2">
            <select
              className="inline-select"
              value={paymentForm.invoiceId}
              onChange={(event) =>
                setPaymentForm((current) => ({
                  ...current,
                  invoiceId: event.target.value,
                }))
              }
            >
              {references.invoices.map((invoice) => (
                <option key={invoice.id} value={invoice.id}>
                  {invoice.number} · {invoice.company?.name || "Bez kompanije"}
                </option>
              ))}
            </select>
            <input
              className="inline-input"
              placeholder="Iznos"
              value={paymentForm.amount}
              onChange={(event) =>
                setPaymentForm((current) => ({
                  ...current,
                  amount: event.target.value,
                }))
              }
            />
            <select
              className="inline-select"
              value={paymentForm.method}
              onChange={(event) =>
                setPaymentForm((current) => ({
                  ...current,
                  method: event.target.value,
                }))
              }
            >
              <option value="BANK_TRANSFER">Bankovni prenos</option>
              <option value="CARD">Kartica</option>
              <option value="CASH">Keš</option>
              <option value="ONLINE">Online</option>
              <option value="OTHER">Ostalo</option>
            </select>
            <select
              className="inline-select"
              value={paymentForm.status}
              onChange={(event) =>
                setPaymentForm((current) => ({
                  ...current,
                  status: event.target.value,
                }))
              }
            >
              <option value="COMPLETED">Uspešno</option>
              <option value="PENDING">Na čekanju</option>
              <option value="FAILED">Neuspešno</option>
              <option value="REFUNDED">Refundirano</option>
              <option value="CANCELED">Otkazano</option>
            </select>
            <AdminDateTimeField
              label="Datum uplate"
              value={paymentForm.paidAt}
              onChange={(nextValue) =>
                setPaymentForm((current) => ({ ...current, paidAt: nextValue }))
              }
              compact
              className="w-full"
            />
            <input
              className="inline-input"
              placeholder="Transakcioni broj"
              value={paymentForm.transactionRef}
              onChange={(event) =>
                setPaymentForm((current) => ({
                  ...current,
                  transactionRef: event.target.value,
                }))
              }
            />
          </div>
          <textarea
            className="mt-4 min-h-[110px] w-full rounded-[1.5rem] border border-border bg-white px-4 py-3"
            placeholder="Napomena uz uplatu"
            value={paymentForm.note}
            onChange={(event) =>
              setPaymentForm((current) => ({
                ...current,
                note: event.target.value,
              }))
            }
          />
          <button
            type="button"
            className="primary-button mt-4 inline-flex items-center justify-center gap-2"
            onClick={handleRecordPayment}
            disabled={busy !== null}
          >
            {busy === "payment" ? <Spinner /> : null}
            {busy === "payment" ? "Upisujem…" : "Upiši uplatu"}
          </button>
        </div>
      </section>

      <section className="admin-command-shell">
        <div className="admin-command-header">
          <div>
            <p className="eyebrow">Računi</p>
            <h3 className="mt-2 text-3xl font-semibold text-foreground">
              Brze komercijalne izmene
            </h3>
          </div>
          <div className="admin-command-actions">
            <select
              className="inline-select min-w-[220px]"
              value={bulkStatus}
              onChange={(event) => setBulkStatus(event.target.value)}
            >
              <option value="">Masovna promena statusa</option>
              <option value="DRAFT">Nacrt</option>
              <option value="ISSUED">Izdato</option>
              <option value="PARTIALLY_PAID">Delimično plaćeno</option>
              <option value="PAID">Plaćeno</option>
              <option value="OVERDUE">Dospelo</option>
              <option value="CANCELED">Otkazano</option>
            </select>
            <button
              type="button"
              className="primary-button inline-flex items-center justify-center gap-2"
              onClick={handleBulkUpdate}
              disabled={busy !== null || !selectedIds.length || !bulkStatus}
            >
              {busy === "bulk" ? <Spinner /> : null}
              {busy === "bulk" ? "Primenjujem…" : "Primeni na označene"}
            </button>
          </div>
        </div>

        {message ? (
          <div className="mt-4 rounded-[1.2rem] bg-accent/55 px-4 py-3 text-sm font-medium text-primary">
            {message}
          </div>
        ) : null}

        <div className="mt-5 space-y-4">
          {invoices.map((invoice) => (
            <article
              key={invoice.id}
              className="rounded-[1.5rem] border border-border bg-white/85 p-5"
            >
              <div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
                <div className="flex items-start gap-4">
                  <input
                    type="checkbox"
                    aria-label={`Označi račun ${invoice.number}`}
                    checked={selectedIds.includes(invoice.id)}
                    onChange={() => toggleSelection(invoice.id)}
                    className="mt-2 size-4"
                  />
                  <div>
                    <h4 className="text-xl font-semibold text-foreground">
                      {invoice.number}
                    </h4>
                    <p className="mt-1 text-sm text-muted-foreground">
                      {invoice.company?.name || "Bez kompanije"} ·{" "}
                      {getInvoiceTypeLabel(invoice.type)}
                    </p>
                    <div className="mt-3 flex flex-wrap gap-2">
                      <span className="admin-chip">
                        {getInvoiceStatusLabel(invoice.status)}
                      </span>
                      <span className="admin-chip">
                        {formatCurrency(invoice.totalAmount, invoice.currency)}
                      </span>
                      <span className="admin-chip">
                        Rok: {formatDate(invoice.dueAt)}
                      </span>
                    </div>
                  </div>
                </div>
                <div className="rounded-[1.2rem] bg-muted/55 px-4 py-3 text-sm text-muted-foreground">
                  Uplata evidentirano:{" "}
                  {formatCurrency(
                    invoice.payments
                      .filter((payment) => payment.status === "COMPLETED")
                      .reduce((sum, payment) => sum + payment.amount, 0),
                    invoice.currency
                  )}
                </div>
              </div>

              <div className="mt-4 flex flex-wrap gap-3">
                <a
                  href={`/api/admin/invoices/${invoice.id}/proforma`}
                  target="_blank"
                  rel="noreferrer"
                  className="ghost-button"
                >
                  PDF predračun
                </a>
                <button
                  type="button"
                  className="ghost-button inline-flex items-center gap-2"
                  onClick={() => handleSendProforma(invoice.id)}
                  disabled={busy !== null}
                >
                  {busy === `send:${invoice.id}` ? <Spinner /> : null}
                  {busy === `send:${invoice.id}` ? "Šaljem…" : "Pošalji email"}
                </button>
                {invoice.status === "PAID" &&
                invoice.finalDocumentStatus !== "ISSUED" ? (
                  <button
                    type="button"
                    className="primary-button inline-flex items-center gap-2"
                    onClick={() => handleMarkFinalDocument(invoice)}
                    disabled={busy !== null}
                  >
                    {busy === `final:${invoice.id}` ? <Spinner /> : null}
                    {busy === `final:${invoice.id}`
                      ? "Izdajem…"
                      : `Označi ${finalDocumentLabel(
                          invoice.finalDocumentType
                        )} kao izdat`}
                  </button>
                ) : (
                  <span className="admin-chip">
                    Finalni dokument:{" "}
                    {invoice.finalDocumentStatus === "ISSUED"
                      ? `Izdat${
                          invoice.finalDocumentNumber
                            ? ` · ${invoice.finalDocumentNumber}`
                            : ""
                        }`
                      : finalDocumentLabel(invoice.finalDocumentType)}
                  </span>
                )}
                <span className="admin-chip">
                  {buyerTypeLabel(invoice.buyerType)}
                </span>
                {invoice.status !== "PAID" &&
                invoice.status !== "PARTIALLY_PAID" ? (
                  <button
                    type="button"
                    className="ghost-button ml-auto inline-flex items-center gap-2 text-red-600 hover:bg-red-50 hover:text-red-700"
                    onClick={() => handleDeleteInvoice(invoice)}
                    disabled={busy !== null}
                  >
                    {busy === `delete:${invoice.id}` ? <Spinner /> : null}
                    {busy === `delete:${invoice.id}`
                      ? "Brišem…"
                      : "Obriši predračun"}
                  </button>
                ) : null}
              </div>

              <div className="mt-4 grid gap-3 lg:grid-cols-3">
                <div className="rounded-[1.2rem] bg-muted/35 p-4 text-sm">
                  <p className="font-semibold text-foreground">Plan / paket</p>
                  <p className="mt-2 text-muted-foreground">
                    {invoice.institutionalPlan
                      ? invoice.institutionalPlan.nameSr
                      : invoice.plan
                      ? `${invoice.plan.nameSr} · ${getTierAdminLabel(
                          invoice.plan.tier
                        )}`
                      : "Nije vezan"}
                  </p>
                </div>
                <div className="rounded-[1.2rem] bg-muted/35 p-4 text-sm">
                  <p className="font-semibold text-foreground">Isticanje</p>
                  <p className="mt-2 text-muted-foreground">
                    {invoice.placement?.label ||
                      invoice.placement?.position ||
                      "Nije vezano"}
                  </p>
                </div>
                <div className="rounded-[1.2rem] bg-muted/35 p-4 text-sm">
                  <p className="font-semibold text-foreground">Kampanja</p>
                  <p className="mt-2 text-muted-foreground">
                    {invoice.adCampaign?.name || "Nije vezana"}
                  </p>
                </div>
              </div>
            </article>
          ))}
        </div>
      </section>

      <section className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]">
        <div className="surface rounded-[2rem] p-6">
          <p className="eyebrow">Poslednje uplate</p>
          <div className="mt-5 space-y-3">
            {payments.map((payment) => (
              <div
                key={payment.id}
                className="rounded-[1.2rem] border border-border bg-white/80 px-4 py-4 text-sm"
              >
                <div className="flex items-center justify-between gap-3">
                  <span className="font-semibold text-foreground">
                    {payment.invoice.number}
                  </span>
                  <span className="text-muted-foreground">
                    {formatCurrency(payment.amount, payment.currency)}
                  </span>
                </div>
                <p className="mt-2 text-muted-foreground">
                  {payment.invoice.company?.name || "Bez kompanije"} ·{" "}
                  {getPaymentMethodLabel(payment.method)} ·{" "}
                  {getPaymentStatusLabel(payment.status)}
                </p>
                <p className="mt-1 text-xs text-muted-foreground">
                  Datum: {formatDate(payment.paidAt)}
                </p>
              </div>
            ))}
          </div>
        </div>

        <div className="surface rounded-[2rem] p-6">
          <p className="eyebrow">Upozorenja naplate</p>
          <div className="mt-5 space-y-3">
            {alerts.length ? (
              alerts.map((alert) => (
                <div
                  key={alert.id}
                  className="rounded-[1.2rem] border border-border bg-white/80 px-4 py-4"
                >
                  <p className="text-sm font-semibold text-foreground">
                    {alert.title}
                  </p>
                  <p className="mt-2 text-sm text-muted-foreground">
                    {alert.message}
                  </p>
                  <p className="mt-2 text-xs uppercase tracking-[0.14em] text-primary">
                    {alert.company?.name ||
                      alert.invoice?.number ||
                      alert.level}
                  </p>
                </div>
              ))
            ) : (
              <div className="rounded-[1.2rem] border border-border bg-white/80 px-4 py-4 text-sm text-muted-foreground">
                Trenutno nema otvorenih upozorenja za naplatu.
              </div>
            )}
          </div>
        </div>
      </section>
    </div>
  );
}
