import { useState, useEffect, useMemo, useCallback, useRef } from "react";
import {
  useNavigate,
  useSearchParams,
  useParams,
  Link,
} from "react-router-dom";
import DOMPurify from "dompurify";
import { useAlert } from "../context/AlertContext";
import { useAuth } from "../context/AuthContext";
import Forbidden from "../components/Forbidden";
import FormField from "../components/FormField";
import AdminDatePicker from "../components/AdminDatePicker";
import ConfirmModal from "../components/ConfirmModal";
import { motion } from "framer-motion";
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  TouchSensor,
  useSensor,
  useSensors,
  type DragEndEvent,
} from "@dnd-kit/core";
import {
  SortableContext,
  verticalListSortingStrategy,
  useSortable,
  arrayMove,
} from "@dnd-kit/sortable";
import {
  restrictToVerticalAxis,
  restrictToParentElement,
} from "@dnd-kit/modifiers";
import { CSS } from "@dnd-kit/utilities";
import apiFetch from "../utils/api";
import { formatCurrency, formatDate } from "../utils/formatters";

const API_BASE = "/api/admin";

const STATUS_LABELS: Record<string, string> = {
  issued: "Vystavena",
  paid: "Zaplacena",
  overdue: "Po splatnosti",
};

const STATUS_CLASSES: Record<string, string> = {
  issued: "admin-badge-invoice-issued",
  paid: "admin-badge-invoice-paid",
  overdue: "admin-badge-invoice-overdue",
};

const TRANSITION_LABELS: Record<string, string> = { paid: "Zaplaceno" };
const TRANSITION_CLASSES: Record<string, string> = {
  paid: "admin-btn admin-btn-primary",
};

interface InvoiceItem {
  id?: number;
  _key: string;
  description: string;
  quantity: number;
  unit: string;
  unit_price: number;
  vat_rate: number;
}

interface Customer {
  id: number;
  name: string;
  company_id?: string;
  city?: string;
}

interface BankAccount {
  id: number;
  account_name: string;
  account_number?: string;
  bank_name?: string;
  bic?: string;
  iban?: string;
  is_default?: boolean;
}

interface InvoiceForm {
  customer_id: number | null;
  customer_name: string;
  order_id: number | null;
  issue_date: string;
  due_date: string;
  tax_date: string;
  currency: string;
  apply_vat: number;
  vat_rate: number;
  payment_method: string;
  constant_symbol: string;
  issued_by: string;
  billing_text: string;
  notes: string;
  language: string;
  bank_account_id: number | string;
  bank_name: string;
  bank_swift: string;
  bank_iban: string;
  bank_account: string;
}

interface InvoiceCustomer {
  company_id?: string;
  vat_id?: string;
}

interface Invoice {
  id: number;
  invoice_number: string;
  customer_id?: number | null;
  customer_name: string | null;
  customer?: InvoiceCustomer;
  order_id?: number;
  order_number?: string;
  currency: string;
  status: string;
  issue_date: string;
  due_date: string;
  tax_date: string;
  payment_method: string;
  constant_symbol?: string;
  issued_by: string | null;
  paid_date?: string;
  notes: string;
  language: string;
  apply_vat: number | string;
  vat_rate?: number;
  billing_text?: string;
  bank_name?: string;
  bank_swift?: string;
  bank_iban?: string;
  bank_account?: string;
  bank_account_id?: number | null;
  items: Omit<InvoiceItem, "_key">[];
  valid_transitions?: string[];
}

// Sortable row for create mode
function SortableInvoiceRow({
  item,
  index,
  currency,
  apply_vat,
  vatOptions,
  onUpdate,
  onRemove,
  canDelete,
}: {
  item: InvoiceItem;
  index: number;
  currency: string;
  apply_vat: boolean;
  vatOptions: { value: number; label: string }[];
  onUpdate: (
    index: number,
    field: keyof InvoiceItem,
    value: string | number,
  ) => void;
  onRemove: (index: number) => void;
  canDelete: boolean;
}) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id: item._key });
  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
    background: isDragging ? "var(--bg-secondary)" : undefined,
    position: "relative" as const,
    zIndex: isDragging ? 10 : undefined,
  };
  const lineTotal =
    (Number(item.quantity) || 0) * (Number(item.unit_price) || 0);
  return (
    <tr ref={setNodeRef} style={style}>
      <td style={{ width: "2rem" }}>
        <button
          type="button"
          className="admin-drag-handle"
          {...attributes}
          {...listeners}
          title="Přetáhnout"
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
            <circle cx="9" cy="5" r="1.5" />
            <circle cx="15" cy="5" r="1.5" />
            <circle cx="9" cy="12" r="1.5" />
            <circle cx="15" cy="12" r="1.5" />
            <circle cx="9" cy="19" r="1.5" />
            <circle cx="15" cy="19" r="1.5" />
          </svg>
        </button>
      </td>
      <td className="text-tertiary text-center fw-500">{index + 1}</td>
      <td>
        <input
          type="text"
          value={item.description}
          onChange={(e) => onUpdate(index, "description", e.target.value)}
          className="admin-form-input fw-500"
          placeholder="Popis položky..."
        />
      </td>
      <td>
        <input
          type="number"
          value={item.quantity}
          onChange={(e) => onUpdate(index, "quantity", e.target.value)}
          className="admin-form-input"
          min="0"
          step="any"
          style={{
            textAlign: "center",
            height: "2.25rem",
            padding: "0.375rem 0.5rem",
          }}
        />
      </td>
      <td>
        <input
          type="text"
          value={item.unit}
          onChange={(e) => onUpdate(index, "unit", e.target.value)}
          className="admin-form-input"
          placeholder="ks"
          style={{
            textAlign: "center",
            height: "2.25rem",
            padding: "0.375rem 0.5rem",
          }}
        />
      </td>
      <td>
        <input
          type="number"
          value={item.unit_price}
          onChange={(e) => onUpdate(index, "unit_price", e.target.value)}
          className="admin-form-input"
          step="any"
          style={{
            textAlign: "right",
            height: "2.25rem",
            padding: "0.375rem 0.5rem",
          }}
        />
      </td>
      {apply_vat ? (
        <td>
          <select
            value={item.vat_rate}
            onChange={(e) =>
              onUpdate(index, "vat_rate", Number(e.target.value))
            }
            className="admin-form-select"
            style={{
              height: "2.25rem",
              padding: "0.375rem 0.5rem",
              minWidth: "4.5rem",
            }}
          >
            {vatOptions.map((o) => (
              <option key={o.value} value={o.value}>
                {o.label}
              </option>
            ))}
          </select>
        </td>
      ) : null}
      <td className="text-right fw-600 whitespace-nowrap">
        {formatCurrency(lineTotal, currency)}
      </td>
      <td>
        {canDelete && (
          <button
            type="button"
            onClick={() => onRemove(index)}
            className="admin-btn-icon danger"
            title="Odebrat"
            aria-label="Odebrat"
          >
            <svg
              width="12"
              height="12"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
            >
              <line x1="18" y1="6" x2="6" y2="18" />
              <line x1="6" y1="6" x2="18" y2="18" />
            </svg>
          </button>
        )}
      </td>
    </tr>
  );
}

export default function InvoiceDetail() {
  const { id } = useParams<{ id: string }>();
  const isEdit = Boolean(id);

  const keyCounterRef = useRef(1);
  const emptyItem = useCallback(
    (): InvoiceItem => ({
      _key: `inv-${++keyCounterRef.current}`,
      description: "",
      quantity: 1,
      unit: "ks",
      unit_price: 0,
      vat_rate: 21,
    }),
    [],
  );

  const dndSensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
    useSensor(TouchSensor, {
      activationConstraint: { delay: 200, tolerance: 5 },
    }),
    useSensor(KeyboardSensor),
  );

  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const alert = useAlert();
  const { hasPermission, user } = useAuth();

  // ─── Create mode state ───
  const rawOrderId = searchParams.get("fromOrder");
  const fromOrderId =
    !isEdit && rawOrderId && /^\d+$/.test(rawOrderId) ? rawOrderId : null;

  const [form, setForm] = useState<InvoiceForm>({
    customer_id: null,
    customer_name: "",
    order_id: fromOrderId ? Number(fromOrderId) : null,
    issue_date: new Date().toISOString().split("T")[0],
    due_date: new Date(Date.now() + 14 * 86400000).toISOString().split("T")[0],
    tax_date: new Date().toISOString().split("T")[0],
    currency: "CZK",
    apply_vat: 1,
    vat_rate: 21,
    payment_method: "Příkazem",
    constant_symbol: "0308",
    issued_by: user?.fullName || "",
    billing_text: "",
    notes: "",
    language: "cs",
    bank_account_id: "",
    bank_name: "",
    bank_swift: "",
    bank_iban: "",
    bank_account: "",
  });

  const [bankAccounts, setBankAccounts] = useState<BankAccount[]>([]);
  const [dueDays, setDueDays] = useState(14);
  const [items, setItems] = useState<InvoiceItem[]>([
    {
      _key: "inv-1",
      description: "",
      quantity: 1,
      unit: "ks",
      unit_price: 0,
      vat_rate: 21,
    },
  ]);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(true);
  const [invoiceNumber, setInvoiceNumber] = useState("");
  const initialSnapshotRef = useRef<string | null>(null);
  const hasSetInitialSnapshot = useRef(false);

  const [customers, setCustomers] = useState<Customer[]>([]);
  const [customerSearch, setCustomerSearch] = useState("");
  const [showCustomerDropdown, setShowCustomerDropdown] = useState(false);

  const [companySettings, setCompanySettings] = useState<{
    default_currency: string;
    default_vat_rate: number;
    available_currencies: string[];
    available_vat_rates: number[];
  } | null>(null);

  useEffect(() => {
    apiFetch(`${API_BASE}/company-settings`)
      .then((r) => r.json())
      .then((d) => {
        if (d.success) setCompanySettings(d.data);
      })
      .catch(() => {});
  }, []);

  const vatOptions = (
    companySettings?.available_vat_rates || [0, 10, 12, 15, 21]
  ).map((v) => ({
    value: v,
    label: `${v}%`,
  }));

  useEffect(() => {
    if (companySettings && !isEdit) {
      setForm((prev) => ({
        ...prev,
        currency:
          prev.currency === "CZK"
            ? companySettings.default_currency || "CZK"
            : prev.currency,
        vat_rate:
          prev.vat_rate === 21
            ? (companySettings.default_vat_rate ?? 21)
            : prev.vat_rate,
      }));
    }
  }, [companySettings, isEdit]);

  const DRAFT_KEY = "boha_invoice_draft";

  const clearDraft = useCallback(() => {
    try {
      localStorage.removeItem(DRAFT_KEY);
    } catch {
      /* ignore */
    }
  }, []);

  // ─── Edit mode state ───
  const [invoice, setInvoice] = useState<Invoice | null>(null);
  const [notes, setNotes] = useState("");
  const [statusChanging, setStatusChanging] = useState<string | null>(null);
  const [statusConfirm, setStatusConfirm] = useState<{
    show: boolean;
    status: string | null;
  }>({ show: false, status: null });
  const [pdfLoading, setPdfLoading] = useState(false);
  const [deleteConfirm, setDeleteConfirm] = useState(false);
  const [deleting, setDeleting] = useState(false);

  // ─── Data loading ───

  useEffect(() => {
    if (isEdit) return;
    const load = async () => {
      try {
        const promises = [
          apiFetch(`${API_BASE}/invoices/next-number`),
          apiFetch(`${API_BASE}/customers`),
          apiFetch(`${API_BASE}/bank-accounts`),
        ];
        if (fromOrderId) {
          promises.push(
            apiFetch(`${API_BASE}/invoices/order-data/${fromOrderId}`),
          );
        }

        const results = await Promise.all(promises);

        const numRes = results[0];
        if (numRes.ok) {
          const numData = await numRes.json();
          if (numData.success)
            setInvoiceNumber(
              numData.data?.next_number || numData.data?.number || "",
            );
        }

        const custRes = results[1];
        if (custRes.ok) {
          const custData = await custRes.json();
          if (custData.success)
            setCustomers(
              Array.isArray(custData.data)
                ? custData.data
                : custData.data?.customers || [],
            );
        }

        const bankRes = results[2];
        if (bankRes.ok) {
          const bankData = await bankRes.json();
          if (bankData.success && Array.isArray(bankData.data)) {
            setBankAccounts(bankData.data);
            const defaultAcc = bankData.data.find(
              (a: BankAccount) => a.is_default,
            );
            if (defaultAcc) {
              setForm((prev) => ({
                ...prev,
                bank_account_id: defaultAcc.id,
                bank_name: defaultAcc.bank_name || "",
                bank_swift: defaultAcc.bic || "",
                bank_iban: defaultAcc.iban || "",
                bank_account: defaultAcc.account_number || "",
              }));
            }
          }
        }

        // Pre-fill from order
        if (fromOrderId && results[3]?.ok) {
          const orderData = await results[3].json();
          if (orderData.success) {
            const order = orderData.data;
            const vatRate =
              Number(order.vat_rate) ||
              (companySettings?.default_vat_rate ?? 21);
            setForm((prev) => ({
              ...prev,
              customer_id: order.customer_id,
              customer_name: order.customer_name || "",
              order_id: order.id,
              currency:
                order.currency || companySettings?.default_currency || "CZK",
              apply_vat: Number(order.apply_vat) || 0,
              vat_rate: vatRate,
            }));
            if (order.items?.length > 0) {
              setItems(
                order.items.map((item: Record<string, unknown>) => ({
                  _key: `inv-${++keyCounterRef.current}`,
                  description: (item.description as string) || "",
                  quantity: Number(item.quantity) || 1,
                  unit: (item.unit as string) || "",
                  unit_price: Number(item.unit_price) || 0,
                  vat_rate: vatRate,
                })),
              );
            }
          }
        }
      } catch {
        alert.error("Chyba při načítání dat");
      } finally {
        setLoading(false);
      }
    };
    load();
  }, [isEdit, fromOrderId, alert]);

  // Edit mode: load existing invoice
  const fetchDetail = useCallback(async () => {
    if (!id) return;
    try {
      const [response, custRes, bankRes] = await Promise.all([
        apiFetch(`${API_BASE}/invoices/${id}`),
        apiFetch(`${API_BASE}/customers`),
        apiFetch(`${API_BASE}/bank-accounts`),
      ]);
      if (response.status === 401) return;
      const result = await response.json();
      if (result.success) {
        const inv = result.data;
        setInvoice(inv);
        setNotes(inv.notes || "");
        setInvoiceNumber(inv.invoice_number || "");

        // Populate customers list
        if (custRes.ok) {
          const custData = await custRes.json();
          if (custData.success)
            setCustomers(
              Array.isArray(custData.data)
                ? custData.data
                : custData.data?.customers || [],
            );
        }

        // Populate bank accounts and match existing
        let matchedBankId: number | string = "";
        if (bankRes.ok) {
          const bankData = await bankRes.json();
          if (bankData.success && Array.isArray(bankData.data)) {
            setBankAccounts(bankData.data);
            // Match by IBAN or account number
            const match = bankData.data.find(
              (b: BankAccount) =>
                (inv.bank_iban && b.iban === inv.bank_iban) ||
                (inv.bank_account && b.account_number === inv.bank_account),
            );
            if (match) matchedBankId = match.id;
          }
        }

        // Populate form state from existing invoice
        setForm({
          customer_id: inv.customer_id || null,
          customer_name: inv.customer_name || "",
          order_id: inv.order_id || null,
          issue_date: inv.issue_date
            ? new Date(inv.issue_date).toISOString().split("T")[0]
            : "",
          due_date: inv.due_date
            ? new Date(inv.due_date).toISOString().split("T")[0]
            : "",
          tax_date: inv.tax_date
            ? new Date(inv.tax_date).toISOString().split("T")[0]
            : "",
          currency: inv.currency || "CZK",
          apply_vat: Number(inv.apply_vat) ? 1 : 0,
          vat_rate: Number(inv.vat_rate) || 21,
          payment_method: inv.payment_method || "Příkazem",
          constant_symbol: inv.constant_symbol || "0308",
          issued_by: inv.issued_by || "",
          billing_text: inv.billing_text || "",
          notes: inv.notes || "",
          language: inv.language || "cs",
          bank_account_id: matchedBankId,
          bank_name: inv.bank_name || "",
          bank_swift: inv.bank_swift || "",
          bank_iban: inv.bank_iban || "",
          bank_account: inv.bank_account || "",
        });

        // Calculate dueDays from existing dates
        if (inv.issue_date && inv.due_date) {
          const issue = new Date(inv.issue_date);
          const due = new Date(inv.due_date);
          const diffDays = Math.round(
            (due.getTime() - issue.getTime()) / (1000 * 60 * 60 * 24),
          );
          if (diffDays > 0 && diffDays <= 60) setDueDays(diffDays);
        }

        // Populate items from existing invoice
        if (inv.items?.length > 0) {
          setItems(
            inv.items.map((item: Record<string, unknown>) => ({
              _key: `inv-${++keyCounterRef.current}`,
              id: item.id as number | undefined,
              description: (item.description as string) || "",
              quantity: Number(item.quantity) || 1,
              unit: (item.unit as string) || "",
              unit_price: Number(item.unit_price) || 0,
              vat_rate: Number(item.vat_rate) || Number(inv.vat_rate) || 21,
            })),
          );
        }
      } else {
        alert.error(result.error || "Nepodařilo se načíst fakturu");
        navigate("/invoices");
      }
    } catch {
      alert.error("Chyba připojení");
      navigate("/invoices");
    } finally {
      setLoading(false);
    }
  }, [id, alert, navigate]);

  useEffect(() => {
    if (isEdit) fetchDetail();
  }, [isEdit, fetchDetail]);

  useEffect(() => {
    if (loading) {
      hasSetInitialSnapshot.current = false;
      return;
    }
    if (!hasSetInitialSnapshot.current) {
      initialSnapshotRef.current = JSON.stringify({ form, items });
      hasSetInitialSnapshot.current = true;
    }
  }, [loading, form, items]);

  const isDirty = useMemo(() => {
    if (!initialSnapshotRef.current) return false;
    return JSON.stringify({ form, items }) !== initialSnapshotRef.current;
  }, [form, items]);

  useEffect(() => {
    if (!isDirty) return;
    const handler = (e: BeforeUnloadEvent) => {
      e.preventDefault();
      e.returnValue = "";
    };
    window.addEventListener("beforeunload", handler);
    return () => window.removeEventListener("beforeunload", handler);
  }, [isDirty]);

  // ─── Due date calculation from issue date + days ───
  useEffect(() => {
    if (!form.issue_date) return;
    const d = new Date(form.issue_date);
    d.setDate(d.getDate() + dueDays);
    setForm((prev) => ({ ...prev, due_date: d.toISOString().split("T")[0] }));
  }, [form.issue_date, dueDays]);

  // ─── Create mode: customer filtering ───
  const filteredCustomers = useMemo(() => {
    if (!customerSearch) return customers;
    const q = customerSearch.toLowerCase();
    return customers.filter(
      (c) =>
        (c.name || "").toLowerCase().includes(q) ||
        (c.company_id || "").includes(customerSearch) ||
        (c.city || "").toLowerCase().includes(q),
    );
  }, [customers, customerSearch]);

  useEffect(() => {
    const handleClickOutside = () => setShowCustomerDropdown(false);
    if (showCustomerDropdown) {
      document.addEventListener("click", handleClickOutside);
      return () => document.removeEventListener("click", handleClickOutside);
    }
  }, [showCustomerDropdown]);

  const selectBankAccount = (accountId: string) => {
    const acc = bankAccounts.find((a) => a.id === Number(accountId));
    if (acc) {
      setForm((prev) => ({
        ...prev,
        bank_account_id: acc.id,
        bank_name: acc.bank_name || "",
        bank_swift: acc.bic || "",
        bank_iban: acc.iban || "",
        bank_account: acc.account_number || "",
      }));
    } else {
      setForm((prev) => ({
        ...prev,
        bank_account_id: "",
        bank_name: "",
        bank_swift: "",
        bank_iban: "",
        bank_account: "",
      }));
    }
  };

  const selectCustomer = (customer: Customer) => {
    setForm((prev) => ({
      ...prev,
      customer_id: customer.id,
      customer_name: customer.name,
    }));
    setErrors((prev) => ({ ...prev, customer_id: "" }));
    setCustomerSearch("");
    setShowCustomerDropdown(false);
  };

  // ─── Create mode: items management ───
  const updateItem = (
    index: number,
    field: keyof InvoiceItem,
    value: string | number,
  ) => {
    setItems((prev) =>
      prev.map((item, i) => (i === index ? { ...item, [field]: value } : item)),
    );
  };

  const addItem = () => setItems((prev) => [...prev, emptyItem()]);

  const removeItem = (index: number) => {
    if (items.length <= 1) return;
    setItems((prev) => prev.filter((_, i) => i !== index));
  };

  const handleCreateDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    if (!over || active.id === over.id) return;
    setItems((prev) => {
      const oldIndex = prev.findIndex((i) => i._key === String(active.id));
      const newIndex = prev.findIndex((i) => i._key === String(over.id));
      if (oldIndex === -1 || newIndex === -1) return prev;
      return arrayMove(prev, oldIndex, newIndex);
    });
  };

  // ─── Create mode: totals ───
  const createTotals = useMemo(() => {
    let subtotal = 0;
    const vatByRate: Record<number, number> = {};

    items.forEach((item) => {
      const lineTotal =
        (Number(item.quantity) || 0) * (Number(item.unit_price) || 0);
      subtotal += lineTotal;

      if (form.apply_vat) {
        const rate = Number(item.vat_rate) || 0;
        if (!vatByRate[rate]) vatByRate[rate] = 0;
        vatByRate[rate] += (lineTotal * rate) / 100;
      }
    });

    const totalVat = Object.values(vatByRate).reduce((s, v) => s + v, 0);
    return { subtotal, vatByRate, totalVat, total: subtotal + totalVat };
  }, [items, form.apply_vat]);

  // ─── Create/Edit mode: submit ───
  const handleCreateSubmit = async (e?: React.FormEvent) => {
    e?.preventDefault();

    const newErrors: Record<string, string> = {};
    if (!form.customer_id) newErrors.customer_id = "Vyberte zákazníka";
    if (!form.issue_date) newErrors.issue_date = "Zadejte datum";
    if (!form.tax_date) newErrors.tax_date = "Zadejte datum";
    if (!form.bank_account_id)
      newErrors.bank_account_id = "Vyberte bankovní účet";
    if (items.length === 0 || items.every((i) => !i.description.trim())) {
      newErrors.items = "Přidejte alespoň jednu položku";
    }
    setErrors(newErrors);
    if (Object.keys(newErrors).length > 0) return;

    setSaving(true);
    try {
      const payload: any = {
        ...form,
        items: items
          .filter((i) => i.description.trim())
          .map((item, i) => ({
            ...item,
            position: i,
          })),
      };
      if (isEdit) payload.invoice_number = invoiceNumber;

      const url = isEdit
        ? `${API_BASE}/invoices/${id}`
        : `${API_BASE}/invoices`;
      const method = isEdit ? "PUT" : "POST";

      const response = await apiFetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      const result = await response.json();
      if (result.success) {
        if (!isEdit) clearDraft();
        const invoiceId = isEdit ? id : result.data.invoice_id;
        await apiFetch(
          `${API_BASE}/invoices-pdf/${invoiceId}?lang=${form.language}&save=1`,
        ).catch(() => {});
        alert.success(
          result.message ||
            (isEdit ? "Faktura byla uložena" : "Faktura byla vytvořena"),
        );
        initialSnapshotRef.current = JSON.stringify({ form, items });
        hasSetInitialSnapshot.current = true;
        if (isEdit) {
          fetchDetail();
        } else {
          navigate(`/invoices/${result.data.invoice_id}`);
        }
      } else {
        alert.error(
          result.error ||
            (isEdit
              ? "Nepodařilo se uložit fakturu"
              : "Nepodařilo se vytvořit fakturu"),
        );
      }
    } catch {
      alert.error("Chyba připojení");
    } finally {
      setSaving(false);
    }
  };

  // ─── Edit mode: status change ───
  const handleStatusChange = async () => {
    if (!statusConfirm.status) return;
    setStatusChanging(statusConfirm.status);
    setStatusConfirm({ show: false, status: null });
    try {
      const response = await apiFetch(`${API_BASE}/invoices/${id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status: statusConfirm.status }),
      });
      const result = await response.json();
      if (result.success) {
        alert.success(result.message || "Stav byl změněn");
        fetchDetail();
      } else {
        alert.error(result.error || "Nepodařilo se změnit stav");
      }
    } catch {
      alert.error("Chyba připojení");
    } finally {
      setStatusChanging(null);
    }
  };

  // ─── Edit mode: PDF export ───
  const handleViewPdf = async (_lang = "cs") => {
    const newWindow = window.open("", "_blank");
    setPdfLoading(true);
    try {
      const response = await apiFetch(`${API_BASE}/invoices/${id}/file`);
      if (!response.ok) {
        newWindow?.close();
        alert.error("PDF soubor nenalezen — uložte fakturu pro vygenerování");
        return;
      }
      const blob = await response.blob();
      const url = URL.createObjectURL(blob);
      if (newWindow) newWindow.location.href = url;
      setTimeout(() => URL.revokeObjectURL(url), 60000);
    } catch {
      newWindow?.close();
      alert.error("Chyba připojení");
    } finally {
      setPdfLoading(false);
    }
  };

  // ─── Edit mode: delete ───
  const handleDelete = async () => {
    setDeleting(true);
    try {
      const response = await apiFetch(`${API_BASE}/invoices/${id}`, {
        method: "DELETE",
      });
      const result = await response.json();
      if (result.success) {
        alert.success(result.message || "Faktura byla smazána");
        navigate("/invoices");
      } else {
        alert.error(result.error || "Nepodařilo se smazat fakturu");
      }
    } catch {
      alert.error("Chyba připojení");
    } finally {
      setDeleting(false);
      setDeleteConfirm(false);
    }
  };

  // ─── Permission checks ───
  if (!isEdit && !hasPermission("invoices.create")) return <Forbidden />;
  if (isEdit && !hasPermission("invoices.view")) return <Forbidden />;

  // ─── Loading skeleton ───
  if (loading) {
    return (
      <div className="admin-skeleton" style={{ padding: 0, gap: "1.5rem" }}>
        <div
          className="admin-skeleton-row"
          style={{ justifyContent: "space-between" }}
        >
          <div className="flex-row-gap">
            {isEdit && (
              <div
                className="admin-skeleton-line"
                style={{ width: "32px", height: "32px", borderRadius: "8px" }}
              />
            )}
            <div
              className="admin-skeleton-line h-8"
              style={{ width: "200px" }}
            />
          </div>
          {isEdit && (
            <div className="admin-skeleton-row gap-2">
              <div
                className="admin-skeleton-line h-10"
                style={{ width: "100px", borderRadius: "8px" }}
              />
              <div
                className="admin-skeleton-line h-10"
                style={{ width: "100px", borderRadius: "8px" }}
              />
            </div>
          )}
        </div>
        <div className="admin-card">
          <div className="admin-skeleton" style={{ gap: "1.25rem" }}>
            {[0, 1, 2, 3].map((i) => (
              <div key={i} className="admin-skeleton-row">
                <div className="admin-skeleton-line w-1/4" />
                <div className="admin-skeleton-line w-1/2" />
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  // ═══════════════════════════════════════════════════════════
  // PAID INVOICE — read-only view
  // ═══════════════════════════════════════════════════════════
  const isPaid = isEdit && invoice?.status === "paid";

  if (isEdit && !invoice) return null;

  if (isPaid && invoice) {
    return (
      <div>
        {/* Header */}
        <motion.div
          className="admin-page-header"
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.25 }}
        >
          <div className="flex-row gap-4">
            <Link
              to="/invoices"
              className="admin-btn-icon"
              title="Zpět"
              aria-label="Zpět"
            >
              <svg
                width="20"
                height="20"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <path d="M19 12H5M12 19l-7-7 7-7" />
              </svg>
            </Link>
            <div>
              <h1 className="admin-page-title flex-row-gap">
                Faktura {invoice.invoice_number}
                <span
                  className={`admin-badge ${STATUS_CLASSES[invoice.status] || ""}`}
                >
                  {STATUS_LABELS[invoice.status] || invoice.status}
                </span>
              </h1>
            </div>
          </div>
          <div className="admin-page-actions">
            {hasPermission("invoices.export") && (
              <button
                onClick={() => handleViewPdf(invoice.language || "cs")}
                className="admin-btn admin-btn-secondary"
                style={{
                  display: "inline-flex",
                  alignItems: "center",
                  gap: "0.4rem",
                }}
                disabled={pdfLoading}
              >
                {pdfLoading ? (
                  <div className="admin-spinner admin-spinner-sm" />
                ) : (
                  <svg
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                  >
                    <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
                    <polyline points="14 2 14 8 20 8" />
                  </svg>
                )}
                Zobrazit fakturu
              </button>
            )}
            {hasPermission("invoices.delete") && (
              <button
                onClick={() => setDeleteConfirm(true)}
                className="admin-btn admin-btn-primary"
              >
                Smazat
              </button>
            )}
          </div>
        </motion.div>

        {/* Info */}
        <motion.div
          className="admin-editor-section"
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.25, delay: 0.06 }}
        >
          <h3 className="admin-card-title">Informace</h3>
          <div className="admin-form">
            <div className="admin-form-row admin-form-row-3 mb-2">
              <FormField label="Zákazník">
                <div className="fw-500">
                  {invoice.customer_name || "\u2014"}
                </div>
                {invoice.customer && (
                  <div
                    className="text-tertiary"
                    style={{ fontSize: "0.8rem", marginTop: "0.2rem" }}
                  >
                    {invoice.customer.company_id &&
                      `IČ: ${invoice.customer.company_id}`}
                    {invoice.customer.vat_id &&
                      ` · DIČ: ${invoice.customer.vat_id}`}
                  </div>
                )}
              </FormField>
              <FormField label="Objednávka">
                <div>
                  {invoice.order_id ? (
                    <Link
                      to={`/orders/${invoice.order_id}`}
                      className="link-accent"
                    >
                      {invoice.order_number}
                    </Link>
                  ) : (
                    "\u2014"
                  )}
                </div>
              </FormField>
              <FormField label="Měna">
                <div>{invoice.currency}</div>
              </FormField>
            </div>
            <div className="admin-form-row admin-form-row-3 mb-2">
              <FormField label="Datum vystavení">
                <div>{formatDate(invoice.issue_date)}</div>
              </FormField>
              <FormField label="Datum splatnosti">
                <div>{formatDate(invoice.due_date)}</div>
              </FormField>
              <FormField label="DÚZP">
                <div>{formatDate(invoice.tax_date)}</div>
              </FormField>
            </div>
            <div className="admin-form-row admin-form-row-3">
              <FormField label="Forma úhrady">
                <div>{invoice.payment_method}</div>
              </FormField>
              <FormField label="Variabilní symbol">
                <div>{invoice.invoice_number}</div>
              </FormField>
              <FormField label="Vystavil">
                <div>{invoice.issued_by || "\u2014"}</div>
              </FormField>
            </div>
            {invoice.paid_date && (
              <div className="admin-form-row mt-2">
                <FormField label="Datum úhrady">
                  <div className="fw-500" style={{ color: "var(--success)" }}>
                    {formatDate(invoice.paid_date)}
                  </div>
                </FormField>
              </div>
            )}
          </div>
        </motion.div>

        {/* Items (read-only) */}
        <motion.div
          className="admin-card"
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.25, delay: 0.12 }}
        >
          <div className="admin-card-body">
            <div className="admin-card-header flex-between">
              <h3 className="admin-card-title">Položky</h3>
            </div>
            {invoice.items?.length > 0 ? (
              <div className="admin-table-responsive">
                <table className="admin-table">
                  <thead>
                    <tr>
                      <th style={{ width: "2.5rem", textAlign: "center" }}>
                        #
                      </th>
                      <th>Popis</th>
                      <th style={{ width: "5.5rem", textAlign: "center" }}>
                        Množství
                      </th>
                      <th style={{ width: "5rem", textAlign: "center" }}>
                        Jednotka
                      </th>
                      <th style={{ width: "8rem", textAlign: "right" }}>
                        Jedn. cena
                      </th>
                      <th style={{ width: "4rem", textAlign: "center" }}>
                        %DPH
                      </th>
                      <th style={{ width: "9rem", textAlign: "right" }}>
                        Celkem
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {invoice.items.map((item, index) => {
                      const lineSubtotal =
                        (Number(item.quantity) || 0) *
                        (Number(item.unit_price) || 0);
                      const lineVat = Number(invoice.apply_vat)
                        ? (lineSubtotal * (Number(item.vat_rate) || 0)) / 100
                        : 0;
                      return (
                        <tr key={item.id || index}>
                          <td className="text-tertiary text-center fw-500">
                            {index + 1}
                          </td>
                          <td className="fw-500">
                            {item.description || "\u2014"}
                          </td>
                          <td className="text-center">
                            {item.quantity}{" "}
                            {item.unit && (
                              <span className="text-tertiary">{item.unit}</span>
                            )}
                          </td>
                          <td className="text-center">
                            {item.unit || "\u2014"}
                          </td>
                          <td className="admin-mono text-right">
                            {formatCurrency(item.unit_price, invoice.currency)}
                          </td>
                          <td className="text-center">
                            {Number(invoice.apply_vat)
                              ? Number(item.vat_rate)
                              : 0}
                            %
                          </td>
                          <td className="admin-mono text-right fw-600">
                            {formatCurrency(
                              lineSubtotal + lineVat,
                              invoice.currency,
                            )}
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            ) : (
              <p className="text-tertiary">Žádné položky.</p>
            )}

            <div className="admin-totals-summary">
              <div className="admin-totals-row">
                <span>Mezisoučet:</span>
                <span>
                  {formatCurrency(createTotals.subtotal, invoice.currency)}
                </span>
              </div>
              {Number(invoice.apply_vat) > 0 &&
                Object.entries(createTotals.vatByRate).map(([rate, amount]) => (
                  <div key={rate} className="admin-totals-row">
                    <span>DPH {rate}%:</span>
                    <span>{formatCurrency(amount, invoice.currency)}</span>
                  </div>
                ))}
              <div className="admin-totals-row admin-totals-total">
                <span>Celkem k úhradě:</span>
                <span>
                  {formatCurrency(createTotals.total, invoice.currency)}
                </span>
              </div>
            </div>
          </div>
        </motion.div>

        {/* Notes (read-only) */}
        <motion.div
          className="admin-editor-section"
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.25, delay: 0.15 }}
        >
          <h3 className="admin-card-title">Veřejné poznámky na faktuře</h3>
          {notes && notes.trim() && notes !== "<p><br></p>" ? (
            <div
              dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(notes) }}
            />
          ) : (
            <p className="text-tertiary">Žádné poznámky.</p>
          )}
        </motion.div>

        {/* Delete confirm */}
        <ConfirmModal
          isOpen={deleteConfirm}
          onClose={() => setDeleteConfirm(false)}
          onConfirm={handleDelete}
          title="Smazat fakturu"
          message={`Opravdu chcete smazat fakturu "${invoice.invoice_number}"? Tato akce je nevratná.`}
          confirmText="Smazat"
          cancelText="Zrušit"
          type="danger"
          loading={deleting}
        />
      </div>
    );
  }

  // ═══════════════════════════════════════════════════════════
  // CREATE MODE + EDIT (not paid) — shared form
  // ═══════════════════════════════════════════════════════════
  return (
    <div>
      <motion.div
        className="admin-page-header"
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.25 }}
      >
        <div className="flex-row gap-4">
          <Link
            to="/invoices"
            className="admin-btn-icon"
            title="Zpět"
            aria-label="Zpět"
          >
            <svg
              width="20"
              height="20"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
            >
              <path d="M19 12H5M12 19l-7-7 7-7" />
            </svg>
          </Link>
          <div>
            {isEdit && invoice ? (
              <h1 className="admin-page-title flex-row-gap">
                Faktura {invoice.invoice_number}
                <span
                  className={`admin-badge ${STATUS_CLASSES[invoice.status] || ""}`}
                >
                  {STATUS_LABELS[invoice.status] || invoice.status}
                </span>
              </h1>
            ) : (
              <>
                <h1 className="admin-page-title">
                  Nová faktura{" "}
                  {invoiceNumber && (
                    <span className="text-tertiary">({invoiceNumber})</span>
                  )}
                </h1>
                {fromOrderId && (
                  <p className="admin-page-subtitle">Z objednávky</p>
                )}
              </>
            )}
          </div>
        </div>
        <div className="admin-page-actions">
          {isEdit && invoice && hasPermission("invoices.export") && (
            <button
              onClick={() => handleViewPdf(invoice.language || "cs")}
              className="admin-btn admin-btn-secondary"
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: "0.4rem",
              }}
              disabled={pdfLoading}
            >
              {pdfLoading ? (
                <div className="admin-spinner admin-spinner-sm" />
              ) : (
                <svg
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                >
                  <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
                  <polyline points="14 2 14 8 20 8" />
                </svg>
              )}
              Zobrazit fakturu
            </button>
          )}
          <button
            onClick={handleCreateSubmit}
            className="admin-btn admin-btn-primary"
            disabled={saving}
          >
            {saving ? (
              <>
                <div className="admin-spinner admin-spinner-sm" />
                Ukládání...
              </>
            ) : (
              "Uložit"
            )}
          </button>
          {isEdit && invoice && (
            <>
              {hasPermission("invoices.edit") &&
                invoice.valid_transitions?.map((status) => (
                  <button
                    key={status}
                    onClick={() => setStatusConfirm({ show: true, status })}
                    className={
                      TRANSITION_CLASSES[status] ||
                      "admin-btn admin-btn-secondary"
                    }
                    disabled={statusChanging === status}
                  >
                    {statusChanging === status ? (
                      <div
                        className="admin-spinner"
                        style={{ width: 14, height: 14, borderWidth: 2 }}
                      />
                    ) : (
                      TRANSITION_LABELS[status] || status
                    )}
                  </button>
                ))}
              {hasPermission("invoices.delete") && (
                <button
                  onClick={() => setDeleteConfirm(true)}
                  className="admin-btn admin-btn-primary"
                >
                  Smazat
                </button>
              )}
            </>
          )}
        </div>
      </motion.div>

      <form onSubmit={handleCreateSubmit}>
        {/* Basic info */}
        <motion.div
          className="admin-editor-section"
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.25, delay: 0.06 }}
        >
          <h3 className="admin-card-title">Základní údaje</h3>
          <div className="admin-form">
            <div className="admin-form-row admin-form-row-3">
              <FormField label="Číslo faktury">
                <input
                  type="text"
                  value={invoiceNumber}
                  readOnly
                  className="admin-form-input"
                  style={{
                    backgroundColor: "var(--bg-secondary)",
                    cursor: "default",
                  }}
                />
              </FormField>
              <FormField label="Odběratel" error={errors.customer_id} required>
                {form.customer_id ? (
                  <div className="admin-customer-selected">
                    <span>{form.customer_name}</span>
                    <button
                      type="button"
                      onClick={() =>
                        setForm((prev) => ({
                          ...prev,
                          customer_id: null,
                          customer_name: "",
                        }))
                      }
                      className="admin-btn-icon"
                      title="Odebrat zákazníka"
                    >
                      <svg
                        width="14"
                        height="14"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2"
                      >
                        <line x1="18" y1="6" x2="6" y2="18" />
                        <line x1="6" y1="6" x2="18" y2="18" />
                      </svg>
                    </button>
                  </div>
                ) : (
                  <div
                    className="admin-customer-select"
                    onClick={(e) => e.stopPropagation()}
                  >
                    <input
                      type="text"
                      value={customerSearch}
                      onChange={(e) => {
                        setCustomerSearch(e.target.value);
                        setShowCustomerDropdown(true);
                      }}
                      onFocus={() => setShowCustomerDropdown(true)}
                      className="admin-form-input"
                      placeholder="Hledat zákazníka (název, IČ, město)..."
                      autoComplete="off"
                    />
                    {showCustomerDropdown && (
                      <div className="admin-customer-dropdown">
                        {filteredCustomers.length === 0 ? (
                          <div className="admin-customer-dropdown-empty">
                            Žádní zákazníci
                          </div>
                        ) : (
                          filteredCustomers.slice(0, 10).map((c) => (
                            <div
                              key={c.id}
                              className="admin-customer-dropdown-item"
                              onMouseDown={() => selectCustomer(c)}
                            >
                              <div>{c.name}</div>
                              {(c.company_id || c.city) && (
                                <div>
                                  {c.company_id && `IČ: ${c.company_id}`}
                                  {c.city && ` · ${c.city}`}
                                </div>
                              )}
                            </div>
                          ))
                        )}
                      </div>
                    )}
                  </div>
                )}
              </FormField>
              <FormField label="Vystavil">
                <input
                  type="text"
                  value={form.issued_by}
                  className="admin-form-input"
                  readOnly
                  style={{
                    backgroundColor: "var(--bg-secondary)",
                    cursor: "default",
                  }}
                />
              </FormField>
            </div>

            <FormField label="Text fakturace (na PDF)">
              <input
                type="text"
                value={form.billing_text}
                onChange={(e) =>
                  setForm((prev) => ({
                    ...prev,
                    billing_text: e.target.value,
                  }))
                }
                className="admin-form-input"
                placeholder="Fakturujeme Vám za: (ponechte prázdné pro výchozí)"
              />
            </FormField>

            <div className="admin-form-row">
              <FormField
                label="Datum vystavení"
                error={errors.issue_date}
                required
              >
                <AdminDatePicker
                  mode="date"
                  value={form.issue_date}
                  onChange={(val: string) => {
                    setForm((prev) => ({ ...prev, issue_date: val }));
                    setErrors((prev) => ({ ...prev, issue_date: "" }));
                  }}
                />
              </FormField>
              <FormField label="Splatnost (dny)">
                <select
                  value={dueDays}
                  onChange={(e) => setDueDays(Number(e.target.value))}
                  className="admin-form-select"
                >
                  {Array.from({ length: 60 }, (_, i) => i + 1).map((n) => (
                    <option key={n} value={n}>
                      {n}
                    </option>
                  ))}
                </select>
                {form.due_date && (
                  <span className="text-tertiary text-xs mt-1">
                    Splatnost:{" "}
                    {new Date(form.due_date).toLocaleDateString("cs-CZ")}
                  </span>
                )}
              </FormField>
              <FormField label="DÚZP" error={errors.tax_date} required>
                <AdminDatePicker
                  mode="date"
                  value={form.tax_date}
                  onChange={(val: string) => {
                    setForm((prev) => ({ ...prev, tax_date: val }));
                    setErrors((prev) => ({ ...prev, tax_date: "" }));
                  }}
                />
              </FormField>
            </div>

            <div className="admin-form-row admin-form-row-3">
              <FormField label="Forma úhrady">
                <select
                  value={form.payment_method}
                  onChange={(e) =>
                    setForm((prev) => ({
                      ...prev,
                      payment_method: e.target.value,
                    }))
                  }
                  className="admin-form-select"
                >
                  <option value="Příkazem">Příkazem</option>
                  <option value="Hotově">Hotově</option>
                  <option value="Dobírka">Dobírka</option>
                </select>
              </FormField>
              <FormField label="Měna">
                <select
                  value={form.currency}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, currency: e.target.value }))
                  }
                  className="admin-form-select"
                >
                  {(
                    companySettings?.available_currencies || [
                      "CZK",
                      "EUR",
                      "USD",
                      "GBP",
                    ]
                  ).map((c) => (
                    <option key={c} value={c}>
                      {c}
                    </option>
                  ))}
                </select>
              </FormField>
              <FormField label="Jazyk faktury">
                <select
                  value={form.language}
                  onChange={(e) =>
                    setForm((prev) => ({
                      ...prev,
                      language: e.target.value,
                    }))
                  }
                  className="admin-form-select"
                >
                  <option value="cs">Čeština</option>
                  <option value="en">English</option>
                </select>
              </FormField>
              <FormField label="DPH">
                <div className="flex-row-gap">
                  <label className="admin-form-checkbox whitespace-nowrap">
                    <input
                      type="checkbox"
                      checked={!!form.apply_vat}
                      onChange={(e) =>
                        setForm((prev) => ({
                          ...prev,
                          apply_vat: e.target.checked ? 1 : 0,
                        }))
                      }
                    />
                    <span>Uplatnit DPH</span>
                  </label>
                </div>
              </FormField>
            </div>

            <FormField
              label="Bankovní účet"
              error={errors.bank_account_id}
              required
            >
              <select
                value={form.bank_account_id}
                onChange={(e) => {
                  selectBankAccount(e.target.value);
                  setErrors((prev) => ({ ...prev, bank_account_id: "" }));
                }}
                className="admin-form-select"
              >
                <option value="">
                  {"\u2014"} Vyberte účet {"\u2014"}
                </option>
                {bankAccounts.map((acc) => (
                  <option key={acc.id} value={acc.id}>
                    {acc.account_name}
                    {acc.account_number ? ` (${acc.account_number})` : ""}
                    {acc.is_default ? " \u2605" : ""}
                  </option>
                ))}
              </select>
            </FormField>
          </div>
        </motion.div>

        {/* Items */}
        <motion.div
          className="admin-card"
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.25, delay: 0.12 }}
        >
          <div className="admin-card-body">
            <div className="admin-card-header flex-between">
              <div>
                <h3 className="admin-card-title">Položky</h3>
                {errors.items && (
                  <span className="admin-form-error">{errors.items}</span>
                )}
              </div>
              <button
                type="button"
                onClick={addItem}
                className="admin-btn admin-btn-secondary admin-btn-sm"
              >
                + Přidat položku
              </button>
            </div>

            <DndContext
              sensors={dndSensors}
              collisionDetection={closestCenter}
              modifiers={[restrictToVerticalAxis, restrictToParentElement]}
              onDragEnd={handleCreateDragEnd}
            >
              <SortableContext
                items={items.map((i) => i._key)}
                strategy={verticalListSortingStrategy}
              >
                <div className="admin-table-responsive">
                  <table className="admin-table">
                    <thead>
                      <tr>
                        <th style={{ width: "2rem" }} />
                        <th style={{ width: "2rem", textAlign: "center" }}>
                          #
                        </th>
                        <th>Popis</th>
                        <th style={{ width: "5.5rem", textAlign: "center" }}>
                          Množství
                        </th>
                        <th style={{ width: "5.5rem", textAlign: "center" }}>
                          Jednotka
                        </th>
                        <th style={{ width: "5.5rem", textAlign: "center" }}>
                          Jedn. cena
                        </th>
                        {form.apply_vat ? (
                          <th style={{ width: "5rem", textAlign: "center" }}>
                            DPH
                          </th>
                        ) : null}
                        <th style={{ width: "8rem", textAlign: "right" }}>
                          Celkem
                        </th>
                        <th style={{ width: "2.5rem" }}></th>
                      </tr>
                    </thead>
                    <tbody>
                      {items.map((item, index) => (
                        <SortableInvoiceRow
                          key={item._key}
                          item={item}
                          index={index}
                          currency={form.currency}
                          apply_vat={!!form.apply_vat}
                          vatOptions={vatOptions}
                          onUpdate={updateItem}
                          onRemove={removeItem}
                          canDelete={items.length > 1}
                        />
                      ))}
                    </tbody>
                  </table>
                </div>
              </SortableContext>
            </DndContext>

            {/* Totals */}
            <div className="admin-totals-summary">
              <div className="admin-totals-row">
                <span>Mezisoučet:</span>
                <span>
                  {formatCurrency(createTotals.subtotal, form.currency)}
                </span>
              </div>
              {form.apply_vat &&
                Object.entries(createTotals.vatByRate).map(([rate, amount]) => (
                  <div key={rate} className="admin-totals-row">
                    <span>DPH {rate}%:</span>
                    <span>{formatCurrency(amount, form.currency)}</span>
                  </div>
                ))}
              <div className="admin-totals-row admin-totals-total">
                <span>Celkem k úhradě:</span>
                <span>{formatCurrency(createTotals.total, form.currency)}</span>
              </div>
            </div>
          </div>
        </motion.div>

        {/* Notes */}
        <motion.div
          className="admin-editor-section"
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.25, delay: 0.15 }}
        >
          <h3 className="admin-card-title">Veřejné poznámky na faktuře</h3>
          <textarea
            className="admin-form-input"
            rows={4}
            value={form.notes}
            onChange={(e) =>
              setForm((prev) => ({ ...prev, notes: e.target.value }))
            }
            placeholder="Poznámky zobrazené na faktuře..."
          />
        </motion.div>
      </form>

      {/* Status change confirm (edit mode only) */}
      {isEdit && invoice && (
        <>
          <ConfirmModal
            isOpen={statusConfirm.show}
            onClose={() => setStatusConfirm({ show: false, status: null })}
            onConfirm={handleStatusChange}
            title="Změnit stav faktury"
            message={`Opravdu chcete změnit stav faktury "${invoice.invoice_number}" na "${STATUS_LABELS[statusConfirm.status || ""]}"?`}
            confirmText={
              TRANSITION_LABELS[statusConfirm.status || ""] || "Potvrdit"
            }
            cancelText="Zrušit"
            type="default"
          />

          <ConfirmModal
            isOpen={deleteConfirm}
            onClose={() => setDeleteConfirm(false)}
            onConfirm={handleDelete}
            title="Smazat fakturu"
            message={`Opravdu chcete smazat fakturu "${invoice.invoice_number}"? Tato akce je nevratná.`}
            confirmText="Smazat"
            cancelText="Zrušit"
            type="danger"
            loading={deleting}
          />
        </>
      )}
    </div>
  );
}
